Both the computer and the user have a row of units, each unit has a value. The rows are aligned face to face (like in a 2xn chess table). Each unit fights the unit in front of it. The unit with the biggest value wins. If 2 units have the same value, the computer wins. If the user knows how the computer will position its units in the row, how can the user position his units in order to minimize his loses. Write a program which computes this win/loss score. (some test data is provided).
And here is my sample:
1 let rec without_max ascending_sorted_list =
2 match ascending_sorted_list with
3 | [] -> []
4 | x::[] -> []
5 | x::y::xs -> x::without_max(y::xs)
6
7 let rec acc (me:list<int>, computer:list<int>, saved:int) =
8 match me, computer with
9 | x::xs, y::ys -> if x <= y then acc(xs, without_max(computer), saved)
10 else acc(xs, ys, saved+x)
11 | [], [] -> saved
12 | _ -> failwith "unequal arrays"
13
14 let save_creatures (me:list<int>) (computer:list<int>) =
15 let ascending_sort = List.sort(fun (x:int) (y:int) -> x.CompareTo y) in
16 acc(ascending_sort(me), ascending_sort(computer), 0)
17
18 let _ =
19 let a = save_creatures [5;15;100;1;5] [5;15;100;1;5] in
20 let b = save_creatures [15;15;15;15;15] [15;15;15;15;15] in
21 let c = save_creatures [1;3;5;7;9;11;13;15;17;19] [2;4;6;8;10;12;14;16;18;20] in
22 let d = save_creatures [2;3;4;5;6;7;8;9;10;11] [10;9;8;7;6;5;4;3;2;1] in
23 print_int a; print_int b; print_int c; print_int d
I had fun ;)
No comments:
Post a Comment