new programmer here and I am a little confused on this code sample I'm working on. Basically I'm taking arrayA and passing it down to my method, I would then like my method to take and multiply each adjacent numbers, therefore my total should come out to 962, return it back to main and sopln it out.
public class 8a
{
public static void main(String [] args)
{
int [] arrayA = {10,5,100,3,6,2,30,20};
int result = sumOfProducts(arrayA);
}
public static int sumOfProducts(int [] a)
{
int counter = 1;
for(int x = 0; x < a.length; x++)
}
}
Are you sure 962 is the correct result? If you multiply each adjacent number and sum up the results, your return value should be 1540. You seem to take only every other pair into consideration:
10*5 ok
5*100 not
100*3 ok
3*5 not
...etc.
If you want to sum up of the results of every adjacent pair multiplication (also the ones marked with 'not'), you can simply go through the array like this:
int sum= 0;
for(int x = 0; x < arrayA.length-1; x++)
sum+=(arrayA[x]*arrayA[x+1]);
On the other hand, if you are REALLY 100% sure you want to leave out every other pair and get to the 962 result:
int sum= 0;
for(int x = 0; x < arrayA.length-1; x+=2)
sum+=(arrayA[x]*arrayA[x+1]);
However, this only works for arrays with an even number of entries. And since this is part of an exercise, i would consider the first solution to be far more likely to be the indended one.
Related
I have been trying to implement the given formula in JAVA but i was unsuccessful. Can someone help me find what I am doing wrong?
Do i need to shift the summation index and if so how?
My code:
public final class LinearSystem {
private LinearSystem() {
}
public static int[] solve(int [][]A , int []y) {
int n = A.length;
int[] x = new int[n];
for (int i = 0 ; i < n; i++) {
x[i] = 0;
int sum = 0;
for(int k = i + 1 ; k == n; k++) {
sum += A[i][k]*x[k]; // **java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3**
}
x[i] = 1/A[i][i] * (y[i] - sum);
}
return x;
}
public static void main(String[] args) {
int[][]A = new int[][]{{2,-1,-3},{0,4,-1},{0,0,3}};
int [] y = new int[] {4,-1,23};
System.out.println(Arrays.toString(solve(A,y))); **// awaited result [2, -3, 1]**
}
}
Just trying to collect all my comments under the question into one coherent answer, since there are quite a few different mistakes in your program.
This method of solving linear equations relies on your calculating the components of the answer in reverse order - that is, from bottom to top. That's because each x[i] value depends on the values below it in the vector, but not on the values above it. So your outer loop, where you iterate over the x values needs to start at the biggest index, and work down to the smallest. In other words, instead of being for (int i = 0; i < n; i++), it needs to be for (int i = n - 1; i >= 0; i++).
The inner loop has the wrong stopping condition. With a for loop, the part between the two semicolons is the condition to continue iterating, not the condition to stop. So instead of for(int k = i + 1; k == n; k++), you need for(int k = i + 1; k < n; k++).
You're doing an integer division at the beginning of 1 / A[i][i] * (y[i] - sum);, which means the value is rounded to an integer before carrying on. When you divide 1 by another integer, you always get -1, 0 or 1 because of the rounding, and that makes your answer incorrect. The fix from point 4 below will deal with this.
The formula relies on the mathematical accuracy that comes with working with either floating point types or decimal types. Integers aren't going to be accurate. So you need to change the declarations of some of your variables, as follows.
public static double[] solve(double[][] A, double[] y)
double x[] = new double[n];
double sum = 0.0;
along with the corresponding changes in the main method.
First, you need the second loop to go until k < n, otherwise this throws the ArrayOutOfBounds Exceptions.
Second, you need to calculate your x in reverse order as #Dawood ibn Kareem said.
Also, you probably want x[] to be a double-array to not only get 0-values as result.
I am sorry I don't know much about math side so I couldn't fix it to the right solution but I noticed a few things wrong about your code.
1-You shouldn't initialize your arrays as integer arrays, because you will be doing integer division all over the place. For example 1/A[i][i] will result in 0 even if A[i][i] = 2
2-You shouldn't write k == n, if you do it like this then your for loop will only execute if k equals n, which is impossible for your case.
I think you want to do k < n, which loops from i+1 to the point where k = n - 1
Here is my code:
import java.util.Arrays;
public final class LinearSystem {
private LinearSystem() {
}
public static double[] solve(double [][]A , double []y) {
int n = A.length;
double[] x = new double[n];
for (int i = 0 ; i < n; i++) {
x[i] = 0;
int sum = 0;
for(int k = i + 1 ; k < n; k++) {
sum += A[i][k] * x[k]; // **java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3**
}
x[i] = 1/A[i][i] * (y[i] - sum);
}
return x;
}
public static void main(String[] args) {
double[][]A = new double[][]{{2,-1,-3},{0,4,-1},{0,0,3}};
double [] y = new double[] {4,-1,23};
System.out.println(Arrays.toString(solve(A,y))); // awaited result [2, -3, 1]**
}
}
Remember that arrays are indexed from 0, so the last element is at index n - 1, not n.
As part of a program I'm building I need to iterate through all the points in a tridimensional matrix.
On each point I need to execute a method that takes int x, int y, int z as parameters.
The tridimensional matrix always has the same width(16) length(16) & height(256).
What is the most performant way of doing the iteration?(i'm specially concerned about CPU, not so concerned about ram usage)
Based on what i know , I think this are the most efficient methods, but I'm open to other suggestions if they are faster.
A. Iterate directly:
public void doSomethingForAllPointsInMatrix(Matrix matrix){
for(int x= 0; x<16; x++){
for(int z = 0; z<16; z++){
for(int y = 0; y<256; y++){
matrix.doSomething(x,y,z);//A method out of my control without any alternatives
}
}
}
}
B. Iterate an array containing the coordinates
private static final int[] zeroToFifteen; //Contains every number from 0 to 15
private static final int[] zeroToTwoHundredFiftyFive; //Contains every number from 0 to 255
public void doSomethingForAllPointsInMatrix(Matrix matrix){
for(int x: zeroToFifteen){
for(int z: zeroToFifteen){
for(int y: zeroToTwoHundredFiftyFive){
matrix.doSomething(x,y,z);//A method out of my control without any alternatives
}
}
}
}
Thanks in advance for any help you can provide!
A counting loop is already one of the most efficient iteration mechanisms.
Your idea to incorporate an array indicates that you are not aware that the for-each loop over an array is just syntactic sugar for a counting loop over the indices from zero to the array length.
In other words, your
public void doSomethingForAllPointsInMatrix(Matrix matrix){
for(int x: zeroToFifteen){
for(int z: zeroToFifteen){
for(int y: zeroToTwoHundredFiftyFive){
matrix.doSomething(x,y,z);//A method out of my control without any alternatives
}
}
}
}
is basically equivalent to
public void doSomethingForAllPointsInMatrix(Matrix matrix){
for(int index1 = 0; index1 < zeroToFifteen.length; index1++){
int x = zeroToFifteen[index1];
for(int index2 = 0; index2 < zeroToFifteen.length; index2++){
int z = zeroToFifteen[index2];
for(int index3 = 0; index3 < zeroToTwoHundredFiftyFive.length; index3++){
int y = zeroToTwoHundredFiftyFive[index3];
matrix.doSomething(x,y,z);//A method out of my control without any alternatives
}
}
}
}
differing from the counting loop of your first approach only by doing additional array operations, which is very unlikely to improve the performance.
Since your bounds are powers of two, you could do the entire operation with a single loop
public void doSomethingForAllPointsInMatrix(Matrix matrix) {
for(int coord = 0; coord < 0x10000; coord++) {
matrix.doSomething(coord >> 12, coord & 0xff, (coord >> 8)&0xf);
}
}
reducing the number of conditionals. However, the actual performance depends on what the JVM’s optimizer makes out of it and it might be that it can deal better with the nested loops.
So you can only try and benchmark the approaches, to find “the best”, whereas “the best” may be different, depending on the system and the JVM implementation/version.
As said in the comments, the performance is likely dominated by whatever doSomething does and if the processing order is not important for your program logic, you should try with alternative iteration orders, as it may affect how the caches are utilized.
So this is a coding question from school I have, I don't want to say "hey guys do my homework for me!", I actually want to understand what's going on here. We just started on arrays and they kind of confuse me so I'm looking for some help.
Here's the complete question:
Write a program in which the main method creates an array with
10 slots of type int. Assign to each slot a randomly-generated
integer. Call a function, passing it the array. The called
function should RETURN the largest integer in the array to
your main method. Your main method should display the number
returned. Use a Random object to generate integers. Create it
with
Random r = new Random(7);
Generate a random integer with
x = r.nextInt();
So, here's what I have so far:
import java.util.Random;
public class Q1 {
public static void main(String[] args) {
Random r = new Random(7);
int[] count = new int[11];
int x = r.nextInt();
for (int i = 0; i < count.length; i++)
{
count[i] = x;
}
}
I created that array with 10 ints, then used a for loop to assign each slot that randomly generated integer.
I'm having a hard time for what to do next, though. I'm not sure what kind of method / function to create and then how to go from there to get the largest int and return it.
Any help is really appreciated because I really want to understand what's going on here. Thank you!
Here is how to generate Random ints
public static void main(String[] args) {
int []count = new int[10];
Random r = new Random(7);
int x=0;
for (int i = 0; i < count.length; i++)
{
x = r.nextInt();
count[i] = x;
}
System.out.println("Max Number :"+maxNumber(count));}//Getting Max Number
Here is how to make method and get max number from list.
static int maxNumber(int[] mArray){//Passing int array as parameter
int max=mArray[0];
for(int i=0;i<mArray.length;i++){
if(max<mArray[i]){//Calculating max Number
max=mArray[i];
}
}
return max;//Return Max Number.
}
Ask if anything is not clear.
This is how we make method which return int.
You can do it by using a simple for loop for the Array.
First you have to create a seperate int variable (eg: int a) and assign value zero (0) and at each of the iterations of your loop you have to compare the array item with the variable a. Just like this
a < count[i]
and if it's true you have to assign the count[i] value to the variable a . And this loop will continue until the Array's last index and you will have your largest number in the a variabe. so simply SYSOUT the a variable
Important: I didn't post the code here because I want you to understand the concept because If you understand it then you can solve any of these problems in future by your self .
Hope this helps
What you have got so far is almost correct, but you currently are using the same random number in each iteration of your for-loop. Even though you need to get a new random number for each iteration of your for-loop. This is due to how the Random object is defined. You can achieve this by changing your code the following way:
import java.util.Random;
public class Q1 {
public static void main(String[] args) {
Random r = new Random(7);
int[] count = new int[11];
for (int i = 0; i < count.length; i++)
{
int x = r.nextInt(); // You need to generate a new random variable each time
count[i] = x;
}
}
Note that this code is not optimal but it is the smallest change from the code you already have.
To get the largest number from the array, you will need to write another for-loop and then compare each value in the array to the largest value so far. You could do this the following way:
int largest = 0; // Assuming all values in the array are positive.
for (int i = 0; i < count.length; i++)
{
if(largest < count[i]) { // Compare whether the current value is larger than the largest value so far
largest = count[i]; // The current value is larger than any value we have seen so far,
// we therefore set our largest variable to the largest value in the array (that we currently know of)
}
}
Of course this is also not optimal and both things could be done in the same for-loop. But this should be easier to understand.
Your code should be something like this. read the comments to understand it
public class Assignment {
public static int findMax(int[] arr) { // Defiine a function to find the largest integer in the array
int max = arr[0]; // Assume first element is the largest element in the array
for (int counter = 1; counter < arr.length; counter++) // Iterate through the array
{
if (arr[counter] > max) // if element is larger than my previous found max
{
max = arr[counter]; // then save the element as max
}
}
return max; // return the maximum value at the end of the array
}
public static void main(String[] args) {
int numberofslots =10;
int[] myIntArray = new int[numberofslots]; // creates an array with 10 slots of type int
Random r = new Random(7);
for (int i = 0; i < myIntArray.length; i++) // Iterate through the array 10 times
{
int x = r.nextInt();
myIntArray[i] = x; // Generate random number and add it as the i th element of the array.
}
int result = findMax(myIntArray); // calling the function for finding the largest value
System.out.println(result); // display the largest value
}
}
Hope you could understand the code by reading comments..
This can be done in one simple for loop no need to have 2 loops
public static void main(String[] args) {
Integer[] randomArray = new Integer[10];
randomArray[0] = (int)(Math.random()*100);
int largestNum = randomArray[0];
for(int i=1; i<10 ;i++){
randomArray[i] = (int)(Math.random()*100);
if(randomArray[i]>largestNum){
largestNum = randomArray[i];
}
}
System.out.println(Arrays.asList(randomArray));
System.out.println("Largest Number :: "+largestNum);
}
Initialize max value as array's first value. Then iterate array using a for loop and check array current value with max value.
OR you can sort the array and return. Good luck!
Here's a basic method that does the same task you wish to accomplish. Left it out of the main method so there was still some challenge left :)
public int largestValue(){
int largestNum;
int[] nums = new int[10];
for (int n = 0; n < nums.length; n++){
int x = (int) (Math.random() * 7);
nums[n] = x;
largestNum = nums[0];
if (largestNum < nums[n]){
largestNum = nums[n];
}
}
return largestNum;
}
import java.util.Arrays;
public class main {
public static void main (String[] args ) {
int rand = (int)Math.random()*17;
int[][] output = array(rand);
//System.out.println(Arrays.deepToString(output));
}
public static int[][] array(int n) { //btw n is y/height
int x = (int)Math.pow(2, n-1); //# of col
int max = (int)Math.pow(2, n) - 1;
int [][] out = new int[n][x];
for (int i = 0; i < n; i++) {
for (int j = 0; j < x; j++) {
out[i][j] = (int) (Math.random() * (max + 1));
}
}
return out;
}
}
I'm learning how to code and a cousin gave me their old laptop and I found some small java files here and there. This one is called "itsmagic.java" but I don't really understand what the purpose is?
From what I understand it seems that we are creating a 2D array of some sort and then what? I understand that deepToString is supposed to be used to convert multidimensional arrays to strings, but how does that work? Why is it commented out?
What I understood from your code is:
-Pick a random int n from 0 to 17.
-setting a x = 2^(n-1)
-setting a max= 2^n
-Creating a double entry tab dimensions n*x
-Filling each case with a random number between 0 and max
So the result is a double entry tab of dimensions [0 to 17][2^(0 to 16)] filled with numbers between 0 and 2^(0 to 17)
Arrays.deepToString() is used for either single or multidimensional arrays, it's usually used for multidimensional arrays as it can clearly output each array.
You will be able to output both the first and second array of "output" in your example.
If you run a test and add in the array manually, you will see it prints both the arrays together instead of showing just the first dimension.
A project I am doing requires me to find horizontal and vertical sums in 2 dimensional arrays. So pretty much its a word search (not using diagonals) but instead of finding words, the program looks for adjacent numbers that add up to int sumToFind. The code below is what I have come up with so far to find horizontal sums, and we are supposed to implement a public static int[][] verticalSums as well. Since I have not yet completed the program I was wondering, first of all, if what I have will work and, secondly, how the array verticalSums will differ from the code below. Thank you
public static int[][] horizontalSums(int[][] a, int sumToFind) {
int i;
int start;
int sum = 0;
int copy;
int [][] b = new int [a[0].length] [a.length];
for (int row = 0; row < a.length; row++) {
for ( start = 0; start < a.length; start++) {
i = start;
sum = i;
do {
i++;
sum = sum + a[row][start];
}
while (sum < sumToFind);
if(sum == sumToFind) {
for (copy = start; copy <= i; copy++) {
b[copy] = a[copy];
}
}
for (i = 0; i < a[0].length; i++) {
if (b[row][i] != a[row][i])
b[row][i] = 0;
}
}
}
return b;
}
Your code won't work.... (and your question is "if what I have will work?" so this is your answer).
You declare the int[][] b array as new int [a[0].length] [a.length] but I think you mean: new int [a.length] [a[0].length] because you base the row variable off a.length, and later use a[row][i].
So, if your array is 'rectangular' rather than square, you will have index-out-of-bounds problems on your b array.
Your comments are non-existent, and that makes your question/code hard to read.
Also, you have the following problems:
you set sum = i where i = start and start is the index in the array, not the array value. So, your sum will never be right because you are summing the index, not the array value.
in the do..while loop you increment i++ but you keep using sum = sum + a[row][start] so you just keep adding the value to itself, not the 'next' value.
At this point it is obvious that your code is horribly broken.
You need to get friendly with someone who can show you how the debugger works, and you can step through your problems in a more contained way.
Test is very simple
public static void main(String[] args) {
int[][] a = {{1, 2}, {1, 0}};
int[][] result = Stos.horizontalSums(a, 1);
System.out.println(Arrays.deepToString(result));
}
Result
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
When you fix this problem, then this should print something like this
[[1, 2], [1, 0]]