Answer:
// Given int n, return an int[] that contains the numbers 0, 1, .. n-1, n, n-1, ... 1, 0.
// For example, if n = 5, then the array should be 0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0.
function mirrorArray(max) {
const firstHalf = []; // initalize the first half (without max)
let count = 0; // we're gonna count up from 0 to the max
while (count < max) { // whilst the count is less than the max provided
firstHalf.push(count); // add the value of count to the array firstHalf
count++; // increment count by 1
}
const secondHalf = firstHalf.slice().reverse();
// we first chane the .slice() method which has no arguments
// this means we can copy our array before reversing it.
// if we did firstHalf.reverse(), we'd end up changing what's inside firstHalf too.
// we don't want that!
return [...firstHalf, max, ...secondHalf];
// ... is the spread operator
// it is used to remove the square brackets [] from an array
// for example: ...[1, 2, 3] becomes 1, 2, 3
}
console.log(mirrorArray(5)); // here we're calling our function, and providing a max of 5
Step-by-step explanation:
Everything that needs explaining should be in the comments I've put in the code! If you need more help, please ask!
I decided to use JavaScript because I think it reduces the amount of extra code needed to get my intentions across to the computer.
P.S.: I've also attached a screenshot of my IDE because it can be hard to read code if it's not colored in!
Don't worry about the array's items being displayed above each other, it is just what my IDE does.