bcherny / bcherny/learner

Consider building graph of Char->Char and doing a topological sort on it...

Open
#1 3 comments 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
0
Forks
1
PR merge metrics
No merged PRs in 30d

Description

Here is my Scala impl.:

``` scala
class Learner[A](root: A) {
import scala.collection.mutable.{Map => Dict}
private val next = Dict.empty[A, Set[A]] withDefaultValue Set.empty[A]

def learn(words: Seq[A]*) = for {
i <- words.indices
_ = words(i).foreach(u => next(root) += u)
j <- words.indices drop (i+1)
(u, v) <- words(i) zip words(j) find {case (a, b) => a != b}
} next(u) += v

private def dfs(visited: Set[A], depth: Dict[A, Int])(u: A): Dict[A, Int] = {
require(!visited(u), s"Cycle detected involving $u")
next(u).filterNot(visited).foreach(dfs(visited + u, depth))
depth(u) = depth(u) max visited.size
depth
}

def inferOrdering(): Seq[(A, Int)] = dfs(Set.empty, Dict.empty[A, Int] withDefaultValue 0)(root).toSeq
}

object AlphabetLearner extends App {
val learner = new Learner('*')
learner.learn("alpha", "baby", "beta", "brownies", "cat", "dad", "dog", "elephant", "ralph", "orange")
val ordering = learner.inferOrdering()
ordering sortBy {case (_, depth) => depth} foreach println
}
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.