Last active
September 23, 2018 13:11
-
-
Save harrisonmalone/317b82936e252166b1c0bb8528155c7b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# probably the most discussed challenge in the ruby fundamentals | |
# some nice logic required | |
hat_arr = [] | |
counter = 0 | |
100.times do | |
# here we create the hat array with 100 false items | |
hat_arr[counter] = true | |
counter += 1 | |
end | |
def toggle(bool) | |
# here we create a function that toggles our booleans, if the teacher hits the item the boolean will be toggled whether it's true or false | |
if bool | |
return false | |
else | |
return true | |
end | |
end | |
def hats(hat_arr) | |
# here we pass in the hat array as an argument | |
counter = 0 | |
while counter <= 100 do | |
# here we make sure the teacher will loop through the array of students 100 times | |
hat_arr.each_with_index do |bool, index| | |
# here we enter into an each loop that inludes the index for each bool (hat) item, if the index modulo by the counter returns zero we know that this is the hat array item that we need to toggle, and we use the toggle function to do this | |
# we have to ensure that our index and counter start at 1 for each each pass thus we need to add 1 to the index in the conditional | |
if (index + 1) % (counter + 1) == 0 | |
hat_arr[index] = toggle(bool) | |
end | |
# example => so the teacher will toggle every 10 students on the 10th pass, so if student index (student number in line) modulo to the counter (how many gaps between students teacher does for current pass) is equal to zero remainders (10, 20, 30, 40, 50, 60, 70, 80, 90, 100) then the bool value is toggled | |
end | |
# this is how we're incremeting the counter value for each loop in the times method | |
counter += 1 | |
end | |
# we return the mutated hat array | |
return hat_arr | |
end | |
# here we store our mutated hat array after its been through the 100 cycles | |
hats = hats(hat_arr) | |
hats.each_with_index do |hat, index| | |
# here we print the hat_arr now called hats incrementing the index by 1 | |
index + 1 | |
hat | |
end | |
# the index represents the students and the counter represents the gaps between each student | |
# by having the counter in the block the while loop doesn't have access to it when it checks the <= condition | |
# the block doesn't allow the while loop to have access to the counter variable because the block has its own scope |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment