Populate a Multidimensional Array with a Loop

Create multidimensional array in for loop

You can do something like this:

var squares = new Array();
for(var i = 0; i <= 8; i++)
{
squares[i] = new Array();
for(var j = (i * 20) + 1; j <= 20 * i + 20; j++)
if (squares[i] == null)
squares[i] = j;
else
squares[i].push(j);
}

Output comes like:

array[0][1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
array[1][21,22,23,24,25,26,27....]

Populate a multidimensional array with a loop

Calling array[i][j] is for elements that are already there. You cannot use it to initialize the array, because currently it is just an empty array. You should be using .append instead. Keep in mind that this actually isn't a multi-dimensional array like Rob Napier states, but it accomplishes the same goal in this scenario. Try something like this:

var array = [[Int]]()
for i in 0...3 {

var subArray = [Int]()
for j in 0...3 {
subArray.append(i + j)
}

array.append(subArray)
}

This prints:

[[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]

Again, may not be the best approach, but this is just how you could do it in Swift.

How to fill multidimensional array with loop

In case you can't initialize arrays (Like suggested in @Barmar Answer), you need to look for the array key to override it with an array. Like here :

$days=array('Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
);
print_r($days);

//Example
$res[0]['name']="Sunday";
$res[0]['ID']="7";
$res[1]['name']="Monday";
$res[1]['ID']="1";

foreach($res as $k => $v){
$daykey = array_search($res[$k]['name'], $days);
if ($daykey !== false) {
$days[$daykey]=array($res[$k]['name']=>array('ID'=>$res[$k]['ID'],'name'=>$res[$k]['name']));
} else {
//do nothing... or whatever
}
}
print_r($days);

Filling a multidimensional array in Java using enhanced for loop

The first method does not fill the array, because in the code

for (char column : rows) {
column = '*';
}

the value in the array is copied to the new variable column. You then just assign a new value for this variable, but the element in the array remains unchanged.

The method Arrays.fill() does not copy the value, instead it operates directly on the array. You can do so yourself with this code (which is basically the same as Arrays.fill() does):

for (int i = 0; i < battleBoard.length; i++) {
for (int j = 0; j < battleBoard[i].length; j++) {
battleBoard[i][j] = '*';
}
}

Populating 2D array with two 1D arrays with for loop

I would suggest to copy every three strings from your arrayTocke and populate the rows of your 2D array using Array.copyOfRange(originalArray, int from, int to)

public static void main(String[] args) {
String[] arrayCentri= {"center1","center2","center3"};
String[] arrayTocke= {"tocka1","tocka2","tocka3","tocka4","tocka5","tocka6","tocka7","tocka8","tocka9", "tocka10"};

int rows = arrayTocke.length/arrayCentri.length + (arrayTocke.length%arrayCentri.length == 0 ? 1 : 2);
int columns = arrayCentri.length;
int rowCount = 0;

String[][] clusterji = new String[rows][columns];
clusterji[rowCount++] = arrayCentri;
for(int i=0;i < arrayTocke.length; i += columns){
clusterji[rowCount++] = Arrays.copyOfRange(arrayTocke, i, Math.min(arrayTocke.length,i+columns));
}
Arrays.stream(clusterji).forEach(row->{System.out.println(Arrays.toString(row));});
}

OR

Using Streams

    public static void main(String[] args) {
String[] arrayCentri= {"center1","center2","center3"};
String[] arrayTocke= {"tocka1","tocka2","tocka3","tocka4","tocka5","tocka6","tocka7","tocka8","tocka9", "tocka10"};
//concat both arrays to one to get {"center1","center2","center3","tocka1","tocka2" ..."tocka10"}
String[] centriAndTocke = Stream.concat(Arrays.stream(arrayCentri), Arrays.stream(arrayTocke)).toArray(String[]::new);

int columns = arrayCentri.length;
String[][] clusterji = IntStream.iterate(0, i -> i + columns)
.limit((long) Math.ceil((double) centriAndTocke.length / columns))
.mapToObj(j -> Arrays.copyOfRange(centriAndTocke, j, Math.min(centriAndTocke.length, j+columns)))
.toArray(String[][]::new);
Arrays.stream(clusterji).forEach(row->{System.out.println(Arrays.toString(row));});
}

Java - How to populate 2d array with nested while loops?

The most common way to do this is through for loops since they allow you to specify the index counters you need in a concise way:

for(int i = 0; i < scores.length; i++){
for(int j = 0; j < scores[i].length; j++){
scores[i][j] = in.nextDouble();
}
}

If you specifically need to use while loops you can do pretty much the same thing, its just broken up into multiple lines:

int i = 0;
while(i < scores.length){
int j = 0;
while(j < scores[i].length){
scores[i][j] = in.nextDouble();
j++;
}
i++;
}

Filling a 2d array using a for loop in javascript

JavaScript doesn't have two-dimensional arrays. It has arrays of arrays.¹ The problem in your code is that you've only created two of the inner arrays, not the other eight.

The solution is to create the inner arrays inside your x loop:

var myArray = []; // *** Just create the outer
var x = 0;var z = 0;for (x = 0; x < 10; x++) { myArray[x] = []; // *** Create inner here for (z = 0; z < 10; z++) { myArray[x][z] = "x"+x+"z"+z; }}
console.log(myArray);

Populate 2D arrays using a loop

Each sub array of your 2D array has 2 items (right?), so you should have a 2 instead of a 1 as the length:

string[,] fieldAndIndex = new string[arrayLength, 2];

Since you want a counter variable I in the loop, you should not use a foreach loop:

for (int i = 0 ; i < arrayLength ; i++) {
// here you want the first item of the subarray to be i, and the second item to be the corresponding segment
fieldAndIndex[i, 0] = i.ToString();
fieldAndIndex[i, 1] = segmentFields[i];
}

Also, I don't think a 2D array is suitable here. Storing the index of each element (which is what you seem to be trying to do) is unnecessary, because fieldAndIndex[x, 0] will always be the same as x!

You might want to use a simple 1D array instead. There are other data structures that might be useful:

  • Dictionary<int, string>
  • (int, string)[]
  • string[][]

How to create 2d array using for loop in Javascript?

Here is some updated code. You need to add i*columns to every value

const numbers = [];
const columns = 4;
const rows = 5;

for (let i = 0; i < rows; i++) {
numbers[i] = [];
for (let j = 0; j < columns; j++){
numbers[i][j] = j + 1 + (i*columns);
}
}
console.log(numbers);


Related Topics



Leave a reply



Submit