简体   繁体   English

从右到左循环

[英]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. 现在,我需要从最后一个位置到第一个位置循环遍历数组m,并在循环时分配与元素位置一致的数组值。 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. 例如,在位置2存储值2,在位置3存储值-3。 I think the second for loop should read values from right to left..? 我认为第二个for循环应该从右到左读取值。 I am almost there but there is something wrong in a 2nd for loop in my code. 我快到了,但是我的代码在第二个for循环中出了点问题。 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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