Reversed sequence in Java

0 min read 168 words

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;
    
  }

}

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();
  }

}

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();
  }

}

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));
      }
    }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags