Skip to content

Instantly share code, notes, and snippets.

@deapsquatter
Created May 10, 2015 18:27
Show Gist options
  • Save deapsquatter/b53f7a3e5d36ceeac848 to your computer and use it in GitHub Desktop.
Save deapsquatter/b53f7a3e5d36ceeac848 to your computer and use it in GitHub Desktop.
Write a program that outputs all possibilities to put + or - or nothing between the numbers 1, 2, ..., 9 (in this order) such that the result is always 100. For example: 1 + 2 + 34 – 5 + 67 – 8 + 9 = 100.
#time "on"
let findSeq =
let rec find n s =
match s |> List.map(fun t -> (abs t).ToString().ToCharArray()) |> Array.concat |> Array.length with
|9 -> [s |> List.rev]
|x -> let ones =
match x with
|x when x > 1 -> find (n + 1) (n::s) @ find (n + 1) (-n::s)
|_ -> find (n + 1) (n::s)
let twos =
match x with
|x when x < 8 -> let two = n * 10 + (n + 1)
find (n + 2) (two::s) @ find (n + 2) (-two::s)
|_ -> []
let threes =
match x with
|x when x < 7 -> let three = (n * 10 + (n + 1)) * 10 + (n + 2)
find (n + 3) (three::s) @ find (n + 3) (-three::s)
|_ -> []
ones @ twos @ threes
find 1 []
|> List.filter(fun t -> t |> List.sum = 100)
@deapsquatter
Copy link
Author

Real: 00:00:00.026, CPU: 00:00:00.026, GC gen0: 1, gen1: 0
val findSeq : int list list =
[[1; 2; 3; -4; 5; 6; 78; 9]; [1; 2; 34; -5; 67; -8; 9];
[1; 23; -4; 5; 6; 78; -9]; [1; 23; -4; 56; 7; 8; 9];
[12; 3; 4; 5; -6; -7; 89]; [12; 3; -4; 5; 67; 8; 9];
[12; -3; -4; 5; -6; 7; 89]; [123; 4; -5; 67; -89];
[123; -4; -5; -6; -7; 8; -9]; [123; 45; -67; 8; -9]; [123; -45; -67; 89]]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment