Reversed sequence in Java

The challenge

Build a function that returns an array of integers from n to 1 where n>0.

Example : n=5 –> [5,4,3,2,1]

The solution in Java code

Option 1:

public class Sequence{ public static int[] reverse(int n) { if (n<=0) return null; int[] out = new int[n]; for (int i=n, j=0; i>0; i--) { out[j] = i; j++; } return out; } }
Code language: Java (java)

Option 2:

import java.util.stream.IntStream; public class Sequence{ public static int[] reverse(int n) { return IntStream.range(-n, 0).map(Math::abs).toArray(); } }
Code language: Java (java)

Option 3:

import java.util.stream.IntStream; public class Sequence{ public static int[] reverse(int n) { return IntStream.iterate(n, i -> i - 1).limit(n).toArray(); } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import org.junit.runners.JUnit4; public class SolutionTest { private int[] reverseSolution(int n){ int[] result = new int[n]; for(int i=n;i>0;i--){ result[n-i]=i; } return result; } @Test public void simpleTest() { assertArrayEquals(new int[]{5,4,3,2,1},Sequence.reverse(5)); assertArrayEquals(new int[]{6,5,4,3,2,1},Sequence.reverse(6)); assertArrayEquals(reverseSolution(100),Sequence.reverse(100)); assertArrayEquals(reverseSolution(1000),Sequence.reverse(1000)); assertArrayEquals(reverseSolution(100000),Sequence.reverse(100000)); assertArrayEquals(reverseSolution(10000000),Sequence.reverse(10000000)); } @Test public void randomTest(){ for(int i=0;i<100;i++){ int random = 1 + (int)(Math.random() * 9999); assertArrayEquals(reverseSolution(random),Sequence.reverse(random)); } } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments