Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add odd numbers between a closed range to an array

I am doing code challenge where given two integers l and r, I have to print all the odd numbers between i and r (i and r inclusive). The function must return an array of integers denoting the odd numbers between l and r.

This is what I have so far

static int[] oddNumbers(int l, int r) {
    int[] theArray = new int[r];
    for (int i = l; i < theArray.length; i++) {
        if (i % 2 != 0) {
            for (int n = 0; n < theArray.length; n++) {
                theArray[n] = i;
            }
        }
    }
    return theArray;

}

So at the moment this code if you give it values 2 and 5 should return 3,5. However, this only returns 33333. What am I doing wrong? And how can I improve this code?

like image 339
user6248190 Avatar asked Jan 27 '23 19:01

user6248190


1 Answers

We are in 2018 and do already have the amazing Streams since Java 8! With that you can solve such things in a single line! So it's worth it to take a look at it:

static int[] oddNumbers(int i, int j){
        return IntStream.rangeClosed(i, j).filter(num -> num % 2 == 1).toArray();
    }

(unless you really want to learn algorithms and not just solve the challenge!)

like image 107
roxch Avatar answered Jan 31 '23 08:01

roxch