The challenge
You must guess a sequence and it has something to do with the number given.
Example
x = 16
result = [1, 10, 11, 12, 13, 14, 15, 16, 2, 3, 4, 5, 6, 7, 8, 9]
The solution in Java code
Option 1:
import java.util.stream.IntStream;
class Challenge {
static int[] sequence(int x) {
return IntStream.rangeClosed(1, x)
.mapToObj(String::valueOf)
.sorted()
.mapToInt(Integer::parseInt)
.toArray();
}
}
Option 2:
import java.util.*;
class Challenge {
static int[] sequence(int x) {
String arr[] = new String[x];
for(int i =1;i<=x;i++){
arr[i-1]= ""+i;
}
Arrays.sort(arr);
int[] tor = new int[x];
for(int i = 0;i<x;i++){
tor[i] = Integer.parseInt(arr[i]);
}
return tor ;
}
}
Option 3:
class Challenge {
public static int[] sequence(int x) {
final var result = new int[x];
int index = 0;
for (int i = 1; i <= 9; i++) {
result[index++] = i;
for (int j = i * 10; j <= x && j < (i + 1) * 10; j++)
result[index++] = j;
}
return result;
}
}
Test cases to validate our solution
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
import java.util.Arrays;
public class SolutionTest {
@Test
public void test0() {
int[] result = {1, 10, 11, 12, 13, 14, 15, 16, 2, 3, 4, 5, 6, 7, 8, 9};
int x = 16;
String expected = Arrays.toString(result),
actual = Arrays.toString(Challenge.sequence(x));
assertEquals(expected, actual);
}
@Test
public void test1() {
int[] result = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int x = 9;
String expected = Arrays.toString(result),
actual = Arrays.toString(Challenge.sequence(x));
assertEquals(expected, actual);
}
}