First, Last and Reversed (Sequenced Collections, Java 21)
Problem
Read an array. Print three lines: first: the first element, last: the last element, reversed: the elements in reverse order, separated by spaces.
Constraints
- 1 <= n <= 1000
Examples
Input
4 1 2 3 4
Output
first: 1 last: 4 reversed: 4 3 2 1
Solutions
Without sequenced collections, the first and last elements need index arithmetic, and a reversed view needs a copy.
/*
* Problem : Process an array.
* Input : n, then n integers.
* Output : Three lines.
* Approach: Index arithmetic and a copy.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String[] solve(int[] a) {
// Step 1: Put the numbers in a list.
java.util.List<Integer> list = new java.util.ArrayList<>();
for (int value : a) {
list.add(value);
}
// Step 2: Before Java 21 the first and last elements need index arithmetic.
int first = list.get(0);
int last = list.get(list.size() - 1);
// Step 3: To get the reversed order we must copy the list and call Collections.reverse.
java.util.List<Integer> copy = new java.util.ArrayList<>(list);
java.util.Collections.reverse(copy);
StringBuilder text = new StringBuilder();
for (int value : copy) {
text.append(text.length() == 0 ? "" : " ").append(value);
}
return new String[] {"first: " + first, "last: " + last, "reversed: " + text};
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(String.join("\n", solve(a)));
}
}
Hints (1)
- Which index is the last one?