Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to return array of values with the odd indexes

I should write algorithm which gets the array of numbers and return array of values with odd indexes
Input = {-5, 590, 234, 985, 14, 68}
Expected Result = {590, 985, 68}

I have written algorithm like this, but it does not work.

public int[] oddInd(int[] array) {
        if (array.length > 0) {
            int i1 = 0;
            for (int i = 1; i < array.length; i += 2) {

                 i1 = array[i];
            }

            return new int[]{i1};
        }
        return new int [0];
    }

When i print the algorithm the output is [1]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Help me , please. What`s wrong with my code?

>Solution :

You need to recalculate the size of the result array and populate it properly:

public int[] oddInd(int[] array) {
    int[] res = new int[array.length / 2];
    for (int i = 0; i < res.length; i++) {
        res[i] = array[2 * i + 1];
    }
    return res;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading