I am a newbie in programming and new to this site and I have a question about nested for loops. This is the code:
function eddardStarkSecret() {
var ans =[];
var map = [
[111, 1, 6], [110, 2, 5, 22], [115, 10], [83, 4], [119, 7],
[105, 9], [97, 12, 15, 18], [84, 14], [114, 16, 19],
[103, 17], [121, 20], [101, 21], [32, 3, 8, 11, 13], [74,0]
];
for (var i = 0; i < map.length; i++) {
for (var j = 1; j < map[i].length; j++)
ans[map[i][j]] = map[i][0];
}
return ans.reduce(function (prev, curr) {
return prev + String.fromCharCode(curr);
},"");
}
The ouput of the code is this: "Jon Snow is a Targaryen"
Now, my question is, how did it happened? I have a little idea on how array.reduce() part works. The part where i am really confused at is how the nested for loop worked(like how did it produce the 32 charcode(space bar) and how did it made the array length to 23 and produce the words needed for the desired output).
Any help would be very much be appreciated. Many, many thanks in advance.
The best way to understand what's happening is to run this code in a debugger, walking through it step by step. Your web browser has a fully-featured debugger built into it which you can use for this, or any JavaScript IDE does.
But briefly:
In the map
array's subarrays, the first entry is the character code and all subsequent entries are where that character should be used. So for instance, [111, 1, 6]
tells us character code 111 ("o"
) should be at positions 1 and 6 in the result.
The part where i am really confused at is how the nested for loop worked(like how did it produce the 32 charcode(space bar)
The 32 is the first value in the second-to-last entry in the map
array, which is [32, 3, 8, 11, 13]
, and so it's put at positions 3, 8, 11, and 13.
and how did it made the array length to 23 and produce the words needed for the desired output).
By looping through the subarrays, skipping the first entry (by starting j
at 1 instead of ), and using all the others as indexes into ans
, where it stores the value of the first entry (the character code) in ans
:
// The char code vvvvvvvvv
ans[map[i][j]] = map[i][0];
// ^^^^^^^^^--- where to put it
Then at the end it just loops through ans
using String.fromCharCode
to convert each entry to its character and append it to the accumulator used with reduce
.