Spoiler - My Interesting Approach

My code isn’t nearly as simple as Ben’s, or as short and great. However, I was able to write it and make all the tests pass in about 40 minutes, while it apparently took him 2 days to get all the tests passing. I have been programming about 4 years, so I expected to get this challenge done in at least an hour at the very least, so 40 minutes surprised me.

public static List ScoreFrames(List rolls) {
//List of frames
List frames = new List();
//List of frames that are waiting for a score. Called Skip Frames because… idk
List skipFrames = new List();

//Variable used to make sure frame detection is not affected by strikes
int skips = 1;

for(int i = 0; i < rolls.Count; i++) {
if (rolls[i] == 10) {
//Increment skips so that when detecting if the score index is a multiple of 2 we can count strikes as a full frame
skips++;

//
skipFrames.Add(rolls[i] + (i >= rolls.Count - 1 ? 0 : rolls[i + 1]) + (i + 1 >= rolls.Count - 1 ? 0 : rolls[i + 2]));

//Checks if the frames score is already known and can be added to the list of frame scores
if (i == rolls.Count - 1 || i < rolls.Count - 2) {
frames.AddRange(skipFrames);
//Clear the frames waiting for a score so that they aren’t added twice
skipFrames.Clear();
}
} else if ((i + skips) % 2 == 0) { //Check if the score’s index is a multiple of 2. To get the correct frame, we must use the skips variable which makes strikes count as a multiple of 2
if (rolls[i - 1] + rolls[i] == 10) { //Check if spare
//Get the scores of the waiting frames
int score = 0;
foreach(int s in skipFrames) {
score += s;
}
//Clear the waiting frames scores so they won’t be accidently added again later
skipFrames.Clear();

//Add the scores of the waiting frames, this frames score and the bonus if this is not the last frame
skipFrames.Add(score + rolls[i - 1] + rolls[i] + (i >= rolls.Count - 1 ? 0 : rolls[i + 1]));

//Checks if the frames score is already known and can be added to the list of frame scores
if (i < rolls.Count - 1) {
frames.AddRange(skipFrames);
//Clear the frames waiting for a score so that they aren’t added twice
skipFrames.Clear();
}
} else {
//Add the frames waiting for a score
frames.AddRange(skipFrames);
//Clear the frames waiting for a score so that they aren’t added twice
skipFrames.Clear();
//Add the scores of this frame
frames.Add(rolls[i - 1] + rolls[i]);
}
}
}

//Cut it down to 10 frames
if(frames.Count > 10) {
frames.RemoveRange(10, frames.Count - 10);
}
return frames;
}

1 Like