let next_permutation list = let rec phase3 taddr = function | _ :: tl when tl == taddr -> [] | hd :: tl -> hd :: phase3 taddr tl | [] -> [] in let rec phase2 h2 taddr = function | h1 :: tl when h1 > h2 -> let lis = phase3 taddr tl in h1, h2 :: lis | h1 :: tl -> let hh, lis = phase2 h2 taddr tl in hh, h1 :: lis | _ -> failwith "??" in let rec phase1 list = function | h1 :: h2 :: tl when h1 > h2 -> let hh, lis = phase2 h2 tl list in List.rev_append tl (hh :: lis) | _ :: tl -> phase1 list tl | _ -> list in let rev_list = List.rev list in phase1 rev_list rev_list in Scanf.scanf "%d" (fun n -> let solve fu = let rec loop ([ a; b; c; d; e; f; g; h; i; j ] as z) = let fl, e1, e2, e3 = fu a b c d e f g h i j in if fl && e1 + e2 = e3 then Printf.printf "%d\n" e3 else loop (next_permutation z) in loop [ 9; 8; 7; 6; 5; 4; 3; 2; 1; 0 ] in solve [| (fun a b c d e f g _ _ _ -> a <> 0 && d <> 0 && b <> 0, 100*a + 10*b + c, 100*d + 10*e + f, 1000*b + 100*g + 10*c + b); (fun a b c d e f g h i j -> a <> 0 && d <> 0 && h <> 0, 1000*a + 100*a + 10*b + c, 1000*d + 100*e + 10*f + g, 10000*h + 1000*i + 100*b + 10*c + j); (fun s p r i n g e h t c -> s <> 0 && e <> 0 && p <> 0, 100000*s + 10000*p + 1000*r + 100*i + 10*n + g, 10000*e + 1000*i + 100*g + 10*h + t, 100000*p + 10000*i + 1000*c + 100*n + 10*i + c) |].(n - 1) )