Skip to content

Instantly share code, notes, and snippets.

@mastoj
Last active August 29, 2015 14:10
Show Gist options
  • Save mastoj/7aea1ab1b17591d3f5a7 to your computer and use it in GitHub Desktop.
Save mastoj/7aea1ab1b17591d3f5a7 to your computer and use it in GitHub Desktop.
Kalender 2014
open System
let toDecStr = sprintf "%i"
let toOctStr = sprintf "%o"
let revStr (x:string) = String(x.ToCharArray() |> Array.rev)
let isPalindrom x = x = (revStr x)
let numPalCheck conv x = x |> conv |> isPalindrom
let decCheck = numPalCheck toDecStr
let octCheck = numPalCheck toOctStr
let checker x = (octCheck x) && (decCheck x)
let result = [1..1000000] |> Seq.filter checker |> Seq.length
printfn "%i" result
Console.ReadLine()
let result2 = [1..1000000] |> Seq.map (fun x -> ((sprintf "%i" x), (sprintf "%o" x))) |> Seq.filter (fun (x,y) -> let rev (z:string) = String(z.ToCharArray() |> Array.rev) in ((x = (rev x)) && (y = (rev y)))) |> Seq.length
printfn "%i" result2
Console.ReadLine()
#time
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let lastManStanding n =
let folks = Array.init (n+1) (fun i -> match i with
| 0 -> None
| x when x = n -> Some (i, 1)
| x -> Some (x, (x+1)))
let getConnectingNode node = match node with
| Some (id, next) -> folks.[next]
| None -> None
let getIdFromNode node = Option.get node |> (fun (id,_) -> id)
let giveDrinkToNext (Some (id, next)) = folks.[next] <- None
let newNext (Some (id, _)) (Some (id2, _)) = folks.[id] <- Some (id, id2)
let rec lastManStandingImpl node =
let connectingNode = getConnectingNode node
let nextConnectingNode = getConnectingNode connectingNode
match connectingNode, nextConnectingNode with
| _,None -> getIdFromNode node
| _,(Some x) -> newNext node nextConnectingNode
giveDrinkToNext connectingNode
lastManStandingImpl nextConnectingNode
lastManStandingImpl folks.[1]
let result = lastManStanding 1500
printfn "OK: %A" result
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
#time
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
type PrimeCalculator = {isPrime: int -> bool; getPrime: int -> int; getIndexOfPrime: int -> int }
let createPrimeCalculator =
let size = 10000000
let filter = Array.init size (fun _ -> false)
filter.[0] <- true
filter.[1] <- true
let primes = Array.init size (fun _ -> 0)
let primeIndex = Array.init size (fun _ -> 0)
let setFilterAtIndex i pcnt =
match filter.[i] with
| true -> pcnt
| false -> primes.[pcnt] <- i
primeIndex.[i] <- pcnt
[2 .. (size/i - 1)] |> List.map (fun j -> filter.[i*j] <- true) |> ignore
pcnt+1
let rec filterBuilder i pcnt =
match i = size with
| true -> ()
| false -> let newPcnt = setFilterAtIndex i pcnt
(filterBuilder (i+1) newPcnt)
filterBuilder 2 0
let isPrime i = not (filter.[i])
let getPrime i = primes.[i]
let getIndexOfPrime i = primeIndex.[i]
{isPrime = isPrime; getPrime = getPrime; getIndexOfPrime = getIndexOfPrime}
let calculator = (createPrimeCalculator)
let doStuff connectingNumbers serie =
let calculateSumOfPrimes startIndex count = {startIndex .. (startIndex + count - 1)}
|> Seq.map (fun i -> (calculator.getPrime i))
|> Seq.sum
let getNextSum sum index relativeIndexToAdd relativeIndexToRemove =
let primeToRemove = (calculator.getPrime (index + relativeIndexToRemove))
let nextPrime = (calculator.getPrime (index + relativeIndexToAdd))
sum + nextPrime - primeToRemove
let rec existSerieMatchingHelper targetSum cnt index sum2 =
match sum2 = targetSum with
| true -> true
| false when sum2 < targetSum -> false
| false ->
let nextSum = getNextSum sum2 index (-1) (cnt-1)
existSerieMatchingHelper targetSum cnt (index - 1) nextSum
let existSerieMatching sum cnt =
let primeIndex = (calculator.getIndexOfPrime sum)
let startIndex = primeIndex - cnt
let sum2 = calculateSumOfPrimes startIndex cnt
existSerieMatchingHelper sum cnt startIndex sum2
let rec run sum index =
match (calculator.isPrime sum) with
| false -> let nextSum = (getNextSum sum index connectingNumbers 0)
run nextSum (index+1)
| true ->
let candidate = serie |> List.fold (fun agg next -> agg && existSerieMatching sum next) true
match candidate with
| true -> sum
| false -> let nextSum = (getNextSum sum index connectingNumbers 0)
run nextSum (index+1)
let startSum = calculateSumOfPrimes 0 connectingNumbers
run startSum 0
let result = doStuff 541 [7;17;41]
[0 .. 20] |> List.map (fun i -> (i, (calculator.getPrime i))) |> List.map (fun i -> (printfn "%A" i))
//let result = doStuff 6 [3]
printfn "OK: %A" result
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
open System
#time
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let startDate = DateTime(1337,1,13)
let now = DateTime.Now
let isFriday (d:DateTime) = d.DayOfWeek = DayOfWeek.Friday
let result = Seq.initInfinite (fun i -> startDate.AddMonths(i))
|> Seq.takeWhile (fun d -> d < now)
|> Seq.filter isFriday
|> Seq.length
printfn "OK: %A" result
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
open System
#time
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let rec sieve = function
| (p::xs) -> p :: sieve [ for x in xs do if x % p > 0 then yield x ]
| [] -> []
let reverse (s:String) =
System.String(Array.rev (s.ToCharArray()))
let reverseNum i =
int (sprintf "%i" i |> reverse)
let isMirptal primes n =
let revN = n |> reverseNum
(primes |> List.filter (fun i -> i = revN && i <> n) |> List.length) > 0
let primes = sieve [2 .. 1000]
let result = primes |> List.filter (isMirptal primes) |> List.length
printfn "OK: %A" result
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
open System
#time
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let toCharArray n = (sprintf "%i" n).ToCharArray()
let isSameFlipped n =
let chars = n |> toCharArray
let length = chars |> Array.length
let rec isSameImpl i =
match i with
| -1 -> true
| _ -> match chars.[i] with
| '6' -> chars.[length - i - 1] = '9' && isSameImpl (i-1)
| '9' -> chars.[length - i - 1] = '6' && isSameImpl (i-1)
| '0' | '1' | '8' -> chars.[length - i - 1] = chars.[i] && isSameImpl (i-1)
| _ -> false
isSameImpl (length/2)
let result = {0 .. 100000} |> Seq.filter isSameFlipped |> Seq.length
printfn "OK: %A" result
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
open System
#time
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let result = seq {for x in 10 .. 99 do
for y in x .. 99 do
if ((string (x*y)).ToCharArray() |> Array.sort) = (((string x) + (string y)).ToCharArray() |> Array.sort) && not (((x % 10) = 0) && ((y % 10) = 0))
then yield 1} |> Seq.length
printfn "OK: %A" result
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
open System
#time
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let result = Seq.initInfinite (fun i -> (i, 1I <<< i)) |> Seq.filter (fun (i, x) -> (string x).Contains("472047")) |> Seq.head |> fst
printfn "OK: %A" result
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
open System
#time
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let getValidMoves = function
| 0 -> [4;6]
| 1 -> [6;8]
| 2 -> [7;9]
| 3 -> [4;8]
| 4 -> [3;9;0]
| 5 -> []
| 6 -> [1;7;0]
| 7 -> [2;6]
| 8 -> [1;3]
| 9 -> [2;4]
let calculatePaths n startPos =
let rec calculatePathsImpl res i pos =
let newRes = pos::res
match i = 0 with
| true -> [newRes]
| false ->
let movesFromHere = getValidMoves pos
List.concat (movesFromHere |> List.map (calculatePathsImpl newRes (i-1)))
calculatePathsImpl [] (n-1) startPos
let result = calculatePaths 10 1
printfn "OK: %A" (result |> List.length)
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
#r "FSharp.Collections.ParallelSeq.dll"
open System
open FSharp.Collections.ParallelSeq
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let readLines filePath = System.IO.File.ReadLines(filePath);;
let result =
readLines "words.txt"
|> Seq.toList
|> List.map (fun (w:string) -> (w, (w.ToLower().ToCharArray() |> Array.sort)))
|> PSeq.groupBy (fun (_, x) -> x)
|> PSeq.sortBy (fun (_, ws) -> -(ws |> Seq.length))
|> PSeq.head
|> fst
|> String.Concat
printfn "OK: %A" (result)
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
#r "FSharp.Collections.ParallelSeq.dll"
open System
open FSharp.Collections.ParallelSeq
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let text = "JegtroringenkanleveetheltlivutenkjærlighetMenkjærlighetenharmangeansikterIhøstkomdetutenboksomheterErlikKjærlighetDenbeståravsamtalermedselgereavgatemagasinetsomnåeretablertimangenorskebyerAllehardeenhistorieåfortelleomkjærlighetsomnoeavgjørendeEntendetertilenpartneretfamiliemedlemenvennelleretkjæledyrMangeharopplevdåblisveketogselvåsvikteMenutrolignokblirikkekjærlighetsevnenødelagtallikevelDenbyggesoppigjengangpågangKjærligheteneretstedåfesteblikketDengirossretningognoeåstyreetterDengirossverdisommenneskerognoeåleveforPåsammemåtesomkjærligheteneretfundamentimenneskeliveterGrunnlovenetfundamentfornasjonenNorgeFor200årsidensamletengruppemennsegpåEidsvollforålagelovensomskullebligrunnlagettildetselvstendigeNorgeGrunnlovensomdengangblevedtattharutvikletsegipaktmedtidenogsikreridagdetnorskefolkrettigheterviletttarforgittihverdagenRettighetersommenneskerimangeandrelandbarekandrømmeomogsomdeslossformedlivetsominnsatsJeghåperatvigjennomjubileumsfeiringeni2014vilbliminnetomhvaGrunnlovenegentligbetyrforosssåvikanfortsetteåarbeideforverdienevårebådeherhjemmeoginternasjonaltJegharlysttilånevnenoeneksemplerpåhvordanGrunnlovenvirkerinnpåenkeltmenneskerslivTenkdegatduskriveretkritiskinnleggomlandetsstyrepåsosialemedier"
let substringOfSize n = Seq.windowed n
let substrings (text: string) =
match text.Length with
| 0 -> Seq.empty
| 1 -> Seq.singleton [|text.[0]|]
| _ -> Seq.unfold (fun n -> if n <= text.Length then Some(substringOfSize n text, n+1) else None) 2
|> Seq.collect id
let isPalindrome (w:'a []) =
let l = w.Length - 1
seq {0 .. (l+1/2)} |> Seq.forall (fun i -> w.[i] = w.[l-i])
let result = text |> substrings |> Seq.filter isPalindrome |> Seq.sortBy (fun w -> -w.Length) |> Seq.head |> String.Concat
printfn "OK: %A" (result)
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
open System
let uniqueInList x xs = (xs |> List.filter (fun y -> y = x) |> List.length) = 1
let isPrime (number : int) =
match number with
| _ -> seq { 2 .. int(Math.Sqrt(float number))}
|> Seq.exists (fun x -> if (number % x = 0) then true else false)
|> not
let primeCandidates = [10..99] |> Seq.filter isPrime |> Seq.toList
let isPrimeForReal x = uniqueInList x primeCandidates
let lastTwo (y:string) = int(y.[(y.Length - 2)..(y.Length - 1)])
let hasNotDuplicates xs = (xs |> List.filter (fun x -> uniqueInList x xs) |> List.length) = (xs |> List.length)
let allIsPrimes = List.fold (fun a c -> a && (isPrimeForReal c)) true
let pairsToNumber xxs =
match xxs with
| x::xs -> xs |> List.map (sprintf "%i") |> List.map (fun x -> sprintf "%O" x.[1]) |> List.fold (fun a c -> a+c) (sprintf "%i" x)
| _ -> ""
let toPairs (x:int) =
let rec toPairs2 pairs (xStr:string) =
match xStr with
| xs when xStr.Length > 1 -> toPairs2 ((lastTwo xStr)::pairs) (xStr.[0 .. (xStr.Length - 2)])
| _ -> pairs
toPairs2 [] (sprintf "%i" x)
let lowerBound x = int(10.0**(x-1.0)*x)
let upperBound x = (lowerBound x)+int(10.0**(x-1.)-1.)
let explode (s:string) = [for c in s -> c]
let quickFilter x = (x % 2) <> 0
let calculate x =
let lowerBound = (lowerBound x)
let upperBound = (upperBound x)
{lowerBound..upperBound}
|> Seq.filter quickFilter
|> Seq.map toPairs
|> Seq.filter allIsPrimes
|> Seq.filter hasNotDuplicates
|> Seq.map pairsToNumber
|> Seq.head
let results = [3. .. 1. .. 9.] |> List.map (fun x -> (x, calculate x))
printfn "%A" results
open System
open System.Collections.Generic
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let crossSum i = i/100 + (i%100)/10 + (i%10)
type Coord = (int*int)
let calculateMoves startPos =
let exploredPaths = new Dictionary<Coord, bool>()
let calCulateValidNeighbours (x,y) =
[for xd in -1 .. 1 do
for yd in -1 .. 1 do
let x2 = x+xd
let y2 = y+yd
if x2 >= 0 && y2 >= 0 && (x2, y2) <> (x,y) && ((crossSum (x2)) + (crossSum (y2))) <= 19
then yield (x2, y2)]
let rec calculateMovesImpl list (explored:Dictionary<Coord,bool>) =
match list with
| [] -> explored
| x::xs ->
if explored.ContainsKey(x)
then
calculateMovesImpl xs explored
else
explored.Add(x, true)
let validNeighbours = calCulateValidNeighbours x
calculateMovesImpl (xs @ validNeighbours) explored
(calculateMovesImpl [startPos] exploredPaths).Keys
let result = calculateMoves (0,0)
let multiplier (x,y) =
match x,y with
| 0,0 -> 1
| 0,_ -> 2
| _,0 -> 2
| _,_ -> 4
printfn "OK: %A" (result |> Seq.map (fun k -> multiplier k) |> Seq.sum)
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
#r "FSharp.Collections.ParallelSeq.dll"
open System
open FSharp.Collections.ParallelSeq
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let readLines filePath = System.IO.File.ReadLines(filePath);;
let result =
readLines "words_luke21.txt"
|> Seq.map (fun w -> (w, w.ToCharArray() |> Array.map (fun c -> int c) |> Array.sum))
|> Seq.sortBy (fun t -> -(t |> snd))
|> Seq.take 42
|> Seq.map (fun t -> t |> snd)
|> Seq.sum
printfn "OK: %A" (result)
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
#r "FSharp.Collections.ParallelSeq.dll"
open System
open System.Collections.Generic
open FSharp.Collections.ParallelSeq
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let isMagicNumber x =
let rec recCalculateSqrts i res =
match i with
| 0 -> res
| _ -> recCalculateSqrts (i/10) (res + (i%10)*(i%10))
let rec isMagicNumberImpl i (seen:Dictionary<int, bool>) =
match i with
| 1 -> true
| _ ->
match seen.ContainsKey(i) with
| true -> false
| _ ->
seen.Add(i,true)
isMagicNumberImpl (recCalculateSqrts i 0) seen
let seenNumbers = new Dictionary<int, bool>()
isMagicNumberImpl x seenNumbers
let result = {1 .. 50}
|> PSeq.filter isMagicNumber
|> PSeq.sort
|> PSeq.toList
|> fun x -> String.Join(", ", x)
printfn "OK: %A" (result)
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
#r "FSharp.Collections.ParallelSeq.dll"
open System
open System.Collections.Generic
open FSharp.Collections.ParallelSeq
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let isMagicNumber n =
let rec isMagicNumberImpl div =
match n/div, n%div with
| 0,_ -> false
| x,y -> (x+y)*(x+y) = n || isMagicNumberImpl (div*10)
isMagicNumberImpl 10
let result = {1 .. (1000000-1)}
|> PSeq.filter isMagicNumber
|> PSeq.length
printfn "OK: %A" (result)
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
open System
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let result = {1 .. (1000000-1)}
|> Seq.filter (fun n -> n%10 = 6 && (n/10%10)=4)
|> Seq.filter (fun n -> int (sprintf "6%i" (n/10)) = 4*n)
|> Seq.head
printfn "OK: %A" (result)
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
open System
type Position = {X:int; Y:int}
type Color =
| White
| Black
let invertColor c = match c with
| White -> Black
| Black -> White
let colorToInt x = match x with
| Black -> 1
| White -> 0
let toPosition x = {X = x/10; Y = x % 10}
let toPositionNum x = x.X*10 + x.Y
let possibleMoves x =
[{X = x.X - 2; Y = x.Y - 1}; {X = x.X - 2; Y = x.Y + 1};
{X = x.X - 1; Y = x.Y - 2}; {X = x.X - 1; Y = x.Y + 2};
{X = x.X + 1; Y = x.Y - 2}; {X = x.X + 1; Y = x.Y + 2};
{X = x.X + 2; Y = x.Y - 1}; {X = x.X + 2; Y = x.Y + 1};
]
let validMove x = x.X >= 0 && x.Y >= 0 && x.X < 10 && x.Y < 10
let validMoves x = x |> toPosition |> possibleMoves |> List.filter validMove
let startBoard = [|0 .. 99|] |> Array.map (fun x -> White)
let rec last = function
| hd :: [] -> hd
| hd :: tl -> last tl
| _ -> failwith "Empty list."
let calculateNextMove pos (board:Color array) =
let color = board.[pos]
let candidates = validMoves pos
let candidatesWithSameColor = candidates
|> List.filter (fun x -> let posC = toPositionNum x in (board.[posC]) = color)
match candidatesWithSameColor with
| x::_ -> x |> toPositionNum
| _ -> candidates |> last |> toPositionNum
let newBoard currentPos newPos (board:Color array) =
board.[currentPos] <- (invertColor board.[currentPos])
board
let play board iterations =
let rec makeStep pos b iter =
let nextPos = calculateNextMove pos b
let nextBoard = newBoard pos nextPos b
match iter with
| 0 -> nextBoard
| _ -> makeStep nextPos nextBoard (iter - 1)
makeStep 0 board (iterations - 1)
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let result = play startBoard 200 |> Array.map colorToInt |> Array.sum
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
printfn "What: %i" result
#r "FSharp.Data.TypeProviders"
#r "..\FSharp.Data.dll"
open Microsoft.FSharp.Data.TypeProviders
open FSharp.Data
open System.Text.RegularExpressions
open System
type Blindern = CsvProvider<"../blindern.txt">
let csv = Blindern.Load("../blindern.txt")
let (|ParseRegex|_|) regex str =
let m = Regex(regex).Match(str)
if m.Success
then Some (List.tail [ for x in m.Groups -> x.Value ])
else None
let (|Integer|_|) (str: string) =
let mutable intvalue = 0
if System.Int32.TryParse(str, &intvalue) then Some(intvalue)
else None
let toDate x =
match x with
| ParseRegex "(\d{2}).(\d{2}).(\d{4})$" [Integer d; Integer m; Integer y] -> new System.DateTime(y, m, d)
let x = csv.Rows
|> Seq.map (fun r -> (toDate r.Dato, r.TAN))
|> Seq.filter (fun (d,i) -> d.Month = 12)
|> Seq.reduce (fun (d1,i1) (d2,i2) -> if i2 < i1 then (d2,i2) else (d1,i1))
#r "FSharp.Collections.ParallelSeq.dll"
open System
open FSharp.Collections.ParallelSeq
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let primfaktorer n =
let rec primFaktorImpl x res candidate =
if candidate > x/candidate
then match x with
| 1 -> res
| _ -> x::res
else match x % candidate with
| 0 -> primFaktorImpl (x/candidate) (candidate::res) candidate
| _ -> primFaktorImpl (x) (res) (candidate+1)
primFaktorImpl n [] 2
let rec removeFirst pred lst =
match lst with
| h::t when pred h -> t
| h::t -> h::removeFirst pred t
| _ -> []
let existInList x list = list |> List.exists (fun y -> y = x)
let rec insertions x = function
| [] -> [[x]]
| (y :: ys) as l -> (x::l)::(List.map (fun x -> y::x) (insertions x ys))
let rec permutations = function
| [] -> seq [ [] ]
| x :: xs -> Seq.concat (Seq.map (insertions x) (permutations xs))
let result = 123456789
|> (fun x -> (sprintf "%i" x).ToCharArray())
|> Array.toList
|> permutations
|> PSeq.map (fun i -> i |> Array.ofList |> System.String.Concat |> int)
|> PSeq.map primfaktorer
|> PSeq.map (fun x -> x |> List.head)
|> PSeq.min
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
printfn "%i" result
open System.Threading.Tasks
#time
let calculateProducts n =
let bits = Array.init ((n+1)*(n+1)) (fun _ -> 0)
let inner i =
let arr = Array.init (n-i+1) (fun x -> x+i)
Parallel.ForEach(arr, (fun j -> bits.[j*i] <- 1)) |> ignore
let arr = Array.init n (fun x -> (x+1))
Parallel.ForEach(arr, (fun i -> inner i)) |> ignore
bits |> Array.sum
printfn "%i" (calculateProducts 8000)
open System.Threading.Tasks
open System.Drawing
open Microsoft.FSharp.Collections
open System.Collections.Generic
#time
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let image = new Bitmap("Santa.png")
let size = image.Size
let result = new Dictionary<System.Drawing.Color, int>()
let x = Array.init size.Width (fun i -> i)
let y = Array.init size.Height (fun i -> i)
let updatePixels (pixel: System.Drawing.Color) =
match result.ContainsKey(pixel) with
| true -> result.[pixel] <- result.[pixel] + 1
| false -> result.Add(pixel, 1)
let doStuff i =
y |> Array.map (fun j -> (image.GetPixel(i,j) |> updatePixels)) |> ignore
x |> Array.map (fun i -> doStuff i) |> ignore
let a = result |> Seq.sortBy (fun (KeyValue(k,v)) -> -v) |> Seq.take 10 |> Seq.toList
printfn "%A" a;;
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
open System.Threading.Tasks
open System.Drawing
open Microsoft.FSharp.Collections
open System.Collections.Generic
open System.Collections.Concurrent
#time
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let divisors i =
let rec divisorsImpl x res =
if x < 1 then res
else match i % x with
| 0 -> divisorsImpl (x-1) (x::res)
| _ -> divisorsImpl (x-1) res
divisorsImpl (i/2) []
let result = [1 .. 10000] |> List.filter (fun i -> ((divisors i |> List.sum) = i))
printfn "OK: %A" result
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
#time
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let lastManStanding n =
let folks = Array.init (n+1) (fun i -> i+1)
folks.[1500] = 1
let rec lastManStandingImpl index =
let nextIndex = folks.[index]
let nextNextIndex = folks.[nextIndex]
match nextNextIndex with
| 0 -> index
| _ -> folks.[index] <- nextNextIndex
folks.[nextIndex] <- 0
lastManStandingImpl nextNextIndex
lastManStandingImpl 1
let result = lastManStanding 1500
printfn "OK: %A" result
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment