I just want to know how this program works, and why the answer is 14.
here is the code:
public class extra {
public static void main(String[] args){
int[][] table = {{1,2,3},{4,5,6},{7,8,9}};
int sum = 0;
for( int i = 2; i > 0; i-- )
sum += table[i][3-i];
System.out.println(sum);
}
}
I understand the way the matrix is set up
123
456
789
but what is i in this problem, because I thought it was the number of rows, but since it is in a for loop, does it mean that i is the number in the matrix? Also how do the [i][3-i] come in to affect? The answer is 14, and I just want to know how it is 14.
It is only summing part of a diagonal, specifically table[2][1] which is 8, and table[1][2] which is 6.
The easiest way to see what is going on is to add an output statement in the loop:
for (int i = 2; i > 0; i--) {
sum += table[i][3 - i];
System.out.println(i + " " + (3 - i) + " " + table[i][3 - i]);
}
your program takes table[2][1] (value of 8) and table[1][2] (value of 6) elements, sums them and prints as output (value of 14)
regarding your question in a title your main method should be more like this:
public static void main(String[] args) {
int[][] table = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int sum = 0;
System.out.println("Before\n");
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
sum += table[i][j];
System.out.printf("Sum after %d iteration: %d\n", i + j + 1, sum);
}
}
System.out.println("\nIn total: " + sum);
}
i + j + 1 is a sum of current iteration which is sum of both axises, and since Java has 0-based indexed tables, it is increased by 1
Hope it helps!
i, in itself, does not correspond directly to anything in the matrix. It is just the name of the variable that the for loop changes each time it loops.
The [i][3-i] is how the i interacts with table. On the first round of the for loop, the i will be equal to 2. Thus, sum will be increased by table[2][1], which is the 3rd row and the 2nd column of the matrix, which has a value of 8.
On the second round of the for loop, the for loop, the i will be equal to 1. Thus, sum will be increased by table[1][2], which is the 2nd row and the 3rd column of the matrix, which has a value of 6.
Therefore, sum will be equal to 8+6=14.
What the for loop does is as follows:
i = 2. Enter loop.
Add table[2][3-2] to sum. Sum is now 8, because table[2][1] = 8.
Decrement i by 1.
i = 1. Enter loop.
Add table[1][3-1] to sum. Sum is now 14, because table[1][2] = 6.
Decrement i by 1.
i = 0. 0 is not greater than 0, so we exit the loop. The sum became 14.
Two-dimensional arrays like int[][] table have two indexes. One for the "outer" array (or rows), and one for the "inner" ones (columns).
Let's use int[][] table = {{1,2,3},{4,5,6},{7,8,9}}; from your code as an example:
table[1][2]: 1 means we should look in the array at index 1, which is {4,5,6}. 2 means we should look at {4,5,6}'s index 2, which is 6. In other words table[1][2] == 6.
table[2][0]: 2 means we should look in the array at index 2, which is {7,8,9}. 0 means we should look at {7,8,9}'s index 0, which is 7.
for (int i = 2; i > 0; i--)
so starting at 2 it checks if i is greater than zero
loops once then i-- subtracts 1
check again still greater than 0
loops again then subtracts 1 again
checks if greater than 0 now 0 it is not greater than 0 so stops looping
//thus loops 2 times
//[0] = 1st [1] = 2nd [2] = third ...
//counting in code starts at zero not 1 so and array of 3 counts a the spaces 0,1,2
int sum = 0;//sum starts at zero
//using the value of i translates as such
sum += table[2][3-2];//[2][1]this is 3rd group 2nd part so sum += 8
//then
sum += table[1][3-1];//[1][2]this is 2nd group 3rd part so sum += 6
0 + 8 + 6 = 14
Here's how to add elements in a 2D array in a easy way.
First when you initialize a 2D array think of the first brackets [ ] as a column and the second bracket [ ] as column rows.
For example: int[][] num = new int[10][5] which means 10 columns and 5 rows.
If you want to fill all the elements in a 2D array you must use two for loops:
int[][] num = new int[10][5];
for (int i =0; i < num.length;i++ ) {
for (int x=0; x < num[0].length;i++) { //we used num[0] because we need the length of the rows not the columns
num[i][x] = //any value you want to assign
}
}
Related
I want to write a code that asks for three numbers dig(1), dig(2), dig(3) and displays a sequence of numbers dig(1), dig(2), dig(3), ..., dig(n) according to this rule:
a = dig(2) - dig(1)
b = dig(3) - dig(2)
dig(n) = dig(n-1) + a if n is odd
dig(n) = dig(n-1) + b if n is even
Example:
7, 8, 5, 6, 3, 4, 1, 2, -1, 0
It asks an user for three integers dig1, dig2, dig3
It asks a number N ≥ 3 which will be the whole sequence count.
It prints a sequence beginning with
Then prints the sequence, beginning with the three leading integers, followed by N-3 other terms that follow the pattern defined by the first three integers. See examples below for more information.
(The sequence begins with n = 1, but of course the array starts at 0.)
int dig1 = 0;
int dig2 = 0;
int dig3 = 0;
int a;
int b;
int n = 0;
int i;
dig1 = scnr.nextInt();
dig2 = scnr.nextInt();
dig3 = scnr.nextInt();
n = scnr.nextInt();
int[] array = new int[n];
array[0] = dig1;
array[1] = dig2;
array[2] = dig3;
a = dig2 - dig1;
b = dig3 - dig2;
for (i = 3; i < n; i++){
if(i%2 == 0){
array[i] = b + array[i-1];
}
else{
array[i] = a + array[i-1];
}
}
System.out.println(array[i]);
}
}
whenever I try to print this out, I get this error:
java.lang.ArrayIndexOutOfBoundsException
Another example: if I put in the numbers: 0 1 0 9 into my input, I should receive back the sequence 0 1 0 1 0 1 0 1 0
Printing array[n-1] gives me back just the final output. I'm trying to iterate through each number.
Sorry if that's unclear, but any help would be great, thank you.
Your System.out.println(array[i]); seems to be out of the for loop. Then i will be equal to n. And there is no element with index n in array with length n. The elements are from 0 to n-1.
At first I thought that you were choosing an array size less than 3, and that the code was failing here, during the initialization of the array:
array[0] = dig1;
array[1] = dig2;
array[2] = dig3;
But now, I actually think that the last line of code is the problem. Have a closer look at your for loop:
for (i=3; i < n; i++) {
if (i % 2 == 0) {
array[i] = b + array[i-1];
}
else {
array[i] = a + array[i-1];
}
}
System.out.println(array[i]);
Appreciate that at the end of the for loop, i, the loop counter, will always be n, the size of the array. Accessing array[n] will always be out of bounds, because an array in Java has a highest addressable index of one less than the actual number of buckets. So, if you were intending to just print the final element, then use this:
System.out.println(array[i-1]);
or
System.out.println(array[n-1]);
at the line n=scrn.nextInt(), you are assigning to n a integer from scrn but you don't know the value of that integer.
Then with this:
int[] array = new int[n];
Your array is of size of n elements starting from index 0 to index n-1.
So let's suppose the value you affected to n with .nextInt() is inferior to 3: initial value of i, the loop will even not be reached, because you will be out of bounds just here:
array[0] = dig1;
array[1] = dig2;
array[2] = dig3;
since you will be attempting to affect a value on an array at an index that does not exists (n is inferior to three but you are trying to affect three values in an array of size n).
Then if n is superior to 3, since your printing code is out from the loop, the value of i is equal to n and there is no value at index n. remember, the loop will leave only if the condition i<n is false and to reach that condition i must be equal or superior and that will lead to an IndexOutOfBoundsException on printing.
I think you printing line code should be inside the for loop.
I'm having a hard time using an array in a for loop that is supposed to cube numbers 1-9 in descending order. I keep getting an out of bounds error and the cubed values are completely off. I would greatly appreciate an explanation as to where I am going wrong with thinking about arrays. I believe the issue is with my index, but I'm struggling to explain why.
System.out.println("***** Step 1: Using a for loop, an array, and the Math Class to get the cubes from 9-1 *****");
System.out.println();
// Create array
int[] values = new int[11];
int[] moreValues = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Create variable to store cubed numbers
double cubedNumber = 0;
// Create for loop to count in descending order
for (int counter = 9; counter < moreValues.length; counter--)
{
cubedNumber = Math.pow(counter,3);
System.out.println(moreValues[counter] + " cubed is " + cubedNumber);
}
Output
Your main bug is the loop termination condition counter < moreValues.length, which if you're counting down will always be true.
Instead, check for the index being at or above zero:
for (int counter = 9; counter >= 0; counter--)
Your other bug is you're cubing the index, not the number pointed to by the index, so code this instead;
cubedNumber = Math.pow(moreValues[counter], 3);
To reduce confusion, you're better using an industry standard name for the loop variable, like i or where the loop variable is being used as an index to an array, index is often used and can improve code clarity.
Try:
for (int counter = moreValues.length; counter >= 1; counter--)
{
cubedNumber = Math.pow(counter,3);
System.out.println(moreValues[counter-1] + " cubed is " + cubedNumber);
}
if we have these numbers in
array [][]
{1, 2, 3, 4},
{1, 2, 20, 4},
{1, 20, 2, 4},
{1, 2, 3, 4},};
it should looks like this
1 0 0 4
0 0 0 0
0 0 0 0
1 0 0 4
but i could output code only like this...
1 0 3 4
1 0 20 4
0 0 0 0
1 0 3 4
and i don't understand how to correct it, please help me,
this is my code.Thanks!
package com.company;
public class Main {
public static void main(String[] args) {
int[][] array2 = {{1, 2, 3, 4},
{1, 2, 20, 4},
{1, 20, 2, 4},
{1, 2, 3, 4},};
int countMax = 0;
int countIndexHorizontal = 0;
int countIndexVertical = 0;
int max = Integer.MIN_VALUE;
int m, k,x;
for (int i = 0; i < array2.length; i++) {
for (int j = 0; j < array2[i].length; j++) {
if (array2[i][j] > max) {
max = array2[i][j];
}
}
}
for (k = 0; k < array2.length; k++) {
for (m = 0; m < array2[k].length; m++) {
if (array2[k][m] == max) {
countIndexHorizontal = k;
countIndexVertical = m;
for (x = 0; x < array2.length; x++) {
for (int j = 0; j < array2[x].length; j++) {
if (countIndexVertical == x || j == countIndexHorizontal) {
array2[x][j] = 0;
}
}
}
}
}
}
for (int i = 0; i < array2.length; i++) {
for (int j = 0; j < array2[i].length; j++) {
System.out.print(array2[i][j] + " ");
}
System.out.println();
}
}
}
it looks like there are a lot of code and a little of words and site don't allow me to finally post my question and i'm really angry, maybe this text will help me to solve this problem.
Algorithm
This is the part when you only use pen and paper. Basically, I understood the problem as follow:
Given a matrix with n rows and m columns of Integer1:
Find the highest value
All entries in the rows and columns holding the highest value must have its value set at 0
Print the updated matrix
Assumption
I made the following assumptions:
In n is not necessarily equal to m. For example, you can have the array:
Valid Input
1 2 3 4 5 6
7 8 9 10 11 12
7 8 12 5 6 4
which must give, as 12 is the highest value:
Output
1 2 0 4 5 0
0 0 0 0 0 0
0 0 0 0 0 0
The matrix is consistent: every row has m columns and every column has n rows. For example, such input is incorrect:
Incorrect input
1 2 3
7 8 9 10
7 8
Logic
At this stage, you're still using pen, paper and Google only!
In my problem understanding, I splitted in three parts as I thought this is how you understood the problem. This is the mathematics understanding. Now let's convert it into a more Java understanding. First of all, we need to translate some vocabulary:
Mathematics wording | Java wording
--------------------|---------------------
matrix | 2-dimensional array
Integer | int (primitive type)
which gives in Java way:
Given an 2-dimensional int[][] array:
Find the highest value
Find the rows and columns holding the highest value
Update the array by setting the value to 0 for the rows and columns found in 2.
Print the array
In the specific case of my solution, I combine 1. + 2. and I combined 3. + 4.
What you did
Let's open your favorite IDE and compare my analysis with your input:
Find the highest value: OK here: : you use the variable max and scan the matrix to find the maximum value. You also assumed that the matrix could be rectangle (n rows and m columns with n != m). So it's good
for (int i = 0; i < array2.length; i++) {
for (int j = 0; j < array2[i].length; j++) {
if (array2[i][j] > max) {
max = array2[i][j];
}
}
}
Find the rows and columns: ERROR here, as mentioned by ccp-beginner, when you found a the highest value, you erase (set to zero) the value for the whole column and whole row but maybe the same highest value was stored somewhere else in this row or column
for (k = 0; k < array2.length; k++) {
for (m = 0; m < array2[k].length; m++) {
if (array2[k][m] == max) {
countIndexHorizontal = k;
countIndexVertical = m;
// additional operation defined in 3.
}
// in ccp-beginner example of
// 2, 2
// 1, 1
// if k=0 and m=0, you'll update the value
// of the first row and first column giving:
// 0, 0
// 0, 1
// but when k=0, m=1, you'll find 0 instead
// of 2 so your program will consider that
// this row / column does not contain the
// highest value
}
}
I assume here the
countIndexHorizontal = row
countIndexVertical = column
So you need to keep track of the rows and columns when you're setting the values to 0.
Update the array: ERROR here (cf ccp-beginner's answer)
for (x = 0; x < array2.length; x++) {
for (int j = 0; j < array2[x].length; j++) {
if (countIndexVertical == x || j == countIndexHorizontal) {
array2[x][j] = 0;
// In your example:
// 1 2 3 4
// 1 2 20 4
// 1 20 2 4
// 1 2 3 4
// and if countIndexVertical=2 and countIndexHorizontal=1
// (the 20 of the second row between 2 and 4), you'll have
// 1 0 3 4
// 1 0 20 4
// 0 0 0 0
// 1 0 3 4
// instead of
// 1 2 0 4
// 0 0 0 0
// 1 20 0 4
// 1 2 0 4
}
}
}
you got confused between countIndexVertical and countIndexHorizontal, as you have
x = row
j = column
You should had (please notice the swapping)
if (countIndexHorizontal == x || j == countIndexVertical) {
array2[x][j] = 0;
}
Print the array: OK here, nothing special to mention
for (int i = 0; i < array2.length; i++) {
for (int j = 0; j < array2[i].length; j++) {
System.out.print(array2[i][j] + " ");
}
System.out.println();
}
The problem
Basically, what you need is how to store the rows and the columns containing the highest value. At first, we could be tempted to use array again right, like
int[] rowsContainingHighestValue;
int[] columnsContainingHighestValue;
But you don't know how many highest value you'll encounter so you need something to store multiple value with a dynamic size: I'll use List.
Some Java point
The rowsContainingHighestValue and columnsContainingHighestValue become:
List<Integer> rowsContainingHighestValue = new ArrayList<>();
List<Integer> columnsContainingHighestValue = new ArrayList<>();
You may want to have a look at the following point:
Why List instead of array?
My objects are declared as List but I instantiate2 with ArrayList: What is a Interface and what is a Class
Why I used List<Integer> instead of List<int>
What is the difference between Integer and int
One solution
loop through for the matrix to fetch the maximum value and store all rows and columns holding this value instead of a single row/column combination (countIndexHorizontal and countIndexVertical)
If a new maximum value is found, store it (like you did) AND store the current row and column index
If a value is identical to the current maximum value (e.g. you have 20 twice), then append the row and column index to the existing respective row / column list
loop a second time for updating and printing the value
it's basically combining your two last double-loop: if the scanned element belongs to a row or a column holding the maximum value, then the value must be set at 0 (exactly the way you did but shorter as I already have the list of rows / columns)
once the values are properly updated, just proceed to a simple printing
Which in code gives:
public static void main(String[] args) {
int[][] array2 = {
{1, 2, 3, 4},
{1, 2, 20, 4},
{1, 20, 2, 4},
{1, 2, 3, 4}
};
// find the maximum value and store its position:
// It's List instead of a single value as multiple
// rows and columns can hold the same maximum value
List<Integer> rowsWithMaxValue = new ArrayList<>();
List<Integer> colsWithMaxValue = new ArrayList<>();
int maxValue = Integer.MIN_VALUE;
// First matrix-scan to fetch the maximum value and the
// row(s) and column(s) to set the value at 0
for (int row = 0; row < array2.length; row++) {
for (int col = 0; col < array2[row].length; col++) {
// get the current value
int value = array2[row][col];
// found a new maximum or an existing one?
if (value > maxValue) {
// this is a new maximum value, we can reset
// the list as the previous rows and columns
// are not relevant anymore
maxValue = value;
rowsWithMaxValue = new ArrayList<>();
colsWithMaxValue = new ArrayList<>();
rowsWithMaxValue.add(row);
colsWithMaxValue.add(col);
} else if (value == maxValue) {
// The same value (like 20) is found again
// so multiple rows and columns will have
// their value set at 0
rowsWithMaxValue.add(row);
colsWithMaxValue.add(col);
}
}
}
// Second matrix-scan for updating the values and printing
for (int row = 0; row < array2.length; row++) {
for (int col = 0; col < array2[row].length; col++) {
// is it in a forbidden row? If yes, set the value
// at zero. One of the condition (row or column) is
// enough to have its value set at 0
if (rowsWithMaxValue.contains(row) || colsWithMaxValue.contains(col)) {
array2[row][col] = 0;
}
// Simply print the value
System.out.print(array2[row][col] + " ");
}
System.out.println();
}
}
1Integer in the mathematics meaning: positive or negative number without decimal
2I won't explain instantiation here. Feel free to google it
You can improve the program by changing the condition to
if (countIndexHorizontal == x || j == countIndexVertical)
Your program is deleting the wrong lines for the first 20 it finds (including the other 20).
This change will get you the correct answer for your specific case, but the program is still broken for examples like this
2 2
1 1
The correct output is
0 0
0 0
but it won't work because when it finds the first 2 it will delete the second 2, but the second 2 is still needed to clear the 0 in the bottom right corner. You're going to have to keep a separate data structure for the positions you want to clear. I'll leave that for you to figure out.
Given an array with any size, in my case the array size is 5.
This array contains ALL numbers from 1 to 5 (must contain all of them)
[1 | 2 | 3 | 4 | 5]
0 1 2 3 4
And now, one element was reset and was set to 0, and the mission is to find what number it used to be before it turned 0.
So I have this simple solution:
Explained: First, loop from 1 to 5, create an inner loop to check if the i from the first loop exists in the whole array, if it doesn't exist, that means that it is the value it used to be before 0, because the array contained all numbers from 1 to 5 or 1 to 100 (doesn't matter) and there's on'y one rested element.
Code:
int[] numbers = new int[]{1, 2, 3, 4, 5};
numbers[1] = 0;
int lost = -1;
loop:
for (int i = 1; i <= numbers.length; i++) {
for (int j = 0; j < numbers.length; j++) {
if (numbers[j] == i) {
continue loop;
}
}
lost = i;
break loop;
}
System.out.println(lost);
That solution is not bad, but I think there's a better solution, something more stable.
I have thought about it mathematically, in our example:
1 + x + 3 + 4 + 5 = 15
x = 2
Mathematically, it's really easy. Is there a way this can be done in a programming language as easy as it is mathematically?
Any better algorithms you can think of to solve this question?
This works for ONE element being reset. Just subtract each remaining element from the sum and what ever is left over would have been the previous number the element was before it was reset.
public static void main(String[] args) throws Exception {
int sum = 15;
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
numbers[4] = 0;
for (int i = 0; i < numbers.length; i++) {
sum -= numbers[i];
}
System.out.println(sum);
}
Results:
5
There is one more possibility, you can use HashMaps!
you don't have to traverse through any "for loops" then.
You can use Hashmaps to check whether is there any value for the key of "0", if yes then that is the case where some number is reset to 0.
Then you can traverse the Hashmap and compare which value is missing.
Everything is done With O(1) complexity and worst case of O(n) complexity.
A perfect number is one that is the sum of its factors, excluding itself. The 1st perfect number is 6 because 6 = 1 + 2 + 3. The 2nd perfect number is 28 which equals 1 + 2 + 4 + 7 + 14. The third is 496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248. In each case, the number is the sum of all its factors excluding itself.
Write a method named henry that takes two integer arguments, i and j and returns the sum of the ith and jth perfect numbers. So for example, henry (1, 3) should return 502 because 6 is the 1st perfect number and 496 is the 3rd perfect number and 6 + 496 = 502.
I have done this far:: but this is showing ArrayIndexOutOfBoundException at this line temp[index] = j; please help me to solve this OutOfBound issue, Thanks..
public static int henry (int a, int b){
List<Integer> arr = new ArrayList<Integer>();
int henryNumber = 0;
for(int i=4;;i++){
List<Integer> temp = new ArrayList<Integer>();
int sum = 0;
for(int j = 1; j<i; j++){
if(i%j == 0 ) { temp.add(j); }
}
for (Integer item : temp) { sum+=item; }
if(sum == i) arr.add(i);
if(arr.size() == b) {
henryNumber = arr.get(a-1) + arr.get(b-1);
break;
}
}
return henryNumber;
}
int[] temp = {};
This sets temp to an array of 0 elements. So when you try to access temp[index] where index is = to 0 its out of bounds because the array doesn't have even a single element
You would need to create an array of x number elements by doing:
int[] temp = new int[x];
and then you can set the value at each of the indicies to whatever value you want.
An array has a fixed length as soon as it it created, and that length cannot be changed.
int[] temp = {};
This creates an empty array. Its length is zero. You can't change that, you can't add any items to it.
temp[index] = j;
This tries to put something in the temp array. However, as I said, the array is empty, its length is zero, so any value of index would be out of bounds.
Using a List (which is commented out in your source) will allow you to create a growing collection of elements. Alternatively, you have to think of a proper size for your array, that will hold all the elements you'll be using, and use that size when you create the array.
Try doing
int[] temp=new int[i];
instead of
int[] temp={};
I have never assigned an array like this before.