I feel like the answer so simple but I just can't figure out what it is. I have an multidimensional array such as this:
int [][] number =
{{ 10, 15, 11, 13, 72, 87, 266},
{ 50, 65, 80, 94, 12, 134, 248},
{ 1, 2, 1, 9, 1, 39, 26},
{ 13, 20, 76, 4, 8, 72, 28},
{ 2, 1, 29, 2, 12, 907, 92},
{ 16, 4, 308, 7, 127, 1, 52}
};
I'm trying to add up all the integers in the each array index and display it at the end so what I thought up of is this
int total=0;
for (int k=0;k<6;k++){
for (int i=0;i<7;i++){
total=number[k][i]+total;}}
System.out.println(total);
What I noticed is that it will add up all the numbers in the entire array. But how do I stop it at the end of each index?
Your question is not clear . But from what I understood you must do
for (int k=0;k<6;k++){
int total=0;
for (int i=0;i<7;i++){
total=number[k][i]+total;}
System.out.println(total);}
It will print sum of all rows
Couldn't the loop be like this:
for (int k = 0; k < 6; k++) {
int total = 0;
for (int i = 0; i < 7; i++) {
total += number[k][i];
}
System.out.println(total);
}
Assuming I get what you mean by stop it at the end of each index.
And better should it be if you parametrize your loops to fit in each dimension length:
for (int k = 0; k < number.length; k++) {
int total = 0;
for (int i = 0; i < number[k].length; i++) {
total += number[k][i];
}
System.out.println(total);
}
Related
I can't figure out how I can get the index location of the largest and smallest numbers in an array. Someone who can help me out here?
My code:
int[] array = {4, 2, 7, 6, -3, -1, -2, 42, 0, -42, 9, -4, 5, -5, -6, -7, -8, -99, 42, 11, 20, 1, 2, 3};
int smallest = array[0];
int largest = array[0];
for (int i = 1; i < array.length; i++){
if (array[i] > largest) {
largest = array[i];
} else if (array[i] < smallest)
smallest = array[i];
}
System.out.println("Largest: " + largest);
System.out.println("Smallest: " + smallest);
I have already the largest and smallest numbers, but how can I find the index locations.
Create two more variables to store Largest index and smallest index, now whenever you assign a new value to smallest and largest in if-else statements also assign the value of i.
int smallestInd = 0;
int largestInd = 0;
for (int i = 1; i < array.length; i++){
if (array[i] > largest) {
largest = array[i];
largestInd = i;
} else if (array[i] < smallest)
smallest = array[i];
smallestInd = i;
}
This should work
int[] array = {4, 2, 7, 6, -3, -1, -2, 42, 0, -42, 9, -4, 5, -5, -6, -7, -8, -99, 42, 11, 20, 1, 2, 3};
int si, smallest = array[si = 0];
int li, largest = array[li = 0];
for (int i = 1; i < array.length; i++) {
if (array[i] > largest) {
largest = array[li = i];
} else if (array[i] < smallest) {
smallest = array[si = i];
}
}
System.out.println("Largest: " + li);
System.out.println("Smallest: " + si);
or easier readable:
int[] array = {4, 2, 7, 6, -3, -1, -2, 42, 0, -42, 9, -4, 5, -5, -6, -7, -8, -99, 42, 11, 20, 1, 2, 3};
int si = 0, smallest = array[0];
int li = 0, largest = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > largest) {
largest = array[i];
li = i;
} else if (array[i] < smallest) {
smallest = array[i];
si = i;
}
}
System.out.println("Largest: " + li);
System.out.println("Smallest: " + si);
I was able to came up with two answers :
ary.sort();
console.log(
`This is max ${ary[0]} of the numbers and here is ${
ary[-1]
} the min of the numbers list!`
);
_________________________________________________________________
` let ary = [8, 13, 2, 5, 44, 1, 5, 55];
let max = ary[0];
let min = ary[0];
let locationMax, locationMin;
for (i = 0; i <= ary.length; i++) {
if (ary[i] > max) {
max = ary[i];
locationMax = i;
} else if (ary[i] < min) {
min = ary[i];
locationMin = i;
}
}
console.log(
`This is the location of the max ${locationMax} so The second location number ${locationMin} is for min!`
);
So I have this dummy 2D array:
int mat[][] = {
{10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89}};
I want to add up all the values by columns so it would add 10 + 15 + 27 + 32 and return 84 and so on. I have this so far:
public void sum(int[][] array) {
int count = 0;
for (int rows = 0; rows < array.length; rows++) {
for (int columns = 0; columns < array[rows].length; columns++) {
System.out.print(array[rows][columns] + "\t");
count += array[0][0];
}
System.out.println();
System.out.println("total = " + count);
}
}
Can anyone help with this? Also the System.out.print(array[rows][columns] + "\t" ); prints the array out by rows, is there a way to print it out by columns?
One possible Solution would be to first find maximum size of all sub arrays and iterate that many times to find sum of each column avoiding unavailable values.
public static void main(String[] args) {
int mat[][] = {{10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89},
};
// Find maximum possible length of sub array
int maxLength = 0;
for (int i = 0; i < mat.length; i++) {
if (maxLength < mat[i].length)
maxLength = mat[i].length;
}
for (int i = 0; i < maxLength; i++) {
int sum = 0;
for (int j = 0; j < mat.length; j++) {
// Avoid if no value available for
// ith column from this subarray
if (i < mat[j].length)
sum += mat[j][i];
}
System.out.println("Sum of Column " + i + " = " + sum);
}
}
Use an ArrayList to get the sum of all the columns.
public static void sum(int[][] array) {
ArrayList<Integer> sums = new ArrayList<>();
for (int row = 0; row < array.length; row++) {
for (int column = 0; column < array[row].length; column++) {
if (sums.size() <= column) {
sums.add(column, 0);
}
int curVal = sums.get(column);
sums.remove(column);
sums.add(column, curVal + array[row][column]);
}
}
for (int i = 0; i < sums.size(); i++) {
System.out.println("Sum of column " + i + " = " + sums.get(i));
}
}
Here is one alternative.
The supplied data.
int mat[][] = { { 10, 20, 30, 40, 50, 60, 70, 80, 90 },
{ 15, 25, 35, 45 }, { 27, 29, 37, 48 },
{ 32, 33, 39, 50, 51, 89 }, };
First, find the maximum length of the array in which to store the sum.
int max = Arrays.stream(mat).mapToInt(a -> a.length).max().orElse(0);
Allocate the new array to hold the sums.
int[] sums = new int[max];
Now just use the Arrays.setAll method to sum them, taking careto not exceed the current array's length.
for (int[] arr : mat) {
Arrays.setAll(sums, i-> i < arr.length ? sums[i] + arr[i] : sums[i]);
}
System.out.println(Arrays.toString(sums));
Prints
[84, 107, 141, 183, 101, 149, 70, 80, 90]
You can use Stream.reduce method to summarise the elements of the rows of the matrix by the columns:
int[][] matrix = {
{10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89}};
int[] arr = Arrays.stream(matrix)
// summarize in pairs
// the rows of the matrix
.reduce((row1, row2) -> IntStream
// iterate over the indices
// from 0 to maximum row length
.range(0, Math.max(row1.length, row2.length))
// summarize in pairs the elements of two rows
.map(i -> (i < row1.length ? row1[i] : 0) +
(i < row2.length ? row2[i] : 0))
// an array of sums
.toArray())
// the resulting array
.get();
System.out.println(Arrays.toString(arr));
// [84, 107, 141, 183, 101, 149, 70, 80, 90]
See also:
• Sum of 2 different 2d arrays
• How to calculate the average value of each column in 2D array?
…and the same with lambda:
int[] array = Arrays.stream(mat)
.reduce((a1, a2) -> IntStream.range(0, Math.max(a1.length, a2.length))
.map(i -> i < a1.length && i < a2.length ? a1[i] + a2[i]
: i < a1.length ? a1[i] : a2[i] ).toArray()).get();
gets the sums of each column in the int[] array:
[84, 107, 141, 183, 101, 149, 70, 80, 90]
i just created an array have 100 elements, so now i want get 10 elements print first, secondly i want continuing 10 elements print out, and 10 elements third keep going. My code is below:
int[] array = { 0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,..., 100 };
int count = 0;
for (int i = 0; i < array.length; i++) {
count++;
if (count == 10) {
System.out.println(array[i]);
count = 0;
}
}
Your logic is correct, only issue is with the printing of array values.
int[] array = { 0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,....,100};
int count = 0;
for (int i = 0; i < array.length; i++) {
count++;
System.out.print(array[i]+" ");
if (count == 10) {
System.out.println();
count = 0;
}
}
This can be done fairly easily by iterating through the array with a double for-loop.
One loop will iterate through the modulo index and the other will print the 10 elements with that modulo value.
int[] array = {1,2,3,4,5,6,7,8,9,10,...,100};
for (int offset = 0; offset < array.length/10; offset++)
for (int i = 0 + offset; i < array.length; i+= array.length/10)
System.out.println(array[i]);
//Creating the array
int[] n = {2, 9, 56, 73, 32, 8, 23, 21, 12, 53, 9, 0, 1};
//Creating the sorting algoritm
for(int i = 1; i <= n.length; i++) {
for(int j = 1; j <= n.length; j++) {
if(n[j]<n[i]) {
int c = n[j];
n[j] = n[i];
n[i] = c;
}
}
}
//Printing the values of the array
for(int i = 0; i < n.length; i ++)
System.out.println(n[i]);
}
If you're doing this just to sort it, perhaps try just using Arrays.sort(n).
Documentation for Arrays class
If you're doing it just because you wan't to write your own sort function then there's a lot more that you need to do. Will the Arrays.sort(n) work for your purposes?
The following array shall be sorted.
int[] n = {2, 9, 56, 73, 32, 8, 23, 21, 12, 53, 9, 0, 1};
public int [] sort(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = i+1; j < array.length; j++) {
if ( (array[i] > array[j]) && (i != j) ) {
int temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
}
return array;
}
The array can be sorted by calling sort method with array as parameter e.g.
int[] array = {2, 9, 56, 73, 32, 8, 23, 21, 12, 53, 9, 0, 1};
int[] sortedArray = sort(array);
Based on this answer I've tried to do my roulette wheel selection in genetic algorithm.
private static final int NUMBER_OF_TOURISTS = 20;
private static int[] roulette(int population[]) {
int sumProb = 0;
for (int i = 0; i < population.length; i++) {
sumProb += population[i];
}
int[] rouletteIndex = new int[NUMBER_OF_TOURISTS];
Random r = new Random();
for (int i = 0; i < NUMBER_OF_TOURISTS; i++) {
int numberRand = r.nextInt(sumProb);
//-------------------------------------------------------
int j = 0;
while (numberRand > 0) {
numberRand = numberRand - population[j];
j++;
}
rouletteIndex[i] = j-1;
//-------------------------------------------------------
}
return rouletteIndex;
}
after this I get:
[6, 2, -1, 19, 13, 2, 14, 2, 6, 19, 7, 14, 18, 0, 1, 9, 13, 10, 7, 2]
"-1"? But how, when j should be always greater than 0.
Is this happen when numberRand = 0 and than while loop doesn't start even once? But how to fix this?
Random.nextInt(int bound) returns 0 (inclusive) to specified bound (exclusive).
So your loop:
while (numberRand > 0) {
numberRand = numberRand - population[j];
j++;
}
Will not run if nextInt(int bound) returns 0, resulting in j being 0 at: rouletteIndex[i] = j-1;