Skip to content

Instantly share code, notes, and snippets.

@ashafa
Created July 21, 2009 21:38
Show Gist options
  • Save ashafa/151608 to your computer and use it in GitHub Desktop.
Save ashafa/151608 to your computer and use it in GitHub Desktop.
(ns contest
(:require [clojure.contrib.str-utils :as s])
(:import (java.math BigInteger)
(java.util.concurrent ScheduledThreadPoolExecutor)))
(def *phrase-int* (BigInteger. (com.ashafa.SHA1/hash "I would much rather hear more about your whittling project") 16))
(def *words-list* (vec (.split #"\r?\n" (slurp "words.txt"))))
(def *words-count* (count *words-list*))
(defn hamming-test
[#^String subject]
(let [to-bin (fn [#^BigInteger i] (.toString i 2))]
(count (filter (fn [c] (identical? \1 c)) (to-bin (bit-xor (BigInteger. (com.ashafa.SHA1/hash subject) 16) *phrase-int*))))))
(defn start
[]
(let [phrase-int *phrase-int*
words-list *words-list*
words-count *words-count*
cores (.. Runtime getRuntime availableProcessors)
hamming (fn [#^String subject]
(let [to-bin (fn [#^BigInteger i] (.toString i 2))]
(count (filter (fn [c] (identical? \1 c)) (to-bin (bit-xor (BigInteger. (com.ashafa.SHA1/hash subject) 16) phrase-int))))))
rand-ascii (fn [length] (apply str (take length (repeatedly #(char (+ (rand-int 95) 32))))))
rand-casing (fn [target] (apply str (map (fn [#^Character c] (if (identical? 1 (rand-int 2)) (Character/toUpperCase c) c)) target)))
upper-casing (fn [#^String word] (.toUpperCase word))
gen-subject (fn [proc]
(let [subjects (map (fn [t] (cond (identical? 0 proc) (rand-casing (words-list t))
(identical? 1 proc) (rand-casing (words-list t))
(identical? 2 proc) (words-list t)
(identical? 3 proc) (upper-casing (words-list t))
:else (rand-casing (words-list t)))) (take 12 (repeatedly (fn [] (rand-int words-count)))))
ascii-len (rand-int 6)]
(s/str-join " " (if (identical? 0 ascii-len) subjects (reverse (conj subjects (rand-ascii ascii-len)))))))
run (fn [proc]
(loop [dist 160]
(let [subject (gen-subject proc)
new-dist (hamming subject)]
(recur (if (< new-dist dist) (do (println new-dist " " subject) new-dist) dist)))))]
(println "Running using" cores "cores on" words-count "words.")
(dotimes [proc cores]
(.execute (ScheduledThreadPoolExecutor. 1) (fn [] (run proc))))))
(start)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment