JAVA - Not able to properly fill multidimentional array from another array - java
I have a string of values separated by commas that I converted into an array, which I was then going to use to create a 2D array. When creating a loop to add the data from the first array to the 2D array it is repeating the data.
The output I'm getting is:
4428,40,401,610,2016,3821,31,347,572,2015,4381,38,341,520,2014,2536,17,193,290,2013,4295,39,371,552,2012,4643,45,343,502,2011,3922,28,312,475,2010,4434,30,350,541,2009,4038,28,341,536,2008,218,1,20,28,2007,46,0,6,15,2006,65,0,9,16,2005,4428,40,401,610,2016,3821,31,347,572,2015,4381,38,341,520,2014,2536,17,193,290,2013,4295,39,371,552,2012,4643,45,343,502,2011,3922,28,312,475,2010,4434,30,350,541,2009,4038,28,341,536,2008,218,1,20,28,2007,46,0,6,15,2006,65,0,9,16,2005,4428,40,401,610,2016,3821,31,347,572,2015,4381,38,341,520,2014,2536,17,193,290,2013,4295,39,371,552,2012,4643,45,343,502,2011,3922,28,312,475,2010,4434,30,350,541,2009,4038,28,341,536,2008,218,1,20,28,2007,46,0,6,15,2006,65,0,9,16,2005,4428,40,401,610,2016,3821,31,347,572,2015,4381,38,341,520,2014,2536,17,193,290,2013,4295,39,371,552,2012,4643,45,343,502,2011,3922,28,312,475,2010,4434,30,350,541,2009,4038,28,341,536,2008,218,1,20,28,2007,46,0,6,15,2006,65,0,9,16,2005,4428,40,401,610,2016,3821,31,347,572,2015,4381,38,341,520,2014,2536,17,193,290,2013,4295,39,371,552,2012,4643,45,343,502,2011,3922,28,312,475,2010,4434,30,350,541,2009,4038,28,341,536,2008,218,1,20,28,2007,46,0,6,15,2006,65,0,9,16,2005
and the correct output should be:
4428,40,401,610,2016,3821,31,347,572,2015,4381,38,341,520,2014,2536,17,193,290,2013,4295,39,371,552,2012,4643,45,343,502,2011,3922,28,312,475,2010,4434,30,350,541,2009,4038,28,341,536,2008,218,1,20,28,2007,46,0,6,15,2006,65,0,9,16,2005
Expected results:
{{4428,40,401,610,2016}
{3821,31,347,572,2015}
{4381,38,341,520,2014}
...} and so on, every 5
My code for adding the array to the 2D array is below:
{String[] columns = {"Yards","Touchdowns","Attempts","Incompletions","Year"};
String[] data1 = results1.split(",");
Object [][] data11 = new Object[columns.length][data1.length];
for(int i = 0; i<columns.length;i++){
for(int j = 0; j<data1.length;j++){
data11[i][j] = data1[j];
//System.out.print(data11[i][j]+",");
}
}}
EDIT: Solution!
Object [][] data11 = new Object[data1.length/columns.length][columns.length];
int column = -1;
for(int j = 0; j<data1.length;j++){
if(j % columns.length == 0) column = column+1;
data11[column][j % 5] = data1[j];
}
Maybe this work for you:
Object [][] data11 = new Object[columns.length][data1.length / 5];
int column = -1;
for(int j = 0; j<data1.length;j++){
if(j % 5 == 0) column = column + 1
data11[j % 5][column] = data1[j];
}
Note the matrix size changed and the assignation too. Haven't tried, probably you can make a prettier version. Hope it helps!
You also loop the first array (i), so he will repeat it. Just write this:
data11[0][j] = data1[j];
Or even don't do the first loop at all, depending on what you need.
Assuming your output, you only want to fill in the first position (0) of the array.
Related
Storing Values to a 2 dimensional array in Java
Brand new to Java. I'm trying to store values from a String to a 2D array in java. The first two values of my String give me rows and columns for a grid. From here, I need to use Integer.parseInt() to parse the values and assign them. I'm attempting do this using a for() loop, but I'm completely stuck. Here's what I have so far (notes included to indicate what I'm attempting to acheive): int r = Integer.parseInt(tokens[0]); rows = r; int c = Integer.parseInt(tokens[1]); cols = c; // create 2D array of int values // place the reference to the array object in grid variable int[][] input = new int[rows][cols]; grid = input; //parse then store remaining values as int values in the 2D array using a nested loop for(int i = 0 ; i < tokens.length ; i++) { // read the next value and assign to next token }
Your code seems to be a bit off - you parse those numbers into int variables r and c but then do int[][] input = new int[rows][cols];. You don't have such variables as rows and cols. Also you should not start with 0 in your loop since values tokens[0] and tokens[1] are for row and column counts. Start loop at 2, or end it with tokens.length-2 and add 2 every time you take value from tokens inside the loop. In order to calculate the row and column index you need to take your i (e.g. index in tokens array), adjust for the aforementioned offset of 2, floor-divide by column count to receive row number, and get a remainder of division by column count to get row number. E.g. for(int i = 2 ; i < tokens.length; i++) { int value = Integer.parseInt(tokens[i]); int idx = i-2; int row = Math.floorDiv(idx, c); int col = idx % c; grid[row][col] = value; }
Arrays in array, 100 rows, dynamic columns
I'm trying to get this: arrays[1][0] = 5 arrays[2][0] = 7 arrays[2][1] = 2 arrays[3][0] = 6 arrays[3][1] = 9 arrays[3][2] = 11 So I want arrays[1][] to have one element of random data, arrays[2][] to have 2 elements of random data and so on until I have 100 arrays. So my last array would be arrays[100][] with 100 elements of random data. This is the code I have now but I get a NullPointerException when arrays[i][j] = generator.nextInt(max) is executed: Comparable[][] arrays = new Comparable[100][]; for (int i=1; i<101;i++){ for (int j=0; j <= i-1; j++){ arrays[i][j] = generator.nextInt(max); } }
Your Comparable[][] arrays = new Comparable[100][]; line only creates the outermost array. You need to create the arrays that go in it, e.g. something like this: Comparable[][] arrays = new Comparable[100][]; for (int i=1; i<101;i++){ arrays[i] = new Comparable[/* relevant length here*/]; // <==== for (int j=0; j <= i-1; j++){ arrays[i][j] = generator.nextInt(max); } } It's unclear to me why you start i at 1 or where the randomness should be (I'm guessing at /* relevant length here */), but hopefully that points you the right way.
Converting String elements from an array to as values into an integer Array
I'm not allowed to use methods from any class except String and IO Class So my code snippet is: String line = reader.readLine(); while (line != null) { String[] elements = line.split(","); // Array could be too big if there are multiple occurances of // the same number // Array length + 1 because I can't use the 0 and with a input line of // 1,2,3 for example would be the length 3 but I would have the // numbers 0,1,2 in the Array as my index. String[][] placeholderMatrix = new String[elements.length+1][elements.length+1]; for(int i = 0; i < elements.length-1; i++){ placeholderMatrix[(int)elements[i]][(int)elements[i+1]] = 1; } line = reader.readLine(); } In the File I'm getting are only numbers like that: 1,2,3,4,5,8,7,4 So in my splitted String Array are only Numbers but now if I want to use them as my index for my Matrix(placeholderMatrix) My problem is in my for loop where I want to use them as my Index I can't use them because it is a String Array. Normally I would use Integer.parseInt but I'm not allowed to :/ Any ideas on how I can implement them as my Index? and any Idea how I can get the perfect length of my Matrix? Because If I get the following numbers: 1,2,2,2,3 My Matrix should only have the numbers: 0 1 2 3 1 2 3 But if I'm using elements.length+1 for the length of my Matrix I would get the numbers 0 1 2 3 4 5 Hope you could understand my problem. Sorry for my bad english and Thanks in advance. Edit: SO i got another problem with that. If I implement the method(parseInt) of Dici and am using it in the line "placeholderMatrix[parse(elements[i])][parse(elements[i+1])] = 1;" I'm getting the error ArrayOutOfBounce because my defined Array is just the length of my splitted String Array elements. But if I define it with Integer.MAX_VALUE as my length I get a memory error because it is too big. Any ideas? Edit2: My Task: I have to take a row of Numbers seperated by ",". (I will split it with the String split method to get only the numbers) Now I have to create a Matrix(2 dimensional Array) and look for the number at the index i of my new String Array and the number at the index i + 1 and have to take the first Number as my column and th second as my row (or vice versa) and implement at that point a 1. Now are my Numbers I will get from 1 to Integer.MAX_VALUE so I would have to create such a big Matrix but this isn't possible because I get the MemoryError. Error: java.lang.OutOfMemoryError: Requested array size exceeds VM limit at Test.main(Test.java:29) To understand what I have to do: http://de.wikipedia.org/wiki/Adjazenzmatrix the image at the right but for numbers from to Integer.MAX_VALUE so my 2D Array has to be defined with the length of Integer.MAX_VALUE? Edit: So Dici asked for an example: My Sequence could be: 1,2,5,4 So my Matrix should be: Hope this is what you wanted Dici But the numbers I can get from the sequence are 1 to Integer.MAX_VALUE
For converting strings to integers, you can simply implement your own integer parser, it is not complicated. You can start with this and improve it if needed. public int parseInt(String s) { int n = 0; int pow = 1; for (int i=s.length() - 1 ; i>=0 ; i--) { String si = String.valueOf(s.charAt(i); if (si.matches("[0-9]")) { n += pow*(s.charAt(i) - '0'); pow *= 10; } else if (si.matches("+|-") && i == 0) n *= s.charAt(i) == '+' ? 1 : -1; else throw new NumberFormatException(); } return n; } Then, I'll handle the second part of your problem. If Integer.MAX_VALuE is one of your input values, you cannot possibly allocate an Integer.MAX_VALUE x Integer.MAX_VALUE matrix. What you need to do is assign contiguous ids to your input values and record the ids in a map so that you can access easily the index of the matrix corresponding to one node value. Here is an example to get you to understand : public void someMethod() { int id = 0; Map<Integer,Integer> idMap = new HashMap<>(); String[] split = reader.readLine().split(","); int [] nodes = new int[split.length]; for (int i=0 ; i<nodes.length ; i++) { nodes[i] = parseInt(split[i]); if (!idMap.containsKey(nodes[i])) idMap.put(nodes[i],id++); } // the map is now constructed, it should probably be stored in an attribute int[][] placeholderMatrix = new int[nodes.length][nodes.length]; for(int i = 0; i < nodes.length; i++){ if (i > 0) placeholderMatrix[idMap.get(nodes[i])][idMap.get(nodes[i-1])] = 1; if (i < nodes.length-1) placeholderMatrix[idMap.get(nodes[i])][idMap.get(nodes[i+1])] = 1; } } There are other ways to do it, let me know if this solution is ok
You could do something like: String keyword = "1,2,3,4,5,8,7,4";//input line from file String replacedKeyword = keyword.replaceAll("[^\\d]", "");//except numbers replace all. Assuming one digit numbers only. String[][] placeholderMatrix = new String[replacedKeyword.length()+1][replacedKeyword.length()+1]; char keys[] = replacedKeyword.toCharArray(); for (int i = 0; i<keys.length - 1; i++) { placeholderMatrix[keys[i] - '0'][keys[i + 1] -'0'] = "1"; }
I couldn't really understand what you want exactly. but, if that going to help a simple method to convert String number to int: int toInt(String number) { int num = 0; for (int i=0; i<number.length(); i++) { num = num*10 + (number.charAt(i)-'0'); } return num; }
2D array not printing the last element during comparison
I am trying to replace rows from an original 2d array to a updated 2d array. Problem is it won't store the last element during the replacement. Here's my code: String[][] updatedArray = {{"red","a","b","c"},{"yellow","a","b","c"}, {"purple","a","b","c"}}; String[][] originalArray = {{"red","aa","bb","cc"},{"yellow","ww","vv","zz"}, {"green","yy","uu","pp"}, {"purple","nn","mm","bb","hello"}}; for (int i = 0; i < updatedArray.length;i++ ) { for (int j = 0; j < updatedArray[i].length; j++){ for(int x = 0; x < originalArray.length;x++){ for(int z = 0; z < originalArray[x].length;z++){ if(originalArray[x][0].equals(updatedArray[i][0])) { updatedArray[i][j] = originalArray[x][j]; System.out.println("There's a match!!"); }else{ System.out.println("No match!"); } } } } } System.out.println("originalArray:"); System.out.println(Arrays.deepToString(originalArray)); System.out.println("updatedArray:"); System.out.println(Arrays.deepToString(updatedArray)); For example, initially updatedArray in last row "purple" has {"purple","a","b","c"}. When it does the replacement using values from originalArray, the code above only outputs: ... [purple, nn, mm, bb] which is wrong because it doesn't add the last element "hello". It should output: ... [purple, nn, mm, bb, hello] I am aware the problem is in this line: updatedArray[i][j] = originalArray[x][j]; Problem is no matter what I try to change originalArray[x][j] to originalArray[x][z] ... its screws up everything. Any ideas on this? Still trying to get the jist of 2D arrays.
If there is a match, instead of trying to set each element in the updatedArray to the corresponding element in the original array you can just set the entire array to the original array. String[][] updatedArray = {{"red","a","b","c"},{"yellow","a","b","c"}, {"purple","a","b","c"}}; String[][] originalArray = {{"red","aa","bb","cc"},{"yellow","ww","vv","zz"}, {"green","yy","uu","pp"}, {"purple","nn","mm","bb","hello"}}; for (int i = 0; i < updatedArray.length;i++ ) { for (int j = 0; j < originalArray.length; j++){ if(originalArray[j][0].equals(updatedArray[i][0])) { updatedArray[i] = originalArray[j]; System.out.println("There's a match!!"); }else{ System.out.println("No match!"); } } }
The issue is how you chose to iterate over the dimensions of updatedArray which are different than the dimensions of originalArray. Let just look at the case i=2 which is the 'row' for purple: for (int j = 0; j < updatedArray[i].length; j++){ updatedArray[i=2].length = 4 in updated: index = 0 , 1 , 2 , 3 {"purple","a","b","c"} in original: index = 0 , 1 , 2 , 3 , 4 {"purple","nn","mm","bb","hello"} Therefore since j will always be < 4 it can never be used to index originalArray[x][4] = "hello" DANGER: this code also doesn't handle the fact that you would need to extend the purple array for updatedArray. Java may do some magic to handle this for you but I wouldn't trust it to work that way. Suggestion: - compare the lengths of each row and allocate extra memory where necessary before copying data from originalArray to updatedArray - if possible just copy the whole row between original and updated.
Appending to double Array method
So, I have a method like this public String[][] getArgs(){ And, I want it to get results out of a for loop: for(int i = 0; i < length; i++){ But how do I append them to the array instead of just returning them?
Create a String[][] array inside your method, fill this array inside a loop (or in any other way) and return that array in the end. If you are sure you want to have only one for loop (instead of two, typical for 2-dimensional array), ensure your loop will go through the number of examples equal to the number of fields in your String[][] array. Then you can calculate the double-dimension array indexes from your single loop-iterator, for example: for(int i = 0; i < length; i++){ int a = i % numberOfCollumnsInOutput; int b = i / numberOfCollumnsInOutput; String[a][b] = sourceForYourData[i]; } (Of course which array dimension you treat as collumns (and which to be rows) depends on yourself only.) However, it is much more typical to go through an n-dimensional array using n nested loops, like this (example for 2d array, like the one you want to output): for(int i = 0; i < dimensionOne; i++){ for(int j = 0; j < dimensionTwo; j++){ array[i][j] = someData; } }
For your interest. A sample code according to Byakuya. public String[][] getArgs(){ int row = 3; int column =4; String [][] args = new String[row][column]; for(int i=0;i<row;i++) for(int j=0;j<column;j++) args[i][j] = "*"; return args; }
You can make a LinkedList from that array, and then append the elements to it, and then create a new array from it. If you are not sure i'll post some code.