Arrays in array, 100 rows, dynamic columns - java

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.

Related

JAVA - Not able to properly fill multidimentional array from another array

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.

java - Storing String sequence in arraylist

I am trying to create a list using the code below, that stores random binary strings. But everytime I print the string elements of list, all the string elements that are printed are the same.
ex- 101 101 101 101. How do I make it work?
ArrayList<String[]> coded = new ArrayList<String[]>();
Random rand = new Random();
for(int j=0; j<4;j++){
for (int i=0; i<3;i++){
rand1 = (rand.nextInt(4)+0)%2;
x1[i]= "" + rand1;
}
coded.add(x1);
}
You have only declared one x1 array (somewhere), so in essence you're just adding a bunch of references to the same array to the list. The array will contain the values that were inserted during the last iteration.
Declare the array inside the loop to fix the issue.
for (int j=0; j<4; j++){
String[] x1 = new String[3];
for (int i=0; i<3; i++){
rand1 = (rand.nextInt(4) + 0) % 2;
x1[i]= "" + rand1;
}
coded.add(x1);
}

Weighted random numbers in 2D Array - Processing

I would like to fill a 3x3 2D array with values 1,2,3.
I need each number to appear for a given times.
For example:
1 to appear 2 times
2 to appear 4 times
3 to appear 3 times
What I need is to store this numbers to array in a random position.
For Example:
1,2,2
3,2,2
1,3,3
I already did this in a simple way using only 2 different numbers controlled by a counter. So I loop through the 2D array and applying random values of number 1 and number 2.
I'm checking if the value is 1 and add it in the counter and the same with number 2. if one of the counter exceeds the number I have set as the maximum appear times then it continues and applies the other value.
Is there any better approach to fill the 3 numbers in random array position?
See code below:
int [][] array = new int [3][3];
int counter1 =0;
int counter2 =0;
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
array[i][j] = (int)random(1, 3); //1,2
if (arrray[i][j]==1) {
counter1++;
} else if (array[i][j] ==2) {
counter2++;
}
//if it is more than 5 times in the array put only the other value
if (counter1>5) {
array[i][j] = 2;
}
//if it is more than 4 times in the array put only the other value
else if (counter2>4) {
array[i][j] = 1;
}
}
}
I finally did this according to this discussion:
How can I generate a random number within a range but exclude some?, with 1D array for tesing, but it does not always works.
Please see attached code:
int []values = new int[28];
int counter1=0;
int counter2=0;
int counter3=0;
for (int i=0; i<values.length; i++) {
if (counter1==14) {
ex = append(ex, 5);
}
if (counter2==4) {
ex =append(ex, 6);
}
if (counter3==10) {
ex =append(ex, 7);
}
values[i] = getRandomWithExclusion(5, 8, ex);
if (values[i]==5) {
counter1++;
} else if (values[i] ==6) {
counter2++;
} else if (values[i] ==7) {
counter3++;
}
}
int getRandomWithExclusion(int start, int end, int []exclude) {
int rand = 0;
do {
rand = (int) random(start, end);
}
while (Arrays.binarySearch (exclude, rand) >= 0);
return rand;
}
I would like to fill the 1D array with values of 5,6 or 7. Each one a specific number. Number 5 can be added 14 times. Number 6 can be added 4 times. Number 7 can be added 10 times.
The above code works most of the times, however somethimes it does not. Please let me know if you have any ideas
This is the Octave/Matlab code for your problem.
n=3;
N=n*n;
count = [1 2; 2 4; 3 3];
if sum(count(:,2)) ~= N
error('invalid input');
end
m = zeros(n, n);
for i = 1:size(count,1)
for j = 1:count(i,2)
r = randi(N);
while m(r) ~= 0
r = randi(N);
end
m(r) = count(i,1);
end
end
disp(m);
Please note that when you address a 2D array using only one index, Matlab/Octave would use Column-major order.
There are a ton of ways to do this. Since you're using processing, one way is to create an IntList from all of the numbers you want to add to your array, shuffle it, and then add them to your array. Something like this:
IntList list = new IntList();
for(int i = 1; i <= 3; i++){ //add numbers 1 through 3
for(int j = 0; j < 3; j++){ add each 3 times
list.append(i);
}
}
list.shuffle();
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
array[i][j] = list.remove(0);
}
}
You could also go the other way: create an ArrayList of locations in your array, shuffle them, and then add your ints to those locations.

Find the maximum of the length of 2 arrays

I am passing 2 arrays to the controller with different lengths, I want to execute a for loop and length of that will be the max of the length of 2 arrays.
I am not getting how to execute that. I tried Math.max but its giving me error as cannot assign a value to the final variable length.
String[] x =0;
x.length = Math.max(y.length,z.length);
for(int i=0; i < x.length; i++)
The no of elements in x and y are not fixed. it changes what we are passing from the front end.
Initialize the new array with the desired length:
String[] x = new String[Math.max(y.length,z.length)];
In case you don't need to create an array, just use the result of Math.max as conditional to stop your loop:
for (int i = 0; i < Math.max(y.length,z.length); i++) {
//...
}
Just bring your Math.max() operation into the array's initialization.
String[] x = new String[Math.max(y.length, z.length)];
Here's an expansion for clarity:
int xLength = Math.max(y.length, z.length);
String[] x = new String[xLength];
Edit: Unless, OP, you're not interested in creating another array...
I want to execute a for loop and length of that will be the max of the length of 2 arrays
Just bring your Math.max() operation into your for loop:
for(int i=0; i < Math.max(y.length, z.length); i++){
//code here
}
Set a variable to the maximum length of the arrays, create a new array with that length and then loop until that point.
int maxLen = Math.max(y.length, x.length);
String[] array = new String[maxLen];
for(int i = 0; i < maxLen; i++){
// Loop code here
}
int max_length = Math.max(y.length,z.length);
for(int i=0; i < max_length ; i++){
//...
}
you can use that max_length to create a new String[] if you are trying to create an array with total length of y and z arrays, like
String[] newArray = new String[max_length];

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.

Categories