logo CodeStepByStep logo

memoryNumberGame

Write a method named memoryNumberGame that processes a file of integers and simulates a sequence based on specific rules. Your method accepts as its parameter a string representing the name of a file of instruction data, and an integer N representing a 1-based index in the sequence.

You begin by taking turns reading from a list of starting numbers (your puzzle input). Then, each turn consists of considering the most recently seen number:

  • If that was the first time the number has been seen, the next number is 0.
  • Otherwise, the number had been seen before; the next number is how many turns apart the number is from when it was previously seen.

So, after the starting numbers, each turn results in that player speaking aloud either 0 (if the last number is new) or an age (if the last number is a repeat).

For example, consider the following contents, stored in a file named numbers.txt:

0,3,6
  • Turn 1: The 1st number is a starting number, 0.
  • Turn 2: The 2nd number is a starting number, 3.
  • Turn 3: The 3rd number is a starting number, 6.
  • Turn 4: Now, consider the last number, 6. Since that was the first time the number had been seen, the 4th number is 0.
  • Turn 5: Next, again consider the last number, 0. Since it had been seen before, the next number to speak is the difference between the turn number when it was last (the previous turn, 4) and the turn number of the time it was most recently before then (turn 1). Thus, the 5th number is 4 - 1, or 3.
  • Turn 6: The last number, 3 had also been seen before, most recently on turns 5 and 2. So, the 6th number is 5 - 2, or 3.
  • Turn 7: Since 3 was just seen twice in a row, and the last two turns are 1 turn apart, the 7th number is 1.
  • Turn 8: Since 1 is new, the 8th number is 0.
  • Turn 9: 0 was last seen on turns 8 and 4, so the 9th number is the difference between them, 4.
  • Turn 10: 4 is new, so the 10th number is 0.

So the call of memoryNumberGame("game.txt", 10) would return 0.

You may assume that the file exists and is readable, that it follows the format described above, that the number of integers in the input file is less than N, and that there will be at least one line of input in the file.

(This exercise is based on the Advent of Code 2020, day 15.)

Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.