Skip to content

Instantly share code, notes, and snippets.

@brunofarache
Created November 22, 2020 00:54
Show Gist options
  • Save brunofarache/94eae2ad070bca14ddedf524affaf486 to your computer and use it in GitHub Desktop.
Save brunofarache/94eae2ad070bca14ddedf524affaf486 to your computer and use it in GitHub Desktop.
def atMostNGivenDigitSet(digits: Array[String], n: Int): Int = {
val sorted = digits.map(_.toInt).sorted
val maxPow = math.log10(n).toInt
def atMostNGivenDigitSet(sorted: Array[Int], pow: Int = 0): collection.mutable.Set[Int] = {
if (pow > maxPow) return collection.mutable.Set()
val digitSet = collection.mutable.Set[Int]()
for (digit <- sorted) {
val result = atMostNGivenDigitSet(sorted, pow + 1)
val current = digit * math.pow(10, pow).toInt
digitSet += current
if (result.nonEmpty) {
digitSet ++= result.map(_ + current)
}
}
digitSet
}
val set = atMostNGivenDigitSet(sorted).filter(_ <= n)
println(set)
set.size
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment