All right, so this was a relatively simple code challenge, and the goal is very simple. Given that we've
got a function called whosPaying and we pass in an array of names like this one,
our function should be able to pick out a random name from this array and be able to return the output
that one of these people is going to buy lunch today.
So let's see how we might tackle this. Now in order to pick out an item from the array, we would tap
into the array and we would use a square bracket to select an item.
So if we said names[0], then that's going to pull out the item at position zero which
is the first one.
And if we did names[4], then that's going to be 0,
1, 2, 3, 4, and it's going to pull up the last item from the array.
So now we basically need a random number that is in the range of 0 to 4 if the input was this
long,
but we don't know how long the input could be,
right?
It could be an array of names as long as my arm.
So given that we don't know that information, let's first work that out.
Let's create a variable called numberOfPeople which is going to be equal to names.length.
And this is going to calculate in this array that we got passed, how many names are there,
right?
Because once we've got that information, then we can work out a random person's position,
right?
So we could say that the randomPersonPosition = math.random(), which is going to generate
a number between 0 and 1 and not including 1.
And then we can multiply it by the numberOfPeople
then we would get a range of numbers from 0 to 0.9999... recurring.
So now if we multiply it by the total number of people, so the number of items in this array.
So in this example, we would have 5.
So 0 multiplied by 5 is going to be 0, but 0.99999... multiplied by 5 is going to
become 4.99999...
So now all we have to do is use the Math.floor() to cut off everything that's at the end of the decimal
place
and then we get our range 0 to 4.
So let's go ahead and do that.
So I'm going to wrap everything inside a Math.floor(),
and now this randomPersonPosition should be a random number between 0 and the total
numberOfPeople - 1, giving us all of the indices that we need to get each item in the array.
So now all that's to do is to pick out the randomPerson.
And to do that, we tap into the list of names, use our square brackets, and pass in the randomPersonPosition.
Now that we've got our randomPerson, all that we have to do is provide this output.
So let's return this output and we're going to return the randomPerson
plus the string " is going to buy lunch today!"
Now,
remember to add the space between the randomPerson's name and the rest of the sentence.
And now we've completed the challenge and we're ready to check our solution and all going well, it
should work.
And if you run this through Repl.it or through the Chrome snippets tool, you should be able to see that each
time you run this code and you pass in a different array or the same array, it should give you a random
name from that list.