I want to convert ArrayList to Array 2-Dimension
I have the code below:
ArrayList<String> arrayList=new ArrayList();
arrayList.add("A")
arrayList.add("B")
arrayList.add("C")
arrayList.add("D")
arrayList.add("E")
arrayList.add("F")
int nSize=0,n3item=0, remain=0;
nSize=arrayList.size();
n3item=nSize/3;
remain=nSize%3;
String[][] array[n3item][3]
I want to convert ArrayList to array for example
array[0][1]="A"
array[0][2]="B"
array[0][3]="C"
array[1][1]="D"
array[1][2]="E"
array[1][3]="F"
Now I haven't a solution to do this.
In case of remain is not 0. How to give a solution to this problem
I need your help.
Thanks.
You can use a simple nested for-loop to achieve this.
int numCol = 3;
int numRow = (int) Math.ceil(arrayList.size() / ((double) numCol));
String[][] array = new String[numRow][numCol];
int i, j;
for (i = 0; i < numRow; i++) {
for (j = 0; j < 3 && (i * numCol + j) < arrayList.size(); j++) {
array[i][j] = arrayList.get((i * numCol) + j);
}
}
numRow is found by taking the ceil of number of elements in the list divided by num of desired columns.
eg - when arraylist has 7 elements, numRow will be ceil(7/3.0) = 3.
The main trick here is in the inner for-loop condition (i * numCol + j) < arrayList.size(). It enables us to terminate the loop for the condition remain != 0 you mentioned.
Try to think, how you can fill the 2D array with arraylist values. You need to use a nested loop for assigning the values into the 2D array. Outer loop will iterate over the rows and inner loop will fill the values into each 1D array.
int index = 0;
for(int i = 0; i < n3item; i++) {
for(int j = 0; j < 3; j++) {
array[i][j] = arrayList.get(index);
index++;
}
}
One of the questions from my exam asked to write some code to compute the sum of the outer int elements of a 2D array. Length of rows and length of columns aren't necessarily equal.
[EDIT] Corner values cannot be added more than once.
I came up with this code and it works, but I'd like to know if there are more efficient ways to achieve the same results. Thanks.
for(int i = 0; i < in.length; i ++) {
for(int j = 0; j < in[i].length; j++) {
if(i == 0 || i == in.length - 1) {
sum += in[i][j];
}
else {
sum += in[i][in[i].length - 1 ] + in[i][0];
break;
}
}
}
If I understand your question, then you could first extract a method to add the elements of one array like
public static int sumArray(int[] in) {
int sum = 0;
for (int val : in) {
sum += val;
}
return sum;
}
Then you can add the elements on the first and last rows like
int sum = sumArray(in[0]) + sumArray(in[in.length - 1]);
And then the outer elements from the other rows with an additional (non-nested) loop like
for (int i = 1; i < in.length - 1; i++) {
sum += in[i][0] + in[i][in[i].length - 1];
}
Or, in Java 8+, you might eliminate the extra method and the explicit loop and do it with one statement like
int sum = IntStream.of(in[0]).sum() //
+ IntStream.of(in[in.length - 1]).sum() //
+ IntStream.range(1, in.length - 1).map(i -> {
return in[i][0] + in[i][in[i].length - 1];
}).sum();
Yes you can do it more efficiently.
int row = in.length;
int column = in[0].length;//not sure of this syntax but trying to get the column size
int sum = 0;
for(int j=0;j<column;j++)
{
sum+=in[0][j]+in[row-1][j];
}
for(int j=1;j<row-1;j++)
{
sum+=in[j][0]+in[j][column-1];
}
Your solution is O(mn) and the loop iterates through unnecessary indexes.
I want to add a NxN matrix antidiagonal elements using a for loop in a java program.
This code (2 conditions) does not work because it always says when the loop is executed sum2=0.
for (int i=0,j=t-1; i<t && j==0; i++, j--) {
sum2 = sum2 + aNumber[i][j];
}
Instead this one (one condition) works well.
for (int i=0, j=t-1; i<t ; i++, j--) {
sum2 = sum2 + aNumber[i][j];
}
Why does not work the first code?
In your first example the loop ends as soon as j != 0, if t > 1 this means that it will end immediately, making no iterations at all.
Try something like this:
int maxIndex = matrix.length - 1;
int sum = 0;
for (int i = 0; i <= maxIndex; i++) {
sum += matrix[i][maxIndex - i];
}
This relies on the fact that the sum of the indexes of each antidiagonal element is exactly equal to N.
I am having trouble creating multiple arrays with a loop in Java. What I am trying to do is create a set of arrays, so that each following array has 3 more numbers in it, and all numbers are consecutive. Just to clarify, what I need to get is a set of, let's say 30 arrays, so that it looks like this:
[1,2,3]
[4,5,6,7,8,9]
[10,11,12,13,14,15,16,17,18]
[19,20,21,22,23,24,25,26,27,28,29,30]
....
And so on. Any help much appreciated!
Do you need something like this?
int size = 3;
int values = 1;
for (int i = 0; i < size; i = i + 3) {
int[] arr = new int[size];
for (int j = 0; j < size; j++) {
arr[j] = values;
values++;
}
size += 3;
int count = 0;
for (int j : arr) { // for display
++count;
System.out.print(j);
if (count != arr.length) {
System.out.print(" , ");
}
}
System.out.println();
if (i > 6) { // to put an end to endless creation of arrays
break;
}
}
To do this, you need to keep track of three things: (1) how many arrays you've already created (so you can stop at 30); (2) what length of array you're on (so you can create the next array with the right length); and (3) what integer-value you're up to (so you can populate the next array with the right values).
Here's one way:
private Set<int[]> createArrays() {
final Set<int[]> arrays = new HashSet<int[]>();
int arrayLength = 3;
int value = 1;
for (int arrayNum = 0; arrayNum < 30; ++arrayNum) {
final int[] array = new int[arrayLength];
for (int j = 0; j < array.length; ++j) {
array[j] = value;
++value;
}
arrays.add(array);
arrayLength += 3;
}
return arrays;
}
I don't think that you can "create" arrays in java, but you can create an array of arrays, so the output will look something like this:
[[1,2,3],[4,5,6,7,8,9],[10,11,12,13...]...]
you can do this very succinctly by using two for-loops
Quick Answer
==================
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
the first for-loop tells us, via the variable j, which array we are currently adding items to. The second for-loop tells us which item we are adding, and adds the correct item to that position.
All you have to remember is that j++ means j + 1.
Now, the super long-winded explanation:
I've used some simple (well, I say simple, but...) maths to generate the correct item each time:
[1,2,3]
here, j is 0, and we see that the first item is one. At the first item, i is also equal to 0, so we can say that, here, each item is equal to i + 1, or i++.
However, in the next array,
[4,5,6,7,8,9]
each item is not equal to i++, because i has been reset to 0. However, j=1, so we can use this to our advantage to generate the correct elements this time: each item is equal to (i++)+j*3.
Does this rule hold up?
Well, we can look at the next one, where j is 2:
[10,11,12,13,14...]
i = 0, j = 2 and 10 = (0+1)+2*3, so it still follows our rule.
That's how I was able to generate each element correctly.
tl;dr
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
It works.
You have to use a double for loop. First loop will iterate for your arrays, second for their contents.
Sor the first for has to iterate from 0 to 30. The second one is a little less easy to write. You have to remember where you last stop and how many items you had in the last one. At the end, it will look like that:
int base = 1;
int size = 3;
int arrays[][] = new int[30][];
for(int i = 0; i < 30; i++) {
arrays[i] = new int[size];
for(int j = 0; j < size; j++) {
arrays[i][j] = base;
base++;
}
size += 3;
}
I have a string
String word = "FrenciusLeonardusNaibaho";
while I'm trying to make matrix like this:
char matriks[][] = new char[16][16];
int k = 0;
for (int i = 1; i < 16; i++) {
for (int j = 1; j < 16; j++) {
matriks[i][j] = word.charAt(k);
k++;
}
}
I got this error
String index out of range: 24
How can I achieve this?
Thanks..
You are overflowing beyond the end of word at word.charAt(k);. Basically you dont have enough alphabets to fill your matrix.
You can do something like this
if(k >= word.length())
break;
Below the inner loop. Or you can init the element to some default value with this condition.
Additionally as others have mentioned, i,j should start at 0, unless you have a good reason to start at 1.
char matriks[][] = new char[16][16];
int k = 0;
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
matriks[i][j] = word.charAt(k%word.length());
k++;
}
}
So it can go from start to end,then restart.
try adding
if(k >= word.length())
k = 0;
to your inner for loop, this will continue filling the array from the beginning of the word.
'Out of bounds' or 'out of range' occures when you try to read or write in an array, list, string or whatever with a range beyond it's boundary. You can't read a a character at index 8 when your string contains only 7 character. It's not your string's RAM and it would cause RAM corruption like it is happening sometimes in C-arrays.
When you set up your array and your for-loop try to check if you are still in bounds of your string with a size or length function of your container. In special case of string it is length.
I think you are trying to split a list of names stored in a string. In such a case it is easier to create a dynamic container, something like list (http://www.easywayserver.com/blog/java-list-example/).
Here I have a little example. For those purposes I prefer a while-loop. In cases I know the length of a list at least at runtime without interpreting data a for-loop is a good choice, but not in this:
String names = "Foo Bar";
List<String> seperatedNames = new List<String>();
String name = "";
int i = 0;
while (i < names.length()) {
if (names.charAt(i) == ' ') { // you can check for upper case char too
seperatedNames.add(name); // add name to list
name = ""; // clear name-buffer
i++; // increment i, else it would produce an infinite loop
}
name += names.charAt(i++); // add current char to name-buffer and increment current char
}
I hope I could help a bit.
of course, you will get this error surely because the character in your word are only 24 character.
to avoid this your need to check the length of your word and need to break the all looping.
Try this code.
char matriks[][] = new char[16][16];
int k = 0;
int lenght = word.length();
outerloop:
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
matriks[i][j] = word.charAt(k);
k++;
if(k >= lenght){
break outerloop;
}
}
}
You are filling 16x16 array and iterating the loop 16x16 times but your word size is less than 16x16. So put a check when k becomes equal to the word length then terminate the loop.Change your code like this.
char matriks[][] = new char[16][16];
int k = 0;
for (int i = 1; i < 16; i++) {
for (int j = 1; j < 16; j++) {
if(k >=word.length)
break;
matriks[i][j] = word.charAt(k);
k++;
}
}