Project Euler – Problem 79 Solution

Yan Cui

I help clients go faster for less using serverless technologies.

Problem

A common security method used for online banking is to ask the user for three random characters from a passcode. For example, if the passcode was 531278, they may ask for the 2nd, 3rd, and 5th characters; the expected reply would be: 317.

The text file, keylog.txt, contains fifty successful login attempts.

Given that the three characters are always asked for in order, analyse the file so as to determine the shortest possible secret passcode of unknown length.

Solution

open System.IO
open System.Collections.Generic
// read the keylog file into a int [] []
let entries = File.ReadAllLines(@"c:\temp\keylog.txt")
|> Array.map (fun str -> str.ToCharArray() |> Array.map (fun c -> int(c.ToString())))
// dictionary for keeping track of the list of numbers that falls behind a number
let inFrontOf = new Dictionary<int, int list>();
/// function to add the specified int list to the list of numbers that falls behind n
let addInFrontOf n (lst : int list) =
if inFrontOf.ContainsKey n then inFrontOf.[n] <- set(lst @ inFrontOf.[n]) |> Set.toList
else inFrontOf.[n] <- set(lst) |> Set.toList
// analyse the login attempts and populate the dictionary
entries
|> Array.iter (fun arr ->
addInFrontOf arr.[0] [arr.[1]; arr.[2]]
addInFrontOf arr.[1] [arr.[2]]
addInFrontOf arr.[2] [])
let answer = inFrontOf
|> Seq.sortBy (fun kvp -> kvp.Value.Length)
|> Seq.map (fun kvp -> kvp.Key)
|> Seq.toList
|> List.rev

This problem is actually solved much easier by hand with pen and paper, but regardless here’s a F# solution to the problem.

Whenever you’re ready, here are 3 ways I can help you:

  1. Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
  2. I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
  3. Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.

Leave a Comment

Your email address will not be published. Required fields are marked *