Created
December 20, 2017 07:50
-
-
Save milang/ebe5138d35e6076e90e046dfe1d7f64e 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
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
// Problem A | |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
type SpinlockState = { position: int; counter: int; list: int list } | |
let rec insert position value list = | |
if position = 0 then value::list | |
else | |
match list with | |
| head::tail -> head::(insert (position-1) value tail) | |
| [] -> [] | |
let spinlock spins (state: SpinlockState) = | |
let newPosition = (((state.position + spins) % state.list.Length) + 1) | |
let newList = insert newPosition state.counter state.list | |
{ position = newPosition; counter = state.counter + 1; list = newList } | |
let finalState = | |
{ 1..2017 } | |
|> Seq.fold | |
(fun s _ -> spinlock 371 s) | |
{ position = 0; counter = 1; list = [0] } | |
(List.nth finalState.list (finalState.position + 1)).Dump("After 2017") | |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
// Problem A | |
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
type SpinlockState2 = { position: int; counter: int; afterZero: int } | |
let spinlock2 spins state = | |
let newPosition = (((state.position + spins) % state.counter) + 1) | |
{ position = newPosition; counter = state.counter + 1; afterZero = (if newPosition = 1 then state.counter else state.afterZero) } | |
let finalState2 = | |
{ 1..50000000 } | |
|> Seq.fold | |
(fun s _ -> spinlock2 371 s) | |
{ position = 0; counter = 1; afterZero = 0 } | |
(finalState2.afterZero).Dump("After zero") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment