Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Advent of Code 2020 Day 15 Parts 1 and 2 solution by Mike LeSauvage
- using System.Collections;
- using UnityEngine;
- using System.Linq;
- public class MemoryGame : MonoBehaviour
- {
- //Store the spoken numbers in a hashtable.
- //Format:
- // - Each entry in the hash is a 2-element array storing the last two numbers that were spoken.
- // - When the number hasn't been spoken, there is no entry for that number in the hashtable.
- // - When first spoken, the array is initialized to [-1, turn spoken].
- // - When spoken again, older turns are pushed to the left.
- Hashtable spokenNumbers = new Hashtable();
- int numTurns = 30000000;
- int[] puzzleInputSeedNumbers = { 0, 5, 4, 1, 10, 14, 7 };
- int[] testSeedNumbers = { 0, 3, 6 };
- //Start is part of Unity; put code where it makes sense for you!
- void Start()
- {
- int[] seedNumbers = puzzleInputSeedNumbers;
- int turn = 1;
- //Speak the seed numbers.
- //NOTE: This approach assumes seed numbers are not duplicated! (Might work but not considered/tested)
- for(; turn<=seedNumbers.Length; turn++)
- {
- SpeakNumber(seedNumbers[turn - 1], turn);
- }
- int prevSpoken = seedNumbers.Last();
- //Iterate through to the final number.
- for (; turn <= numTurns; turn++)
- {
- int speak = GetTurnSinceLastSpoken(prevSpoken, turn);
- SpeakNumber(speak, turn);
- prevSpoken = speak;
- }
- Debug.Log($"Last spoken on turn {turn-1} was {prevSpoken}");
- }
- int GetTurnSinceLastSpoken(int num, int currentTurn)
- {
- int[] turnsSpoken = (int[])spokenNumbers[num]; //Get the 2D array from the hash. Entry is expected to exist!
- //Only one in the list! Was first spoken last turn
- if (turnsSpoken[0] == -1)
- {
- return 0;
- }
- //Two in the list. [1] has the entry from last turn... look at [0] for the previous entry.
- int lastTurnSpoken = turnsSpoken[0];
- return currentTurn-1 - lastTurnSpoken; //Extra -1 as we're considering the prevous turn as the starting point.
- }
- //If the number hasn't been spoken before, creates a hash entry for it as
- //a 2D array and seeds it with [-1, currentTurn].
- //It it has been spoken before, moves the recent entry to [0] and adds
- //currentTurn to [1] so the most recent turn the number was spoken is at [1].
- void SpeakNumber(int num, int currentTurn)
- {
- int[] turnsSpoken = (int[])spokenNumbers[num];
- if (turnsSpoken == null)
- {
- turnsSpoken = new int[2] { -1, currentTurn };
- spokenNumbers[num] = turnsSpoken;
- }
- else
- {
- turnsSpoken[0] = turnsSpoken[1];
- turnsSpoken[1] = currentTurn;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement