Problems › TypeScript › patterns
Reverse a list end to end
A replay view shows the most recent reading first, so the buffer has to come back the other way round.
- The order reverses; the values themselves are untouched.
- An empty list and a single reading both come back as they went in.
reverseReadings(readings: list<int>) → list<int>
Where you start
function reverseReadings(readings: number[]): number[] {
}
Worked examples
| Call | Result |
|---|---|
reverseReadings([1,2,3]) | [3,2,1] |
reverseReadings([1,2,3,4]) | [4,3,2,1] |
reverseReadings([7]) | [7] |
reverseReadings([]) | [] |
Hint
Put one index at each end. Swap what they point at, then step them towards each other until they meet.
Reference solution in TypeScript
function reverseReadings(readings: number[]): number[] {
const out = readings.slice();
let i = 0;
let j = out.length - 1;
while (i < j) {
const swap = out[i];
out[i] = out[j];
out[j] = swap;
i += 1;
j -= 1;
}
return out;
}