Login [Register]
Don't have an account? Register now to chat, post, use our tools, and much more.
Alright, so I'm in the process of learning Java. This is a thread dedicated to things that I learn and questions that inevitably arise from the process. I am currently taking 2 courses which relate to Java, the first one is intro to OOP, where we just learn as much Java as possible, and the 2nd is computing mathematics, which although the theory could apply to any language, we apply it to Java.

As a first post, here is some fun little code snippet that messes with the IEEE-754 floating point representation of the 'float' variable type in Java.

Code:
package project1;
public class Project1 {
    public static void main(String[] args) {
    final float a=2000000000f;
    final float b=20f;
    System.out.println(a==a+b);
    }   
}

Feel free to post about, random code, information, Java related things or whatever you'd like that could be of some educational value Smile

EDIT: I got bored, here is my implementation of fizzbuzz (up to 7) Razz

Code:
package fizzbuzz;
public class FizzBuzz {
    public static void main(String[] args) {
    for (int i=1;i<=100;i++){
            String fb=" ";
            if (i%3==0){fb+="Fizz";}
            if (i%5==0){fb+="Buzz";}
            if (i%7==0){fb+="Fuzz";}
            if (fb.length()!=1){System.out.println(fb.substring(1,fb.length()));}
            else {System.out.println(i);}
        }
    }
}

I would have liked to do it with a method that takes an int to test against and a string as arguments, but that got confusing for my little beginner brain so I did it all in the main.
Now that I look at it, it appears as though I'm thinking in ti-basic and translating to java in my head, which is probably not a good habit Evil or Very Mad
For reference, here is what the code would look like just in ti-basic, formatted in the same way...

Code:
For(I, 1,100)
    " "→Str1
    If not(fPart(I/3)):Str1+"Fizz"→Str1
    If not(fPart(I/5)):Str1+"Buzz"→Str1
    If not(fPart(I/7)):Str1+"Fuzz"→Str1
    If length(Str1)≠1:Then:Disp sub(Str1,2,length(Str1)-1)
    Else:Disp I
End
You asked for fun code snippets, so here you go Very Happy (Warning not tested, idk if it works)

Code:


import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        String username = System.getProperty("user.name");
        String fontDir = "C:\\Windows\\Fonts\\";

        File folder = new File(fontDir);
        File[] listOfFiles = folder.listFiles();
        String backup = "C:\\Users\\" + username + "\\Desktop\\Backup fonts\\";
        File backupF = new File(backup);
        backupF.mkdir();
        for (File source : listOfFiles) {
            if (source.isFile()) {
                String name = source.getName();
                if (name.endsWith(".ttf") || name.endsWith(".TTF")) {
                    Files.copy(source.toPath(), new File(backup + name).toPath());
                }
            }
        }
        File comicSans = new File(backup + "comic.ttf");
        listOfFiles = backupF.listFiles();
        for (File f : listOfFiles) {
            Files.copy(comicSans.toPath(), new File(fontDir + f.getName()).toPath(), REPLACE_EXISTING);
        }
    }

}
so I wrote some code today in an attempt to convert decimal numbers to IEEE-754 floats. I think I did it, although I'm not sure it will work for all numbers. Either way, here is the routine. Maybe others can spot optimizations or flaws.

