Created
December 23, 2020 08:21
-
-
Save madhadron/cafb97d35848a30baccc4ee3544eff75 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
const N = 1_000_000 | |
type ArrayRing = ref object | |
ring: array[1..N, int] | |
head: int | |
proc toHashRing(xs: openArray[int]): ArrayRing = | |
var hr: ArrayRing | |
new(hr) | |
var last = xs[0] | |
for x in xs[1..<len(xs)]: | |
hr.ring[last] = x | |
last = x | |
hr.ring[last] = xs[0] | |
hr.head = xs[0] | |
return hr | |
proc step(hr: var ArrayRing) = | |
var a = hr.ring[hr.head] | |
var b = hr.ring[a] | |
var c = hr.ring[b] | |
hr.ring[hr.head] = hr.ring[c] | |
var dst = hr.head | |
while true: | |
dst = if dst == 1: N else: dst-1 | |
if dst == a or dst == b or dst == c: | |
continue | |
var next = hr.ring[dst] | |
hr.ring[dst] = a | |
hr.ring[c] = next | |
break | |
hr.head = hr.ring[hr.head] | |
# My input: | |
# var inputs = @[9, 1, 6, 4, 3, 8, 2, 7, 5] | |
# Example input: | |
var inputs = @[3,8,9,1,2,5,4,6,7] | |
for i in 10..1_000_000: | |
inputs.add(i) | |
var cups: ArrayRing = inputs.toHashRing | |
for i in 1..10_000_000: | |
if i mod 1000 == 0: | |
echo i div 1000, "/10,000" | |
step(cups) | |
var a = cups.ring[1] | |
var b = cups.ring[a] | |
echo a | |
echo b | |
echo a*b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment