Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 25s
Walks list with List.iteri, checking if target - x is already in the hashtable; if yes, the earlier index plus current is the answer; otherwise record the current pair. twosum [2;7;11;15] 9 = (0, 1) 2+7 twosum [3;2;4] 6 = (1, 2) 2+4 twosum [3;3] 6 = (0, 1) 3+3 Sum of i+j over each pair: 1 + 3 + 1 = 5. Tests Hashtbl.find_opt + add (the iter-99 cleanup), List.iteri, and tuple destructuring on let-binding (iter 98 'let (i, j) = twosum ... in'). 63 baseline programs total.
18 lines
400 B
OCaml
18 lines
400 B
OCaml
let twosum xs target =
|
|
let h = Hashtbl.create 8 in
|
|
let result = ref (-1, -1) in
|
|
List.iteri (fun i x ->
|
|
let need = target - x in
|
|
match Hashtbl.find_opt h need with
|
|
| Some j -> result := (j, i)
|
|
| None -> Hashtbl.add h x i
|
|
) xs;
|
|
!result
|
|
|
|
;;
|
|
|
|
let (i1, j1) = twosum [2;7;11;15] 9 in
|
|
let (i2, j2) = twosum [3;2;4] 6 in
|
|
let (i3, j3) = twosum [3;3] 6 in
|
|
i1 + j1 + i2 + j2 + i3 + j3
|