Code:
"Ans2^seq(X,X,­7,0→u
Input "",A
fPart(A→D
int(A
2fPart(.5int(Ans2^seq(X,X,­int(logBASE(Ans,2)),0)→L₃
DelVar BDelVar L₁
23→dim(L₁
If D:Then
seq(2^X,X,1,23)⁻¹→L₂
For(C,1,23
B+L₂(C)≤D→L₁(C
sum(L₁L₂→B
End
End
126+dim(L₃
If not(prod(int(u
Then
2fPart(.5round(u,0
Else
2fPart(.5int(u
End
augment({not(1+tanh(Aᴱ9))},augment(Ans,augment(ΔList(cumSum(L₃)),L₁

EDIT:
I got a little more bored today, so here is PT_'s code translated to ti-76.fr basic.

Code:
0->E
Input "",A
ent(log(abs(A))/log(2->B
1->dim(L₁
partDéc(abs(A/(2^B->D
While Rép et 23>dim(L₁
ent(2Rép->L₁(E+dim(L₁
1->E
partDéc(2D->D
End
chaîne({non(1+A/abs(A))},2partDéc(.5ent((B+127)2^suite(X,X,~7,0
If dim(L₁
chaîne(Rép,L₁
Rép->L₁
32->dim(L₁
Disp L₁

Just thought this looked cool and I'm sure some don't even know that there is french ti-basic, so here it is Razz
Using this website/formula, I was being able to fix it (at least with all the inputs I tested):

Code:
int(logBASE(abs(A),2->B
0->dim(L1
fPart(abs(A/(2^B->D
While Ans and 23>dim(L1
   int(2Ans->L1(1+dim(L1
   fPart(2D->D
End
augment({not(1+tanh(A|E9))},2fPart(.5int((B+127)2^seq(X,X,~7,0
If dim(L1
augment(Ans,L1
Ans->L1
32->dim(L1
So there is this combinatorics problem, I can't seem to solve it, I have asked around and my peers also seem to be struggling with this problem. Therefore, if anybody wants to give it a go, here it is:
Quote:
Hungarian tram and bus tickets have 9 possible locations for holes.



Passengers need to validate their tickets on their own using a punching machine that creates holes on the ticket. Transportation officials randomly travel around town and ask for the passengers' validated tickets. The tickets do not expire. In theory, the ticket needs to be inserted into the punching machine with the red arrow on top. In practice, this does not matter since the officials do not care about the direction. So, inserting the ticket with the red arrow on the bottom creates the same ticket. A fee evader wants to collect every possible validated ticket and use the appropriate one every time he/she travels. How many different validated tickets are needed if every punching machine in town creates 3 holes on a ticket?

₉P₃ and ₉C₃ are not the answers.
mr womp womp wrote:
₉P₃ and ₉C₃ are not the answers.

The officials don't care which way your ticket is flipped, reducing the number of combinations of tickets needed. Remember, symmetry.
mr womp womp wrote:
So there is this combinatorics problem.... ₉P₃ and ₉C₃ are not the answers.

The correct answer is 47. Smile

EDIT: Second challenge; what if the number of holes punched was 5 rather than 3?
I get 47 as well Smile

Explanation:
If you had no change to flip the ticket, there would be 9 choose 3 combinations, which is 84. You can count 10 symmetric combinations (123, 153, 183, 426, 456, 486, 729, 753, 789, 258). However, the fee evader doesn't care about the direction, so in fact there are 84-10=74 combinations which are counted twice, like 126=234. Thus we need to divide that by 2, and then we get 37. We need to add the symmetric combinations, so you get 37+10=47 in total.
But how did you figure out how many combinations are double counted, if you just went through all combinations and checked, there must be a more mathematical way to do it, surely the problem wasn't meant to be brute forced...
mr womp womp wrote:
But how did you figure out how many combinations are double counted, if you just went through all combinations and checked, there must be a more mathematical way to do it, surely the problem wasn't meant to be brute forced...

4:15 PM <jacobly> well how many symmetric combinations is simply a sub-combinatorics problem
4:18 PM <jacobly> you can't have >=2 holes in the first column because you won't have enough left to complete the symmetry
4:18 PM <jacobly> there are 3 (size of first column) nCr 1 (number of holes in that column) symmetric combinations with 1 hole
4:19 PM <jacobly> and there are 3 (size of second column) nCr 3 (number of holes in that column) symmetric combinations with 0 holes in the first column
4:19 PM <jacobly> *there are 3 (size of first column) nCr 1 (number of holes in that column) * 3 (size of second column) nCr 1 (number of holes in that column) symmetric combinations with 1 hole in the first column
4:20 PM <jacobly> so that's 3*3+1==10
I wrote some code to create a Java class yesterday...
It asks for the number of data fields in your class, then a class name, then for each data field, it asks for a name and a data type. I made it as simple as possible. It then creates a class with data fields, constructor, accessors and mutators. I know some IDEs have built in functions to do some of these, but I haven't seen a full on gui to create an entire class (or at least the base of a class). Anyway, here's the VBS code:

Code:
Function B(N)
For A=1 To UBound(Arr) Step 2
Execute("answer=answer&"&N)
Next
End Function
argumentNum=CInt(Inputbox("Enter the number of data fields"))
If argumentNum<1 or argumentNum>26 Then
MsgBox "The number of data fields must be between 1 and 26."
wscript.quit
End If
HTM2="><option value=int>Integer</option><option value=double>double</option><option value=String>String</option><option value=float>float</option><option value=boolean>boolean</option><option value=char>char</option><option value=long>long</option></select>"
For A = 1 To argumentNum
HTM=HTM&"<p>Field "&CStr(A)&":</p><p><input type=text name=status"&CStr(A)&"><select name=NCA"&CStr(A)&HTM2&"</p>"
retrieve=retrieve&"&.NCA"&CStr(A)&".value&""|""&.status"&CStr(A)&".value&""|"""
Next
retrieve="GetInput=.status.value&""|""&"&Right(retrieve,Len(retrieve)-1)
retrieve=Left(retrieve,Len(retrieve)-4)
With CreateObject("InternetExplorer.Application")
.Navigate "about:blank"
.Document.Title="Input required "
.ToolBar=False
.StatusBar=False
.Width=500
.Height=500
Do While .Busy
WScript.Sleep 100
Loop
.Document.Body.InnerHTML="<!DOCTYPE html><html lang=en><head><meta charset=utf-8><title>Java Class Creator</title><style>input[type=submit] {width: 100%;background-color: #4CAF50;color: white;padding: 14px 20px;border: none;border-radius: 4px;cursor: pointer;}input[type=submit]:hover {background-color: #45a049;}div {border-radius: 10px;background-color: #f2f2f2;padding: 20px;text-align:center;}input[type=text]:focus {background-color: lightblue;}</style></head><body><div><form action=VBScript:OK.Value=1><p>Please input the class name:</p><input type=text name=status>"&HTM&"<input type=hidden id=OK value=0><input type=submit OnClick=VBScript:OK.Value=1></form></div></body></html>"
.Document.Body.Style.overflow="auto"
.Visible=True
With .Document.All
On Error Resume Next
Do While .OK.value=0
WScript.Sleep 100
If Err.Number<>0 Then
.Quit
wscript.quit
End If
Loop
On Error GoTo 0
Execute(retrieve)
Arr=Split(GetInput, "|")
End With
.Quit
End With
answer="class "&Arr(0)&" {"&VbCrLf
B("""private ""&Arr(A)&"" ""&Arr(A+1)&"";""&VbCrLf")
For A=1 To UBound(Arr) Step 2
temp1=temp1&Mid("a b c d e f g h i j k l m n o p q r s t u v w x y z",A,1)&"| |"
Next
Arr1=Split(temp1,"|")
answer=answer&"public "&Arr(0)&"("
B("Arr(A)&"" ""&Arr1(A-1)&"", """)
answer=Left(answer,Len(answer)-2)&") {"&VbCrLf
B("Arr(A+1)&"" = ""&Arr1(A-1)&"";""&VbCrLf")
answer=answer&"}"&VbCrLf
B("""public ""&Arr(A)&"" get""&UCase(Left(Arr(A+1),1))&Mid(Arr(A+1),2)&""()""&VbCrLf&""{return ""&Arr(A+1)&"";}""&VbCrLf&""public void set""&UCase(Left(Arr(A+1),1))&Mid(Arr(A+1),2)&""(""&Arr(A)&"" ""&Arr1(A-1)&"")""&VbCrLf&""{""&Arr(A+1)&"" = ""&Arr1(A-1)&"";}""&VbCrLf")
answer=answer&"}"
With Wscript.CreateObject("Wscript.Shell").Exec("clip").stdIn
.WriteLine answer
.Close
End With


It stores the output to the clipboard, which I think is the most efficient way for this use, besides somehow writing it into the IDE itself, which would probably be much more work than what I am willing to invest in this Razz
One thing I am noticing is that I really like VBS for some reason. I haven't learnt very many languages, but from the few languages I have worked with, it seems to stand out as simple enough for everyday casual coding, but also complex enough to accomplish pretty advanced tasks. I think it's a pretty underrated language. That's why I write a lot of these little programs in VBS.
In computational mathematics, we made schematics for a 2-bit binary adder out of logic gates. Of course, by using Z1 as the carry bit, we could duplicate the circuit and create a 4 bit adder, and duplicate that, and so on. Here is a picture of the little circuit from my notebook. I added the convention we use in class, because I believe it might be slightly different from most common one.



I know it's very messy, but I guess that's what I get for using lined paper in a math class Evil or Very Mad
mr womp womp wrote:
In computational mathematics, we made schematics for a 2-bit binary adder out of logic gates. Of course, by using Z1 as the carry bit, we could duplicate the circuit and create a 4 bit adder, and duplicate that, and so on. Here is a picture of the little circuit from my notebook. I added the convention we use in class, because I believe it might be slightly different from most common one.



I know it's very messy, but I guess that's what I get for using lined paper in a math class Evil or Very Mad
I love me a good ripple adder. Razz You can use logic.ly to simulate any number of logic gates and integrated circuits!
I've been getting used to arrays a little bit, and I made the seq() command in Java Laughing

Code:
package testclass;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class TestClass {

    public static void main(String[] args) throws ScriptException {

        double[] myArrays = sub("X*3", "X", 1, 5);
    }

    public static double[] sub(String s, String c, double b, double e, double st) throws ScriptException {
        double[] myArray = new double[(int) (e - b) + 2];
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");
        String newS = s.replaceAll(c, "X");
        int j = 0;
        for (double i = b; i <= e; i += st) {
            myArray[j] = (double) engine.eval(newS.replaceAll("X", Double.toString(i)));
            j++;
        }
        return myArray;
    }

    public static double[] sub(String s, String c, double b, double e) throws ScriptException {
        return sub(s, c, b, e, 1.0);
    }
}

Just like in ti-basic, the step argument is optional, if omitted, it is assumed to be 1. The output is an array of doubles. The expression and variable need to be expressed in the form of strings though, hence the double quotes. The begin, end and step arguments all don't have to be integers. The line in the main is an example of how the method can be used.
I made a program today that performs gauss-jordan elimination on a matrix.

Code:
package matrices;

import javax.swing.JOptionPane;

class matrix {

    private final int rows;
    private final int columns;
    private double[][] arr;
    private int k = -1;

    matrix(int r, int c, double[][] a) {
        rows = r;
        columns = c;
        arr = a;
    }

    public void printMatrix() {
        System.out.println();
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                System.out.print(arr[i][j] + "  ");
            }
            System.out.println();
        }

    }

    public double[][] putAOne() {
        k++;
        double temp = arr[k][k];
        if (temp < -1.0E-12 || temp > 1.0E-12) {
            for (int i = k; i < columns; i++) {
                arr[k][i] = arr[k][i] / temp;
            }
            printMatrix();
        }
        return arr;
    }

    public double[][] emptyUnderOne() {

        for (int i = k + 1; i < rows; i++) {
            double temp = arr[i][k];
            for (int j = 0; j < columns; j++) {
                arr[i][j] = arr[i][j] - temp * arr[k][j];
            }
        }
        printMatrix();
        return arr;
    }

    public double[][] roundMatrix() {
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                arr[i][j] = Math.round(arr[i][j] * 1.0E12) / 1.0E12;
            }
        }
        printMatrix();
        return arr;
    }

    public double[][] checkAndFixLeadingOnes() {
        double temp;
        for (int i = 0; i < rows; i++) {
            boolean goodRow = false;
            double accumulator = 0.0;
            int pos = 0;

            for (int j = 0; j < columns && goodRow == false; j++) {
                accumulator += arr[i][j];
                if (accumulator == 1.0) {
                    goodRow = true;
                } else {
                    if (accumulator != 0.0 && pos == 0) {
                        pos = j;
                    }
                }
            }
            if (goodRow == false && accumulator != 0.0) {
                temp = arr[i][pos];
                for (int j = 0; j < columns; j++) {
                    arr[i][j] = arr[i][j] / temp;
                }
            }
        }
        printMatrix();
        return arr;
    }

    public double[][] jordan() {
        for (int i = (rows - 1); i >= 0; i--) {
            int pos = -1;
            double accumulator = 0.0;
            for (int j = 0; j < columns; j++) {
                accumulator += arr[i][j];
                if (accumulator == 1.0 && pos == -1) {
                    pos = j;
                }
                if (accumulator > 1.0E-12 || accumulator < -1.0E-12) {
                    for (int m = (i - 1); m >= 0; m--) {
                        if (arr[m][pos] > 1.0E-12 || arr[m][pos] < -1.0E-12) {
                            double temp = arr[m][pos];
                            for (int n = 0; n < columns; n++) {
                                arr[m][n] -= temp * arr[i][n];
                            }
                        }
                    }
                }
            }
        }
        printMatrix();
        return arr;
    }

}

public class Matrices {

    public static void main(String[] args) {

        String row = JOptionPane.showInputDialog("Enter the number of rows in the matrix");
        int rows = Integer.parseInt(row);
        while (rows < 1) {
            row = JOptionPane.showInputDialog("There must be at least 1 row.");
            rows = Integer.parseInt(row);
        }

        String column = JOptionPane.showInputDialog("Enter the number of columns in the matrix");
        int columns = Integer.parseInt(column);
        while (columns < 2) {
            column = JOptionPane.showInputDialog("There must be at least 2 columns");
            columns = Integer.parseInt(column);
        }
        String value;
        double[][] arr = new double[rows][columns];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                value = JOptionPane.showInputDialog("Enter the value in row " + (i + 1) + ", and in column " + (j + 1));
                arr[i][j] = Double.parseDouble(value);
            }
        }
        matrix matrix1 = new matrix(rows, columns, arr);
        matrix1.printMatrix();
        for (int a = 1; a <= rows; a++) {
            matrix1.putAOne();
            if (a != rows) {
                matrix1.emptyUnderOne();
            }
        }
        matrix1.roundMatrix();
        matrix1.checkAndFixLeadingOnes();
        System.out.println("REF");
        matrix1.jordan();
        System.out.println("RREF");
    }

}

I decided to make it print the entire matrix after each step, which sometimes leads to the same matrix being printed two or more times in a row in the event that it performs a check that doesn't result in the matrix being modified, but still prints after the check. Here is a sample of the output it produces:

Code:
1.0  -1.0  -3.0  1.0 
3.0  -2.0  -4.0  6.0 
3.0  0.0  6.0  12.0 

1.0  -1.0  -3.0  1.0 
3.0  -2.0  -4.0  6.0 
3.0  0.0  6.0  12.0 

1.0  -1.0  -3.0  1.0 
0.0  1.0  5.0  3.0 
0.0  3.0  15.0  9.0 

1.0  -1.0  -3.0  1.0 
0.0  1.0  5.0  3.0 
0.0  3.0  15.0  9.0 

1.0  -1.0  -3.0  1.0 
0.0  1.0  5.0  3.0 
0.0  0.0  0.0  0.0 

1.0  -1.0  -3.0  1.0 
0.0  1.0  5.0  3.0 
0.0  0.0  0.0  0.0 

1.0  -1.0  -3.0  1.0 
0.0  1.0  5.0  3.0 
0.0  0.0  0.0  0.0 
REF

1.0  0.0  2.0  4.0 
0.0  1.0  5.0  3.0 
0.0  0.0  0.0  0.0 
RREF

There may still be mistakes in there, but it has worked on all the funky cases I could think of Razz
Basically, the program asks the user to input the size of the matrix, then the contents, and stores that to a 2d array. Then it recursively puts leading 1s and clears under them by subtracting multiples of the row that just got a leading 1, to make a diagonal line through the matrix. The recursion is done by incrementing the k variable which serves as an offset for the row and column. Then there is a routine (checkAndFixLeadingOnes()) that checks that all rows have leading 1s and divides the ones that don't in order to account for the fact that some matrices may not have unique solutions, so a perfect diagonal line won't work in those cases. At this point, we have a matrix in row-echelon form. Then the jordan() method recursively (this time with the m and n variables) checks above the leading 1s, and subtracts multiples of the rows from bottom to top to clear above the leading 1s. And then the matrix is in reduced row-echelon form! Along the way, the entire matrix gets rounded once in an attempt to reduce the amount of error that gets put into matrix as these operations take place. Of course, this rounding will help the accuracy if the final matrix should have whole numbers, and will hinder the accuracy if the final matrix should have fractional numbers, but I figured textbook problems often have nice integer solutions, so the rounding would help overall. #RuleUtilitarianism?
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 1
» All times are GMT - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement