How to create an array from a pre-existing array?

wetmoney :

New to java and am trying to create a program/method that will take an int array, and return another int array but it replaces the values of the indexes with the value of the elements. (Example {2,1,3} will return {0,0,1,2,2,2}

public static void main(String[] args) {

    int[] pracArray = {2, 1, 3};

    int sum = 0;

    for (int i = 0; i < pracArray.length; i++)
    {
        sum = sum + pracArray[i];
    }

    System.out.println("Amount of array indexes: " + sum);

    int[] newArray = new int[sum];

    System.out.println(Arrays.toString(pracArray));

    for (int i = 0; i < pracArray.length; i++)
    {

        for (int j = 0; j < pracArray[i]; j++)
        {
            newArray[j] = i;
        }
    }
    System.out.println(Arrays.toString(newArray));
}

}

Currently I am getting [2,2,2,0,0,0]. I have tried changing the how many times each for loop iterates with no avail. I have also tried to make the elements of newArray equal to a counter ( int count = 0; and having count++ in the for loop) since the values of the new array will always be 0 - however many runs.

Surronie :

Given the length of your array is 3, your outer 'i' loop is iterating through the values 0,1,2. That means your inner 'j' loop never writes to index 3,4,5 (hence why they are 0 in the output), and why the first 3 indexes are set to '2' (2 is the last indexed processed in the 'i' loop). Try this instead...

int h = 0;

for (int i = 0; i < pracArray.length; i++)
{
    for (int j = 0; j < pracArray[i]; j++)
    {
        newArray[h] = i;

        h++;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31822&siteId=1