Skip to content

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<=) return null; int[] out = new int[n]; for (int i=n, j=; i>; i--) { out[j] = i; j++; } return out; } }
Code language: Java (java)

Option 2:

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

Option 3:

import; 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>;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=;i<100;i++){ int random = 1 + (int)(Math.random() * 9999); assertArrayEquals(reverseSolution(random),Sequence.reverse(random)); } } }
Code language: Java (java)

See also  Count the divisors of a number in Java
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x