Ralph Henry
Ralph Henry

Reputation: 124

How can I pick out the odd numbers and even numbers from a given array and then store them in another array?

How can I pick out the odd numbers and even numbers from a given array and then store them in another array? The flow is: the odd numbers will go to the odd[] array while the even numbers will go to the even[] array??

Here's my code, I'm not sure if this is correct since it somewhat stores and prints a mix of zeros and even numbers, no presence of odd numbers.....

int[] num = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};

int[] odd = new int[10];
int[] even = new int[10];

for (int i = 0; i < num.length; i++) {  // For odd numbers
    if (num[i] % 2 != 0) {
        num[i] = odd[i];
    }
    System.out.println(num[i] + " ");
}

for (int j = 0; j < num.length; j++) {  // For even numbers
    if (num[j] % 2 == 0) {
        num[j] = even[j];
    }
    System.out.println(num[j] + " ");
}

Upvotes: 3

Views: 1904

Answers (4)

Mike B
Mike B

Reputation: 2776

You can do all that in one loop - that would be way faster. To know the correct position to put the number in, add extra counter for each array.

Your kind of approach

int[] num = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
int[] odd = new int[10];
int[] even = new int[10];
int oddPos = 0;
int evenPos = 0;
for (int i = 0; i < num.length; i++) {
    if (num[i] % 2 == 0) {
        even[evenPos] = num[i];
        evenPos++;
    } else {
        odd[oddPos] = num[i];
        oddPos++;
    }
}

However this would not be the best solution as you (in most cases) cannot determine the length of odd and even arrays beforehand. Then you should use either arraylists or count the values of each or something else.

More dynamic approach

As stated before - you need to determine the size of the arrays at first

int[] num = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
int oddCount = 0, evenCount = 0;
int oddPos = 0, evenPos = 0;
//get the count of each type
for (int i = 0; i < num.length; i++) {
    if (num[i] % 2 == 0)
        oddCount++;
    else
        evenCount++;
}
//define arrays in correct sizes
int[] odd = new int[oddCount];
int[] even = new int[evenCount];
//put values in arrays
for (int i = 0; i < num.length; i++) {
    if (num[i] % 2 == 0) {
        even[evenPos] = num[i];
        evenPos++;
    } else {
        odd[oddPos] = num[i];
        oddPos++;
    }
}

Upvotes: 2

Arya Parvizi
Arya Parvizi

Reputation: 27

the approach for detecting odd and even numbers is correct, But I think the problem with the code you wrote is that the length of odd and even arrays, isn't determinant. so for this matter, I suggest using ArrayList<Integer>, let's say you get the array in a function input, and want arrays in the output (I'll mix the arrays in the output for better performance. but separating the functions for each list extracting is also ok depending on what you're going to do with them).

Solution

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test {
    public static Integer[][] separateOddnEven(int[] input) {
        Integer[][] output = new Integer[2][];
        List<Integer> odds = new ArrayList<>();
        List<Integer> evens = new ArrayList<>();
        for (int i = 0; i < input.length; ++i) {
            int temp = input[i];
            if (temp % 2 == 0)
                evens.add(temp);
            else
                odds.add(temp);
        }
        // alternative is to use these Arraylists directly
        output[0] = new Integer[odds.size()];
        output[1] = new Integer[evens.size()];
        output[0] = odds.toArray(output[0]);
        output[1] = evens.toArray(output[1]);
        return output; // index 0 has odd numbers and index 1 has even numbers.
    }

    public static void main(String[] args) {
        int[] input = {0, 21, 24, 22, 14, 15, 16, 18};
        Integer[][] output = separateOddnEven(input);
        System.out.println("odd numbers :");
        System.out.println(Arrays.toString(output[0]));
        System.out.println("even numbers :");
        System.out.println(Arrays.toString(output[1]));
    }
}

output :

odd numbers :
[21, 15]
even numbers :
[0, 24, 22, 14, 16, 18]

Upvotes: 2

Kaplan
Kaplan

Reputation: 3718

in lambda (3 lines)

int[] nums = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};

separate even and odd nums with partitioningBy:

Map<Boolean, List<Integer>> map = IntStream.of(nums)
        .boxed().collect(partitioningBy(n -> (n & 1) == 0));

…and transform the resulting List<Integer> for even and odd to int[]:

int[] even = map.get(true).stream().mapToInt(i -> i).toArray();
int[] odd = map.get(false).stream().mapToInt(i -> i).toArray();

System.out.println("even numbers: " + Arrays.toString(even));
System.out.println("odd numbers:  " + Arrays.toString(odd));
even numbers: [2, 4, 6, 8, 10, 12, 14, 16]
odd numbers:  [1, 3, 5, 7, 9, 11, 13, 15]

Upvotes: 1

user14940971
user14940971

Reputation:

You can collect a 2d array with two rows: even and odd as follows:

int[] num = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
// a 2d array of two rows: even and odd
int[][] arr = new int[2][];
// process a 1d array and fill a 2d array
Arrays.stream(num).boxed()
        // Map<Integer,List<Integer>>
        .collect(Collectors.toMap(
                // key: 0 - even, 1 - odd
                n -> n % 2,
                // value - a list of one
                // element, i.e. number
                n -> new ArrayList<>(List.of(n)),
                // merge duplicates
                (list1, list2) -> {
                    list1.addAll(list2);
                    return list1;
                }))
        // fill the rows of a 2d array: even and odd
        .forEach((key, value) -> arr[key] = value.stream()
                .mapToInt(Integer::intValue).toArray());
// output
System.out.println("Even: " + Arrays.toString(arr[0]));
// Even: [2, 4, 6, 8, 10, 12, 14, 16]
System.out.println("Odd: " + Arrays.toString(arr[1]));
// Odd: [1, 3, 5, 7, 9, 11, 13, 15]

Upvotes: 1

Related Questions