Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void Main()
- {
- ///TEST CODE
- if(PlayGame(09, 0025) != 000032) throw new Exception("Failed Game");
- if(PlayGame(10, 1618) != 008317) throw new Exception("Failed Game");
- if(PlayGame(13, 7999) != 146373) throw new Exception("Failed Game");
- if(PlayGame(17, 1104) != 002764) throw new Exception("Failed Game");
- if(PlayGame(21, 6111) != 054718) throw new Exception("Failed Game");
- if(PlayGame(30, 5807) != 037305) throw new Exception("Failed Game");
- //GET DATA
- var aoc = new AdventOfCode(2018, 9);
- //PARSE IT
- var i = Parse(aoc.InputLines[0]);
- //Submit
- aoc.SubmitAnswer(PlayGame(i.playerCount, i.lastMarble), Part.A);
- aoc.SubmitAnswer(PlayGame(i.playerCount, i.lastMarble * 100), Part.B);
- }
- //Parse
- (int playerCount, int lastMarble) Parse(string line)
- {
- var splt = line.Split(' ');
- return(int.Parse(splt[0]), int.Parse(splt[6]));
- }
- long PlayGame(int playerCount, int lastMarble)
- {
- //the players and their score
- var players = new long[playerCount];
- int playerPosition = 0;
- //circle with the marbles, small extension added to circular usage
- var circle = new LinkedList<int>();
- //the currentMarble
- int currentMarble = 0;
- //add the first
- circle.AddFirst(currentMarble++);
- //the position we are working from
- var position = circle.First;
- //loop till last marble
- while (currentMarble <= lastMarble)
- {
- //move the playerposition by 1
- playerPosition++;
- //special moment?
- if (currentMarble % 23 == 0)
- {
- //add the score
- players[playerPosition % playerCount] += currentMarble++;
- //move 7 times (bit ugly but save a for loop SPPEEED!
- position = position.GetPrevious().GetPrevious().GetPrevious().GetPrevious().GetPrevious().GetPrevious().GetPrevious();
- //add the new current marble to the score
- players[playerPosition % playerCount] += position.Value;
- //this needs to be removed
- var toRemove = position;
- //get the new position
- position = position.GetNext();
- //and remove
- circle.Remove(toRemove);
- }
- else
- {
- //move
- position = position.GetNext();
- //add marble
- position = circle.AddAfter(position, currentMarble++);
- }
- }
- //return score
- return players.Max();
- }
- //extension, for easy circular list usage.
- public static class test
- {
- public static LinkedListNode<int> GetNext(this LinkedListNode<int> item)
- {
- if(item.List.Last == item) return item.List.First;
- else return item.Next;
- }
- public static LinkedListNode<int> GetPrevious(this LinkedListNode<int> item)
- {
- if (item.List.First == item) return item.List.Last;
- else return item.Previous;
- }
- }
- // Define other methods and classes here
Advertisement
Add Comment
Please, Sign In to add comment