[Programmers / JAVA] Level 1 N Numbers Spaced by x (12954)
[Programmers / JAVA] Level 1 N Numbers Spaced by x (12954)
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
The function solution receives an integer x and a natural number n, and must return a list containing n numbers starting from x and increasing by x each time. Look at the following constraints and complete the function solution that satisfies the conditions.
- x is an integer between -10000000 and 10000000, inclusive.
- n is a natural number no greater than 1000.
| x | n | answer |
|---|---|---|
| 2 | 5 | { 2, 4, 6, 8, 10 } |
| 4 | 3 | { 4, 8, 12 } |
| -4 | 2 | { -4, -8 } |
We need to list n numbers spaced apart by x and return them as an array. This works fine otherwise, but the case of negative numbers is a problem.
For negative numbers, they must be sorted in descending order.
After storing the elements in an ArrayList, sort them in ascending order based on the absolute value of each number. Convert the ArrayList into a stream and use the sorted() method, overriding the sort algorithm. This can be done by overriding it with (o1, o2) -> (int) (Math.abs(o1) - Math.abs(o2)). The Math.abs() method can be used to extract the absolute value of each number.
JAVA
import java.util.ArrayList; /** * N Numbers Spaced by x class * * @author RWB * @since 2021.12.13 Mon 22:21:01 */ class Solution { /** * Method that returns the answer * * @param x: [int] interval * @param n: [int] count * * @return [long[]] answer */ public long[] solution(int x, int n) { ArrayList<Long> list = new ArrayList<>(); while (n != 0) { list.add((long) x * n); n--; } return list.stream().sorted((o1, o2) -> (int) (Math.abs(o1) - Math.abs(o2))).mapToLong(Long::longValue).toArray(); } }
