for loop math with array in java - java

I'm trying to practice using Arrays methods in java. I used the following code to make an Java array:
int numArr[] = new int[10];
for(int i = 0; i< numArr.length;++i)
{
numArr[(numArr.length)-i-1] = (i+1)*2;
System.out.println("numArr[i]" + numArr[i]);
}
My intention was to use this to make the list 20,18,...,4,2. Then, I wanted to use the Arrays sort method to see if it worked properly.
The odd result that I can't understand is that above code prints:
numArr[i] = 0;
numArr[i] = 0;
numArr[i] = 0;
numArr[i] = 0;
numArr[i] = 0;
numArr[i] = 10;
numArr[i] = 8;
numArr[i] = 6;
numArr[i] = 4;
numArr[i] = 2;
I understand the simple mistake with printing the i each time but I don't understand why the initial results are all the 0. I thought maybe it just failed and they were still just initialized to the 0 default. But then I realized that after later in the code after using Arrays.sort(), the list prints correctly for all of the indexes 2,4,...,18,20.
What mistake am I making on the pre-sorted array print?

Your mistake is in how you are indexing into the array in the loop. You are assigning to array element (numArr.length)-i-1 but printing array element i. Try printing array element (numArr.length)-i-1 inside the loop to see the value you just assigned.

Let's say i=0, or the first loop.
numArr[(numArr.length)-i-1] = (i+1)*2;
Run that through, you get
numArr[9] = 2;
Yet, you print numArr[0], which is not yet assigned.
You'll start seeing values once you reach the midpoint of the array
If you are still confused, write out your algorithm on paper

You are trying to print the results even before they are populated in the array.
Here you are populating from behind but trying to print from front(Which are not yet given any value)
Wait for the array to get populated and loop through the array to get the proper result
Doing this should solve your problem,
for(int i = 0; i< numArr.length;++i)
{
numArr[(numArr.length)-i-1] = (i+1)*2;
}
for(int i = numArr.length-1; i>-1;i--)
{
System.out.println(numArr[i]);
}

You are trying to print indexes which has their default value (0) in it. Instead, try printing the indexes which you've already assigned a value into
for(int i = 0; i< numArr.length;++i)
{
numArr[i] = (i+1)*2;
System.out.println("numArr[i]" + numArr[i]);
}
or
for(int i = 0; i< numArr.length;++i)
{
numArr[(numArr.length)-i-1] = (i+1)*2;
System.out.println("numArr[i]" + numArr[(numArr.length)-i-1]);
}

As #Vinay pointed out when printing you are using i as subscript for array elements that didn't get populated yet. If you want to print array while populated you have to use the same index
int numArr[] = new int[10];
for(int i = 0; i< numArr.length;++i)
{
numArr[(numArr.length)-i-1] = (i+1)*2;
System.out.println("numArr[(numArr.length)-i-1]);
}

The easiest way is populate the array and then print the result with another loop:
Test:
public class Test
{
public static void main ( String [ ] args )
{
int numArr[] = new int[10];
for(int i = 0; i< numArr.length;++i)
{
numArr[(numArr.length)-i-1] = (i+1)*2;
}
for(int i = 0; i < numArr.length; i++)
{
System.out.println("numArr["+i+"]" + numArr[i]);
}
}
}
Output:
numArr[0]20
numArr[1]18
numArr[2]16
numArr[3]14
numArr[4]12
numArr[5]10
numArr[6]8
numArr[7]6
numArr[8]4
numArr[9]2

int numArr[] = new int[10];
for(int i = numArr.length-1; i >= 0; i--)
{
numArr[i] = (i+1)*2;
System.out.println("numArr["+i+"]" + numArr[i]);
}
Output:
numArr[9]20
numArr[8]18
numArr[7]16
numArr[6]14
numArr[5]12
numArr[4]10
numArr[3]8
numArr[2]6
numArr[1]4
numArr[0]2
Is this what you wanted to look like?
[Vote up if helped]

Related

Converting this line of code to a for loop

So in java, This is what I'm trying to execute:
num [0]=list.get(2);
num [1]=list.get(4);
num [2]=list.get(6);
num [3]=list.get(8);
I have an arraylist of integers called list and I want to put the values that are in the even number indices starting at 2 into an array of integers called num in the indices 0,1,2,3,etc. My problem is, I'm trying to do this within a for loop but I'm not sure how to go about it. Here is what I have:
for (int i=0; i<list.size()-2; i++){
num[i] = list.get(i+2);
}
My problem here is, after incrementing i, my arraylist goes to the next index also instead of every other index. I've tried multiple variations of this loop but I keep coming to the same problem.
This should do it:
int max = list.size()/2;
if(list.size()%2==0) max-=1; // prevents IndexOutOfBounds for even list lengths
for (int i=0; i<max; i++){
num[i] = list.get(i*2 + 2);
}
You can try something like this.
for (int i=0,j=0; i<list.size()-2; i+=2,j++){
num[j] = list.get(i+2);
}
The loop should continue as long as the i is less then (list.size()-1)/2
List<Integer> list = Arrays.asList(0,1,2,3,4,5,6);
int size = (list.size()-1)/2;
int[] num = new int[size];
for (int i=0; i<size; i++){
num[i] = list.get(i*2+2);
}
System.out.println("num="+ Arrays.toString(num));
Here is DEMO
This should work:
for(int i = 0; i < list.size() - 2; i++)
num[i] = list.get((i * 2) + 2);

Sort all Columns independently form a 2d array java

I need to have the columns organized in increasing order. Right now I have the following done but, it is sorting the rows and not columns.Any help would be nice, ive been working on this all day. Thanks.
public static double[][] sortColumns(double[][] m) {
double[][] sortedArray = new double[m.length][m.length];
for (int i = 0; i < m.length; i++) {
double[] temp = new double[m.length];
for (int j = 0; j < m.length; j++) {
temp[j] = m[j][i];
}
Arrays.sort(temp);
for (int j = 0; j < temp.length; j++) {
sortedArray[j][i] = temp[j];
}
}
return sortedArray;
}
If you change
temp[j] = m[j][i];
to
temp[j] = m[i][j];
and
sortedArray[j][i] = temp[j];
to
sortedArray[i][j] = temp[j];
then your existing algorithm will work fine. It just means you'll be copying columns to your "temporary sorting area" instead of rows.
In your current solution, you are just mistaking on indexes, just like David Wallace tells you in his answer. I propose you a different answer, enumerating the possible solutions of this problem.
You have at least 4 solutions :
instead of storing your data like you are currently doing it, use the transponate of your matrix
implement yourself an efficient sorting algorithm that takes a bi-dimensional array and the index of a column in argument
at each turn of you loop, fill an array with the current column, sort it, and copy it back (if you don't care about using some additional memory, do it). That is what you are currently trying to do
transponate your matrix, sort its lines, transponate it back (if you don't want to use too much memory, use this)
I prefer the last solution, which code is :
public static double[][] sortColumns(double[][] m) {
double[][] sortedArray = new double[m.length][m.length];
// compute the transponate of m
for (int i=0 ; i<m.length ; i++)
for (int j=0 ; j<m[i].length ; j++)
sortedArray[j][i] = m[i][j];
// sort the lines of the transponate
for (int i=0; i<sortedArray.length; i++)
Arrays.sort(sortedArray[i]);
// transponate back the result of the sorting
for (int i=0 ; i<sortedArray.length ; i++)
for (int j=i+1 ; j<sortedArray[i].length ; j++) {
double tmp = sortedArray[i][j];
sortedArray[i][j] = sortedArray[j][i];
sortedArray[j][i] = tmp;
}
return sortedArray;
}
When I look at your code I see the following line:
double[][] sortedArray = new double[m.length][m.length];
it doesn't look right to me.
you need to find length and breath of the array so i would do something like this:
length = m.length;
breath = m[0].length;
if i m not sure of all rows have same no of elements i may do that check by a for loop and initialize with the max.. wud lead to memory wastage but thats another demon to tame :)
next when we write m[x][y] x represents the rows and y represents the columns so when ur doing :
for (int j = 0; j < m.length; j++) {
temp[j] = m[j][i];
}
Arrays.sort(temp);
you are fetching all the values from a column i, assigning it to temp array and sorting the column.
hope that helps

How do you add two int arrays with different lengths?

I've been working on a Java lab that wants us to have the user enter two digits up to 50 digits long and add them together. I've successfully been able to complete everything except for when the two arrays have a different length. I've been toying around with the code for a while, but I keep coming up short. Can anyone look at the code for this and have any suggestions? Thanks!
int[] number1 = new int[input1.length()];
int[] number2 = new int[input2.length()];
int[] answer = new int[input1.length()];
if(number1.length > number2.length){
number2 = new int[number1.length];
for(int i = 0; i < number2.length - number1.length; i++){
number2[i] = 0;
}
}
if(number2.length > number1.length){
number1 = new int[number2.length];
for(int i = 0; i < number1.length - number2.length; i++){
number1[i] = 0;
}
}
Whenever I add, say 120 and 12, it says there's an Array out of bounds error.
First thing you need to do is get the numbers into an int array. Do that by Splitting string to char array. Then convert to int array. Then add.
String input1 = scanner.nextLine().trim(); <-- get input as String
String input2 = scanner.nextLine().trim();
char[] array1 = input1.toCharArray(); <-- split to char array
char[] array2 = input2.toCharArray();
// convert to int array
int[] intArray1 = new int[array1.length]; <-- declare int array
int[] intArray2 = new int[array2.length];
for (int i = 0; i < array1.length; i++){
intArray1[i] = Integer.parseInt(String.valueOf(array1[i])); <-- convert to int
}
for (int i = 0; i < array2.legnth; i++){
intArray2[i] = Integer.parseInt(String.valueOf(array2[i]));
}
// check which one is larger and add to that one
if (intArray1.length > intArray2.length){
for (int i = 0; i < intArray2.length; i++){
intArray1[i] += intArray2[i]; <-- add values
}
System.out.println(Arrays.toString(intArray1); <-- print largest
} else {
for (int i = 0; i < intArray1.length; i++){
intArray2[i] += intArray1[i];
}
System.out.println(Arrays.toString(intArray2);
}
If you want to get the number representation printed instead of an array, instead of the System.out.println(), use this
StringBuilder sb = new StringBuilder();
for (int i : intArray1){
sb.append(String.valueOf(i));
}
System.out.println(sb.toString());
So 123 and 12 will print out 233
My understanding of your code is, you try to pre-append (push from head) 0s to the shorter array. Look at the first if-block. The length of number1 is larger than what of number2. Thus, number2.length - number1.length is negtive. Then, in the for loop, i < number2.length - number1.length is always ture. (I am not familiar with java. I guess array's length is an integer.) And you still have to copy the rest of array.
The correct code should be,
if(number1.length > number2.length) {
int[] number3 = new int[number1.length];
for(int i = 0; i < number1.length - number2.length; ++i) {
number3[i] = 0;
}
for(int i = 0; i < number2.length; ++i) {
number3[i + number1.length - number2.length] = number2[i];
}
number2 = number3;
}
BTW, the second if-block should be changed in a similar way. Perhaps, java provides an API link insert(0, 0) for array object. It will be easier to implement.

Storing computations in arrays - second try

im new to Java and currently trying to learn how to best store numbers in arrays.
the specific problem im working on is trying to find a way to better implement the below methods by storing the computations in an array.
the code looks like this:
public static long myF(int N) {
long[] computedValues;
computedValues = new long[N+1];
computedValues[0] = 0;
computedValues[1] = 1;
for (int i = 2; i < computedValues.length ;i++){
computedValues[i] = computedValues[(i-1)]+computedValues[(i-2)];
System.out.println("array["+(i)+"] = "+computedValues[i]);
}
return computedValues[N-1];
}
public static void runMyF() {
for (int N = 0; N < 100; N++)
StdOut.println(N + " " + myF(N));
}
public static void main(String[] args) {
runMyF ();
}
Main in this code is supposed to call runMyF(), and then runMyF() is supposed to call myF().
My problem is that I cant get computedValues[0] = 0; computedValues[1] = 1; included in the output and the second problem is that ie get this error message when runMyF() calls myF():
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at algs11.MyFib.myF(MyFib.java:21)
at algs11.MyFib.runMyF(MyFib.java:30)
at algs11.MyFib.main(MyFib.java:37)
Any help please?
#Dukeling, your solution was a bit over my pay grade (sorry) - I think there are some bugs in my code and I need help to find them. Thank you.
You're incrementing the wrong variable.
for (int i = 2; i < computedValues.length; N++){
should be
for (int i = 2; i < computedValues.length; i++){
Note the N++ changed to i++.
Remember to initialize computedValues[0] and computedValues[1]. This should appear before the loop:
computedValues[0] = 0;
if (N > 0) // needed because when N = 0, the below will be out of bounds
computedValues[1] = 1;
It should probably be computedValues = new long[N+1];, otherwise the array is too small.
You need to return the correct value - change return computedValues[N]; to return 0;.
Additional efficiency:
I guess the point is to compare the efficiency of the two method. If not, you should declare computedValues outside of the function as an ArrayList and, in the function, add to it as required. This will cause you to only compute each value once for the entire run of the program.
static ArrayList<Long> computedValues = new ArrayList<Long>(Arrays.asList(0l,1l));
public static long myF(int N) {
for (int i = computedValues.size(); i <= N; i++){
computedValues.add(computedValues.get(i-1) + computedValues.get(i-2));
System.out.println("array[" + i + "] = " + computedValues.get(i));
}
return computedValues.get(N);
}
You forgot the initial numbers in the array:
long[] computedValues;
computedValues = new long[N];
computedValues[0] = 0;
computedValues[1] = 1;
You are initializing computedValues to a new long
computedValues = new long[N];
I think you wanted to do this :
computedValues[i] = F(N);
Also, in your loop you are not incementing i which makes it as infinite loop. Change it to
for (int i = 2; i < computedValues.length ;i++)
You can use a method that returns an arraylist:
ArrayList<Long>series=new ArrayList<Long>();
for(int i=0;i<100;i++)
{
if(i==0)series.add(new Long(0));
if(i==1)series.add(new Long(1));
if(i>1)series.add(new Long(series.get(i-1).longValue()+series.get(i-2).longValue()));
}
the list will have 0,1,1,2,3,5,8,....

Java integer array, I cant do simple maths it seems

I have the code below:
int lines = 0;
while(lines < 2)
{
int[] oldarr = parr;
for(int i = 0; i < arrsize; i++)
System.out.print(" " + oldarr[i]);
System.out.println();
for(int i = 0; i < arrsize; i++)
{
if(i == 0)
parr[i] = 0;
else
parr[i] = Math.abs(oldarr[i] - oldarr[i-1]);
}
lines++;
}
parr is an array of integers of size [arrsize]. Each time through this loop I want to print the value of each index in parr, then set each index to the difference between the index before it and itself. Currently it gives me the correct (hardcoded) originally parr. But the next(first) iteration of changing parr gives me unexpected values; they are not even close to the difference between the two neighboring values..
Any ideas?
You aren't copying your array with this line:
int[] oldarr = parr;
The two variables are still pointing at the same array.
To get a copy, you can do:
int[] oldarr = Arrays.copyOf(parr, parr.length);
In your second for loop, you are setting the new value to the difference of the current value and the previous value, but the previous value was already changed in the previous iteration of the for loop.
Change your second for loop iteration to iterate through the array backwards, so your calculations don't depend on previous calculations.
for(int i = arrsize - 1; i >= 0; i--)

Categories