4 people like it.

Coding Kata: Score a Bowling Game

Score a Bowling game. The game is represented as a list of integers. A game of bowling consists of ten frames. In each frame, the bowler will have two chances to knock down as many pins as possible with his bowling ball. If a bowler is able to knock down all ten pins with the first ball, he is awarded a strike. If the bowler is able to knock down all 10 pins with the two balls of a frame, it is known as a spare. Bonus points are awarded for both of these, depending on what is scored in the next 2 balls (for a strike) or 1 ball (for a spare). If the bowler knocks down all 10 pins in the tenth frame, the bowler is allowed to throw 3 balls for that frame. This allows for a potential of 12 strikes in a single game, and a maximum score of 300 points, a perfect game.

Coding Kata: Score a Bowling Game

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
/// Bowling rules: http://en.wikipedia.org/wiki/Ten-pin_bowling

let score game =
    let rec loop acc turn xs =
        match turn, xs with
            | 0,  _ -> // game over
                acc
            | _, 10::(x::y::_ as xs) -> // Strike : 10 + pins down on the next two throws
                loop (10 + x + y + acc) (turn - 1) xs
            | _, x::y::(z::_ as xs) when x + y = 10 -> // Spare: 10 + pins down in the next throw
                loop (10 + z + acc) (turn - 1) xs
            | _, x::y::xs -> // open frame
                loop (x + y + acc) (turn - 1) xs
            | _ -> 
                failwith "Error in the score"
    loop 0 10 game

let game1 = [10; 10; 10; 10; 10; 10; 10; 10; 10; 10; 10; 10] // Score: 300
// > score game1;;
// val it : int = 300

let game2 = [9; 1; 9; 1; 9; 1; 9; 1; 9; 1; 9; 1; 9; 1; 9; 1; 9; 1; 9; 1; 9] // Score: 190
// > score game2;;
// val it : int = 190

let game3 = [10; 1; 9; 1; 2; 1; 9; 1; 9; 1; 9; 1; 9; 1; 9; 1; 9; 1; 9; 10] // Score: 120
// > score game3;;
// val it : int = 120

let game4 = [5; 2; 3; 4; 4; 2; 6; 1; 8; 0; 0; 9; 2; 7; 2; 3; 8; 1; 3; 3] // Score: 73
// > score game4;;
// val it : int = 73
val score : game:int list -> int

Full name: Script.score


 Bowling rules: http://en.wikipedia.org/wiki/Ten-pin_bowling
val game : int list
val loop : (int -> int -> int list -> int)
val acc : int
val turn : int
val xs : int list
val x : int
val y : int
val z : int
val failwith : message:string -> 'T

Full name: Microsoft.FSharp.Core.Operators.failwith
val game1 : int list

Full name: Script.game1
val game2 : int list

Full name: Script.game2
val game3 : int list

Full name: Script.game3
val game4 : int list

Full name: Script.game4
Raw view Test code New version

More information

Link:http://fssnip.net/ei
Posted:12 years ago
Author:Cesar Mendoza
Tags: kata , sports