Row Bot explainer

The aim of this puzzle: Check if the row string has three Os in a row.

Walkthrough of the solution: The row is a string with 10 random letters, each one is either 'X' or 'O'. The row represents a row of seats, and each one is either taken ('X') or open ('O').

To see if there are 3 open seats next to eachother, the row string would need to contain 'OOO' somewhere in it. The .includes() method searches the string and returns either true or false.

In the 2nd If Statement, the test is row.includes('X'). That would check if there is any seat that is taken. The 'X' should be changed into 'OOO' to check if there are 3 seats side by side.

Sample code solution:
(Tap below to reveal)

if (row.includes('O')) {
  console.log('There is an open seat.');

if (row.includes('OOO')) {
  console.log('There are 3 seats together.');

JavaScript Concepts: console.log(), If Statements, .includes()
Additional Code (hidden code that runs before the puzzle’s code):

let row = [...Array(10)].map(i=>pickRandom(['X','O'])).join('');

Where are .map and .join used for in the hidden code?

does this help?

1 Like

Thanks, I should use Google more often :wink:

actually, i got the mozilla link from grasshopperben from another explainer

Great question. It’s a super confusing line of code, and should be rewritten to be more readable by humans.

That said, Array(10) is using the Array constructor. This basically tells the computer to make some space in the computer’s memory for an array with 10 items. However, all of those items are undefined. Think of it as a house with 10 empty rooms.

Making an array this way leads to some slightly wonky behavior, and the reasons for this are a little beyond my knowledge. In any case, calling .map() directly on the empty array like this: Array(10).map() won’t work, even though you’d think it would.

The author of this code got around this problem by using the spread operator to copy the array into a new one, like this: [...Array(10)].

It’s weird, I know.

Now we have an array with 10 items that looks like this: [undefined, undefined, undefined]. is used to iterate over an array, run a function on each item, and then return a new array.

This function: .map(i => pickRandom(['X', 'O'])) means that for every item in the empty array, pickRandom() will randomly choose an X or an O and return it to the new array. This means our array now looks something like this:

['O', 'O', 'O', 'X', 'O', 'X', 'X', 'X', 'X', 'O']

Array.join() is then used to covert the array into a string, by joining all of the elements in the array.

This means that finally, after all that code runs, we have a string like 'OOOXOXXXXO'.

Here’s a summary of the steps:

  1. Array with 10 undefined items is created
  2. Each undefined item is replaced with 'O' or 'X'. These are stored in a new array.
  3. The new array is then joined into a single string that looks like 'XXOOOX'

Hope this helps!