简体   繁体   中英

For loop from right to left

import java.util.Arrays;

public class A {
    public static void main(String[] args){

        int m = Integer.parseInt(args[0]);
        int[] array = new int[m];
        for(int i = 0; i < m; i++) {
            array[i] = (int)(Math.random() * (m - 1) + 1);
        }
        System.out.println("Input array:" + Arrays.toString(array));

        int array2[] = new int[array.length];

        for(int j = array.length - 1; j != -1; j--){
            array2[j] = array[j];

            int digit = array2[j] % 10;

            if(digit == j || j % 2 == 0){
                array2[j]=array2[j];
            }
            if(digit == j || j % 2 != 0){
                array2[j] = array2[j] - 2 * array[j];
            }
        }
        System.out.println("Output array:" +Arrays.toString(array2));
    }
}

My code generates an array with random values and then copy them to the second array. Now I need to loop through array m starting from the last position till the first position and while looping assign array values that coincide with the position of the element. Also, at even positions values should be positive, while at odd positions values should be negative. For example, at position 2 value 2 is stored and at position 3 value -3 is stored. I think the second for loop should read values from right to left..? I am almost there but there is something wrong in a 2nd for loop in my code. Can anyone help me?

If you are bounded to use two arrays, then your code will look and behave a bit differently.

int [] originalArr = new int[m];
int [] newArr = new int[m];
int rand;
int index = 0;
boolean isDuplicated = false;

while(index < m-1)
{
  rand = (int)(Math.random() * (m - 1) + 1);
  //ensures uniqueness of your random numbers
  for(int i = 0; i < index; i++)
  {
     if(number == originalArr[i])
     {
        isDuplicated = true;
        break;
     }
  }
  if(!isDuplicated)
  {
    originalArr[index++] = rand;
  }
  isDuplicated = false;
}

for(Integer i : originalArr)
{
    if(i % 2 == 0)
    {
        newArr[i] = i;
    }
    else
    {
       newArr[i] = -i;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM