Last active
June 21, 2017 19:25
-
-
Save visibletrap/721ca61fe8573deace874c032898a429 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns codebattle101 | |
(:require [clojure.math.combinatorics :as math])) | |
(defn find-better [target best [a b] input-list] | |
(let [ab (* a b)] | |
(loop [[current-min-diff :as current-best] best | |
l 0 | |
r (count input-list)] | |
(let [pos (quot (+ l r) 2) | |
c (get input-list pos) | |
abc (* ab c) | |
signed-diff (- target abc) | |
min-diff-candidate (Math/abs ^long signed-diff) | |
new-result | |
(if (< min-diff-candidate current-min-diff) | |
[min-diff-candidate abc] | |
current-best)] | |
(cond | |
(or (= c a) (= c b)) (find-better target best [a b] (into [] (remove #{a b} input-list))) | |
(= (- r l) 1) new-result | |
(pos? signed-diff) (recur new-result pos r) | |
:else (recur new-result l pos)))))) | |
(defn solve [fname target] | |
(let [input-numbers (->> fname | |
clojure.java.io/reader | |
line-seq | |
(map #(Long/parseLong %)) | |
sort | |
(into [])) | |
pairs (math/combinations input-numbers 2)] | |
(second | |
(reduce (fn [best pair] | |
(find-better target best pair input-numbers)) | |
[Long/MAX_VALUE -1] | |
pairs)))) | |
(comment | |
(time (solve "testcase_data_small.txt" 37375606804152)) ; ans: 37375989634830 | |
(time (solve "testcase_data_large.txt" 45431751451366)) ; ans: 45431751450537 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment