i am new in java programming.I need to convert my matlab code to basic java codes not complex like just using loops and array, i tried several times but i failed.Thanks for helping.Here is my code.
x = [1,2,3,4,5,6,7];
x = perms(x);
i = 0;
c=1;
for m=1:1:5040;
for n=1:1:6;
if(x(c,n) == (x(c,(n+1))-1))
i = i+1;
break
end
end
c=c+1;
end
Answer : 2119
Let us go through the Matlab code and translate each row into Java. We will be going to need some abstractions, which we will introduce on the go.
First line:
x = [1,2,3,4,5,6,7];
A vector is assigned to a variable x. We could simply say that a vector is an array of integers, but maybe we need some better abstractions later. Let us define a new class Vector. Do not confuse it with java.util.Vector: There may be multiple classes of the same unqualified name.
class Vector {
private int[] value;
Vector(int... value) {
this.value = value;
}
int apply(int i) {
return value[i - 1];
}
int length() {
return value.length;
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
String prefix = "";
for (int entry : value) {
result.append(prefix).append(entry);
prefix = " ";
}
return result.toString();
}
}
We are using an array of integers for the internal representation of our Vector. Note that you can swap out the internal representation any time as long as it does not leak out into the classe's interface. Hence, we restrict the access of our value-member to private, meaning only objects of type Vector are allowed to access it.
New Vector objects are instantiated by calling the constructor Vector(int... value), which takes a vararg integer argument. Internally in Java, varargs are the same as arrays, but they give us syntactic sugar, to instantiate our x in the following way:
Vector x = new Vector(1, 2, 3, 4, 5, 6, 7);
which looks very similar to your Matlab code.
An other thing is that, in Java, arrays are zero-indexed, while Matlab starts indexing at 1. Our Vector class defines an apply-method, which is supposed to access the i-th index. Hence, it returns value[i-1].
Now we want to compute
x = perms(x);
perms returns a matrix, containing all permutations of vector x. So we need an other abstraction: Matrix.
class Matrix {
private Vector[] rows;
Matrix(Vector... value) {
this.rows = value;
}
int apply(int x, int y) {
return rows[x - 1].apply(y);
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
String prefix = "";
for (Vector row : rows) {
result.append(prefix).append(row.toString());
prefix = System.lineSeparator();
}
return result.toString();
}
}
Matrix is defined very similar to Vector, but its internal representation is an array of Vector, the rows of the matrix. Again, we define a method apply to retrieve an element: this time, it takes two parameters, the row index and the column index.
Side note: It is always good to override the method toString which is defined in the top element of Java's type hierarchy: Object. You can try to instantiate a Vector or a Matrix and pass it as argument to System.out.println to see how the string representation looks like.
Now we still need to implement perms in Java. The method perms takes a Vector and returns a Matrix. I have a very hacked and ugly implementation which I am a bit reluctant to show, but for the sake of a complete answer, here it is:
static Matrix perms(Vector vector) {
int[] indices = new int[vector.length()];
for (int i = 0; i < vector.length(); i++)
indices[i] = i;
List<int[]> allPermuationIndices = new ArrayList<int[]>();
permutation(new int[0], indices, allPermuationIndices);
Vector[] perms = new Vector[allPermuationIndices.size()];
for (int i = 0; i < perms.length; i++) {
int[] permutationIndices = allPermuationIndices.get(i);
int[] vectorValue = new int[permutationIndices.length];
for (int j = 0; j < permutationIndices.length; j++)
vectorValue[j] = vector.apply(permutationIndices[j] + 1);
perms[i] = new Vector(vectorValue);
}
return new Matrix(perms);
}
private static void permutation(int[] prefix, int[] remaining, List<int[]> returnValue) {
if (remaining.length == 0)
returnValue.add(prefix);
else {
for (int i = 0; i < remaining.length; i++) {
int elem = remaining[i];
int[] newPrefix = Arrays.copyOf(prefix, prefix.length + 1);
newPrefix[prefix.length] = elem;
int[] newRemaining = new int[remaining.length - 1];
System.arraycopy(remaining, 0, newRemaining, 0, i);
System.arraycopy(remaining, i + 1, newRemaining, i + 1 - 1, remaining.length - (i + 1));
permutation(newPrefix, newRemaining, returnValue);
}
}
}
Don't bother to understand what it is doing. Try writing a clean implementation on your own (or google for a solution).
Now, if we want to reassign our x, we run into trouble: The type does not match: We declared x to be of type Vector, but perm is returning a Matrix. There are multiple ways to solve this:
We could declare Vector to be a Matrix, i.e., change the signature to Vector extends Matrix. This solution may make sense, but be careful not to break behavioral subtyping: If a class B is a class A, then B must have the same behavior as A and can define additional behavior. Look up the Liskov Substitution Principle on the same note.
We could declare x to be of a supertype of both, Vector and Matrix. Currently, this is Object, but we could also define a new common supertype. This solution may however lose our static type safety. For example, if we want to use x as argument to perm, we need to dynamically cast it to a Vector
We could define a second variable x2 of type Matrix which holds the result. I suggest this solution in this case.
Next, we assign i = 0; and c=1;, which in Java translates to
int i = 0;
int c = 1;
Now, the for-loops:
for m = 1:1:5040
...
end
translates to
for (int m = 1; m <= 5040; i++) {
...
}
The only thing remaining, besides putting it all together, is the if-statement:
if(x2(c,n) == (x2(c,(n+1))-1))
...
end
translates to
if (x2.apply(c, n) == (x2.apply(c, n+1) - 1)) {
...
}
where apply is the method we defined on Matrix. Note that in Java, == will give you strange results if applied to non-primitive types, i.e., everything besides int, byte, char, double, boolean, and float. Generally, you test equivalence using the method equals which is defined on Object.
Related
I am working on a project where I need to push elements into Array. I made a function as follow to push value inside array:
public float[] insertFloatIntoArray(float[] arr, float val) {
float newarr[] = new float[arr.length + 1];
for (int i = 0; i < arr.length; i++) {
newarr[i] = arr[i];
}
newarr[arr.length] = val;
return newarr;
}
But is there any way to make it generic so that if I provide an Array of any data type with value of same datatype and return new array of same datatype. doing so can make me avoid replica of code and function for various data types.
You do not need to return an array because arrays are based on pointers ,and whenever you change an array in a method , it will also affect to the array in main or in the location that you sent.
public void insertFloatIntoArray(float[] arr, float val) {
float newarr[] = new float[arr.length + 1];
for (int i = 0; i < arr.length; i++) {
newarr[i] = arr[i];
}
newarr[arr.length] = val;
}
This is the functionality that you desire.
Lastly , If you have two arrays.You can send both as parameters ,so it will be way easier than what you try.
You can do something loke this:
public <T extends Number> T[] insertFloatIntoArray(Class<T> clazz, T[] arr, T val) {
T newarr[] = (T[]) Array.newInstance(clazz, arr.length + 1);
for (int i = 0; i < arr.length; i++) {
newarr[i] = arr[i];
}
newarr[arr.length] = val;
return newarr;
}
but in this case you must use object wrap of numper types (Float instead float, Integer instead int etc)
insertFloatIntoArray(Integer.class, <old array>, <int or Integer value>);
insertFloatIntoArray(Float.class, <old array>, <float or Float value>);
array content class you can get by this code:
Class componentType = arr.getClass().getComponentType();
After all I think you should use ArrayList for this
I'm not going to say that this is a good idea... And you lose type safety so may well run into lots of errors when calling it... But this can be done for primitives and non-primitives alike using the Array class:
public static <T> T insertAtEnd(final T array, final Object toAppend) {
// Find the type of the provided array
final Class<?> klass = array.getClass().getComponentType();
final int arrayLength = Array.getLength(array);
// Create a new array with the provided type, but with one more length.
final Object newArray = Array.newInstance(klass, arrayLength + 1);
// Copy the old array's contents into the first elements of the new array.
System.arraycopy(array, 0, newArray, 0, arrayLength);
// Set the final element of the array to the given value.
Array.set(newArray, arrayLength, toAppend);
return (T) newArray;
}
(Note the generic is only used to avoid the caller having to cast the array back at the end... If you replace T with Object this works completely without generics as well.)
You should consider using an ArrayList if you need to add new elements to it. Then you can just call the add method on it. If you need atomic types like int, float, etc... Use the wrapper classes Integer, Float for them.
I have to get an float[] array from an TockaXY[] array.
Example of TockaXY[] with 4 elements:
[60.039005,86.44917][96.53153,41.086178][19.988914,31.67395][96.84925,41.90731]
but I need an float[]. Tried:
for (int i = 0; i < objectArray.length; i++)
floatArray[i] = (Float)objectArray[i];
But I get error cannot Cast.
Any Ideas?
If i understood it right, you have an array within an array.
if you want to keep it this way than you have to create another array within an array
so;
float floatArray[][]; //declare a 2D array
floatArray = new float[4][2]; //make it's length same as yours
for (int i = 0; i < objectArray.length; i++){
for(int j =0; j<objectArray[i].length; j++){
//parse each value as float, and assign it to your new array
floatArray[i][j] = Float.parseFloat(objectArray[i][j]);
}
}
First of all your given element is not array, its array of array.
You can try this to convert Object[][] to Float[][].
Object[][] objectArray = { { 60.039005, 86.44917 }, { 96.53153, 41.086178 }, { 19.988914, 31.67 },
{ 96.84925, 41.90731 } };
Float[][] floatArray = new Float[objectArray.length][2];
for (int i = 0; i < objectArray.length; i++) {
floatArray[i][0] = ((Double) objectArray[i][0]).floatValue();
floatArray[i][1] = ((Double) objectArray[i][0]).floatValue();
}
System.out.println(floatArray);
Assuming TockaXY is something like
public sclass TockaXY {
private float x;
private float y;
//Constructors, getters, setters etc.
#Override
public String toString() {
return "["+ x + ", " + y + "]";
}
}
and you want a float[] containing the values of x and y from each element of a TockaXY[], the size of the float[] must be 2 * size of TockaXY[].
float [] floatArray = new float[objectArray.length * 2];
for (int i = 0, j=0; i < objectArray.length; i++) {
floatArray[j++] = objectArray[i].getX();
floatArray[j++] = objectArray[i].getY();
}
This: (SomeType) someExpr; is called a cast operation. Unfortunately, there are 3 completely different things that java can do, that all look exactly like this. A real guns and grandmas situation!
Casts can convert things, or can assert generics in types, or can coerce types itself. The latter two, at runtime, do nothing (maybe throw ClassCastException), it's just ways to tell the compiler you know what you are doing; to treat things as different types.
The ONLY one that converts anything is the 'type conversion' mode, and that one only kicks in if both the type in the parentheses and the expression you're applying it on are primitive (auto-unboxing may kick in, but it ends there).
Float is not primitive (float is primitive), so you're not doing a type conversion here, but your question makes it sound like you think you are.
Okay, and.. how do I fix my code?
It looks like TockaXY is a class that looks something like:
class TockaXY {
public float x, y;
}
From your question it is unclear what you want here. Do you want all 8 floats in an 8-sized float array? Do you only want the 'x' elements? Only the 'y' elements?
A TockaXY is not a float (it's a coordinate), so this is not easy, you'd have to program that. For example:
TockaXY[] in = ...;
float[] fs = new float[in * 2];
for (int i = 0; i < in.length; i++) {
fs[i * 2] = in[i].x;
fs[(i * 2) + 1] = in[i].y;
}
I'm implementing in Java.
At the moment I'm trying to use BDDs (Binary Decision Diagramms) in order to store relations in a datastructure.
E.g. R={(3,2),(2,0)} and the corresponding BDD:
For this reason I was looking for libraries, which have BDD functionalities in order to help me.
I found two possibilities: JavaBDD and JDD.
But in both cases, I do not understand how I can encode a simple integer to a BDD, because how or when do I give the value of my integer? Or what does it mean, if the BDD is represented by an integer?
In both cases, there are methods like:
int variable = createBDD(); //(JBDD)
or
BDD bdd = new BDD(1000,1000);
int v1 = bdd.createVar(); // (JDD)
How can I simply create a BDD like my example?
Thank you very much!!
So I found a solution for this, but it is not very satisfying, as I cannot get the tuple back from the BDD without knowing, how many boolean variables I used for representing the integer in binary. So I have to define in the beginning for example: All my integers are smaller than 64, so they are represented by 6 binary variables. If I want to add a bigger integer than 64 afterwards I have a problem, but I don't want to use the maximum size of integers from the beginning, in order to save time, because I wanted to use BDDs in order to save running time, else there are a lot of easier things than BDDs for just representing tuples.
I use JDD as my BDD library, so in JDD BDDs are represented as integers.
So this is how I will get a BDD out of an integer tuple:
In the beginning you have to create the BDD-variables, the maxVariableCount is the maximum number of binary variables, which represent the integer (explained in the beginning of this answer):
variablesDefinition is just the number of integer variables I want to represent later in the BDD. So in the example of my question variablesDefinition would be 2, because each tuple has two intereger variables.
The array variables is a two dimension array, which has all BDD variables inside. So for example if our tuple has 2 elements, the BDD variables which represent the first integer variable can be found in variables[0].
BDD bddManager = new BDD(1000,100);
private int variablesDefinition;
private int[][] variables;
private void createVariables(int maxVariableCount) {
variables = new int[variablesDefinition][maxVariableCount];
for(int i = 0; i < variables.length; i++) {
for(int j = 0; j < maxVariableCount; j++) {
variables[i][j] = bddManager.createVar();
}
}
}
Then we can create a bdd from a given integer tuple.
private int bddFromTuple(int[] tuple) {
int result;
result = bddManager.ref(intAsBDD(tuple[0],variables[0]));
for(int i = 1; i < tuple.length; i++) {
result = bddManager.ref(bddManager.and(result, intAsBDD(tuple[i], variables[i])));
}
return result;
}
private int intAsBDD(int intToConvert, int[] variables) {
return bddFromBinaryArray(intAsBinary(intToConvert, variables.length), variables);
}
private int[] intAsBinary(int intToConvert, int bitCount) {
String binaryString = Integer.toBinaryString(intToConvert);
int[] returnedArray = new int[bitCount];
for (int i = bitCount - binaryString.length(); i < returnedArray.length; i++) {
returnedArray[i] = binaryString.charAt(i - bitCount + binaryString.length()) - DELTAConvertASCIIToInt;
}
return returnedArray;
}
static int DELTAConvertASCIIToInt = 48;
private int bddFromBinaryArray(int[] intAsBinary, int[] variables) {
int f;
int[] tmp = new int[intAsBinary.length];
for(int i = 0; i < intAsBinary.length; i++) {
if(intAsBinary[i] == 0) {
if (i == 0) {
tmp[i] = bddManager.ref(bddManager.not(variables[i]));
}
else {
tmp[i] = bddManager.ref(bddManager.and(tmp[i-1], bddManager.not(variables[i])));
bddManager.deref(tmp[i - 1]);
}
}
else {
if (i == 0) {
tmp[i] = bddManager.ref(variables[i]);
}
else {
tmp[i] = bddManager.ref(bddManager.and(tmp[i-1], variables[i]));
bddManager.deref(tmp[i - 1]);
}
}
}
f = tmp[tmp.length-1];
return f;
}
My first intention was to add these tuples to the BDD and afterwards being able to execute arithmetic functions in the integers in the BDD, but this is only possible after transforming the BDD back to tuples and executing the function and returning it to the BDD, which destroys all reasons why I wanted to use BDDs.
Simply encode integer tuples using a k-subset encoding algorithm like lex, colex, revdoor, coolex etc.
Lex encodes a k-tuple out of n integers in lexicographic order, e.g. n=4, k=2 yields the (1 based) encoding
tuple rank
(0,1) -> 1
(0,2) -> 2
(0,3) -> 3
(1,2) -> 4
(1,3) -> 5
(2,3) -> 6
You need a rank(tuple) and unrank(rank) routine to transform tuple to rank and back.
I have written some code for sorting random integers that a user inputted. How would I switch this into sorting randomly inputted letters? Aka, user inputs j, s, g, w, and the programs outputs g, j, s, w?
for (int i = 0; i < random.length; i++) { //"random" is array with stored integers
// Assume first value is x
x = i;
for (int j = i + 1; j < random.length; j++) {
//find smallest value in array (random)
if (random[j] < random[x]) {
x = j;
}
}
if (x != i) {
//swap the values if not in correct order
final int temp = random[i];
random[i] = random[x];
random[x] = temp;
}
itsATextArea.append(random[i] + "\n");// Output ascending order
}
Originally I hoped (though I knew the chances of me being right were against me) that replacing all the 'int' with 'String' would work...naturally I was wrong and realized perhaps I had to list out what letter came before which by using lists such as list.add("a"); etc.
I apologize if this seems like I am asking you guys to do all the work (which I'm not) but I'm not entirely sure how to start going about this, so if anyone can give some hints or tips, that would be most appreciated!
You could use String.compareTo() to do that:
Change this:
int[] random = new int[sizeyouhad];
...
if (random[j] < random[x]) {
...
final int temp = random[i];
to:
String[] random = new String[sizeyouhad];
...
if (random[j].compareTo(random[x]) < 0) {
...
final String temp = random[i];
Trial with your code:
String[] random = new String[3];
random[0] = "b";
random[1] = "c";
random[2] = "a";
int x = 0;
//"random" is array with stored integers
for (int i = 0; i < random.length; i++) {
// Assume first value is x
x = i;
for (int j = i + 1; j < random.length; j++) {
//find smallest value in array (random)
if (random[j].compareTo(random[x]) < 0) {
x = j;
}
}
if (x != i) {
//swap the values if not in correct order
final String temp = random[i];
random[i] = random[x];
random[x] = temp;
}
System.out.println(random[i] + "\n");// Output ascending order
}
If you're just trying to sort a list of strings you should probably use the java.util.Collections.sort method rather than writing your own sorting routine.
Was random originally int[]? If you had changed this to String[], you can use String#compareTo method to discern if one string is "less than" another.
Incidentally, you can change the type of random to Comparable[] and then you can use the same algorithm to sort any object whose class implements the interface!
Try to use Collections.sort() function
List<String> l = Arrays.asList("j","s", "g","w");
Collections.sort(l);
If you consider every character to be a code point[1] and you want to sort by Unicode code point order[2], then there is really no need to change your logic. The work is converting from whatever input you are given (String, char[], etc.) into an int[] of the code points.
[1] - http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#codePointAt(int)
[2] - http://en.wikipedia.org/wiki/Code_point
You can make your code work on any type of Object by using generics.
The following code is very simple and works perfectly (With this library you can solve your problem in few lines):
import static ch.lambdaj.Lambda.sort;
import static ch.lambdaj.Lambda.on;
import java.util.Arrays;
import java.util.List;
public class Test{
public static void main(String[] args) {
List<String> list = Arrays.asList("1","102","-50","54","ABS");
List<String> newList = sort(list, on(String.class));
System.out.println(newList);//[-50, 1, 102, 54, ABS]
}
}
This code uses lambda library (download here, website). Find in the website this example:
List<Person> sorted = sort(persons, on(Person.class).getAge());
I'm learning constructors and I understand them for the most part, but I must not understand it enough. I also don't understand this fully. But this code below is supposed to use these constructors:
default constructor, which will be used to fill the matrix with random doubles
constructor which takes a File object, which points to a file
containing a matrix,
constructor which takes a string, which contains the name of the file
constructor which takes a value of type Matrix, and makes a copy of it
constructor which takes a 2D array, and copies its values
And some more, along with a static multiply method. I am supposed to use the commands that are found in main. But I don't quite understand how using a String as the only parameter will do the constructor it's told to, and also the other ones like the default constructor that fills the array with random doubles. I think I should be using this more in my code, but I'm not quite sure.
I mainly just need to be able to set a matrix, fill m1 matrix with random doubles, do it again with m2 matrix, and then use the static multiply method to multiply them, then output the resulting matrix. Thank you.
(Just a heads up, I'm using a 3 by 3 matrix, originally I was supposed to set the size of the matrix to the one found in the text file, but I can also specify the size I want, which I am. And sorry for the messy code. It got all jumbled up while I was trying to figure this stuff out, and I'm afraid of altering it further.)
public class Matrix {
double A[][] = new double[3][3]
// Matrix file name
public Matrix(String name) {
this(new File(name));
}
// Matrix random fill
public Matrix() {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
this.A[i][j] = (min + Math.random() * (max - min));
}
// Matrix copy
public Matrix(double[][] A) {
private double[][] arrcopy = new double[3][3];
private double[][] array = new double[3][3];
array = A;
for(int i = 0; i < 3; ++i){
for(int j = 0; j < array[i].length; ++j) {
arrcopy[i][j] = array[i][j];
}
}
}
// Set array from text file
public Matrix(File a) {
File f = a;
Scanner inputStreamOne = null;
try{
inputStreamOne = new Scanner(f);
}
catch(FileNotFoundException e){
System.out.printf("Error\n");
}
double arrayOne[][] = new double[3][3];
while(inputStreamOne.hasNextInt()) {
for(int i = 0; i < 3; ++i){
for(int j = 0; j < arrayOne[i].length; ++j){
arrayOne[i][j] = inputStreamOne.nextInt();
}
}
inputStreamOne.close();
}
}
// Gets array in file from string name
public Matrix(String a) {
String inputOne = a;
Scanner inputStreamOne = null;
try{
inputStreamOne = new Scanner(new File(inputOne));
}
catch(FileNotFoundException e){
System.out.printf("Error\n");
}
while(inputStreamOne.hasNextInt()){
for(int i = 0; i < size; ++i){
for(int j = 0; j < arrayOne[i].length; ++j){
arrayOne[i][j] = inputStreamOne.nextInt();
}
}
inputStreamOne.close();
}
}
public static multiply
public static void main(String args[]) {
Matrix m = new Matrix("matrix1.txt");
Matrix m2 = new Matrix("matrix2.txt");
Matrix r = Matrix.multiply(m, m2);
r.output(...);
}
}
Within a constructor or a method this refers to the current object. Within a constructor, if you just use a bare this ( which is to say this without a .method after it ) then it refers to another constructor of the same object that has a different type signature.
Constructors, like any function in Java, can be overloaded. Which is to say, because of Java's type system you can have multiple functions that are of the same name so long as they have different type signatures.
class Foo {
public Foo ( String arg ) {
this(arg, "World");
}
public Foo ( String arg1, String arg2 ) {
// do stuff with arg1 and arg2
}
}
In the above example, one constructor takes a single string and the other takes two. Java won't magically know what to do with the data passed into different constructors. What you have to do is write code in each method so that the resulting object is the same. ( Well technically you don't have to do that, but it's good form ( usually overloaded constructors are for setting default values or for the ease of use of other programmers ))
The this keyword refers to the current object in a constructor or a method, i.e. the object whose constructor or method is being called. Within a constructor, you can also use this to call another constructor in the class.
Refer to http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html for a clear explanation from Java Tutorials.