Sha256: 7bb38ee272a768456a94023485f84f2e11ba715c4df815523fa0dc57f3490a74

Contents?: true

Size: 1.25 KB

Versions: 74

Compression:

Stored size: 1.25 KB

Contents

module WordSearch

let private directions =
    [( 1,  0);
     ( 0,  1);
     (-1,  0);
     ( 0, -1);
     ( 1,  1);
     ( 1, -1);
     (-1,  1);
     (-1, -1)]
     
let private update (x, y) (dx, dy) = x + dx, y + dy

let search (grid: string list) (wordsToSearchFor: string list) =
    let width = List.head grid |> Seq.length
    let height = List.length grid

    let findChar (x, y) = 
        if x > 0 && x <= width && y > 0 && y <= height then 
            Some grid.[y - 1].[x - 1]
        else None
        
    let findWord start direction word =
        let rec helper coord last (remainder: string) =
            if remainder.Length = 0 then Some (start, last)
            elif Some remainder.[0] = findChar coord then helper (update coord direction) coord remainder.[1..]
            else None

        helper start start word

    let tryFindWord word =
        seq { for x in 1 .. width do
                for y in 1 .. height do
                    for dir in directions do
                        let result = findWord (x, y) dir word
                        if Option.isSome result then
                            yield Option.get result }
        |> Seq.tryHead

    wordsToSearchFor
    |> List.map (fun word -> (word, tryFindWord word))
    |> Map.ofList

Version data entries

74 entries across 74 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/fsharp/exercises/word-search/Example.fs
trackler-2.2.1.179 tracks/fsharp/exercises/word-search/Example.fs
trackler-2.2.1.178 tracks/fsharp/exercises/word-search/Example.fs
trackler-2.2.1.177 tracks/fsharp/exercises/word-search/Example.fs
trackler-2.2.1.176 tracks/fsharp/exercises/word-search/Example.fs
trackler-2.2.1.175 tracks/fsharp/exercises/word-search/Example.fs
trackler-2.2.1.174 tracks/fsharp/exercises/word-search/Example.fs
trackler-2.2.1.173 tracks/fsharp/exercises/word-search/Example.fs
trackler-2.2.1.172 tracks/fsharp/exercises/word-search/Example.fs
trackler-2.2.1.171 tracks/fsharp/exercises/word-search/Example.fs
trackler-2.2.1.170 tracks/fsharp/exercises/word-search/Example.fs
trackler-2.2.1.169 tracks/fsharp/exercises/word-search/Example.fs
trackler-2.2.1.167 tracks/fsharp/exercises/word-search/Example.fs
trackler-2.2.1.166 tracks/fsharp/exercises/word-search/Example.fs
trackler-2.2.1.165 tracks/fsharp/exercises/word-search/Example.fs
trackler-2.2.1.164 tracks/fsharp/exercises/word-search/Example.fs
trackler-2.2.1.163 tracks/fsharp/exercises/word-search/Example.fs
trackler-2.2.1.162 tracks/fsharp/exercises/word-search/Example.fs
trackler-2.2.1.161 tracks/fsharp/exercises/word-search/Example.fs
trackler-2.2.1.160 tracks/fsharp/exercises/word-search/Example.fs