Last active
June 21, 2016 02:32
-
-
Save jdh30/05c6cb6adc4861dc6db133163bb9a6fa to your computer and use it in GitHub Desktop.
Neighbors benchmark in F# using the simple hash function from a Rust version
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
open System.Collections.Generic | |
type [<Struct>] P = | |
val i : int | |
val j : int | |
new(i, j) = {i=i; j=j} | |
let cmp = | |
{ new System.Collections.Generic.IEqualityComparer<P> with | |
member __.Equals(this, that) = | |
this.i = that.i && this.j = that.j | |
member __.GetHashCode this = (this.i <<< 10) + this.j } | |
let inline iterNeighbors f (p: P) = | |
let i, j = p.i, p.j | |
f(P(i-1, j)) | |
f(P(i+1, j)) | |
f(P(i, j-1)) | |
f(P(i, j+1)) | |
let rec nthLoop n (s1: HashSet<_>) (s2: HashSet<_>) = | |
match n with | |
| 0 -> s1 | |
| n -> | |
let s0 = HashSet(cmp) | |
let add p = | |
if not(s1.Contains p || s2.Contains p) then | |
ignore(s0.Add p) | |
Seq.iter (fun p -> iterNeighbors add p) s1 | |
s2.Clear() | |
nthLoop (n-1) s0 s1 | |
let nth n p = | |
nthLoop n (HashSet([p], cmp)) (HashSet(cmp)) | |
do | |
let timer = System.Diagnostics.Stopwatch.StartNew() | |
let _ = (nth 6000 (P(0, 0))).Count | |
printfn "%fs" timer.Elapsed.TotalSeconds | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment