Skip to content

Instantly share code, notes, and snippets.

@NightRa
Last active December 19, 2015 05:19
Show Gist options
  • Save NightRa/5903046 to your computer and use it in GitHub Desktop.
Save NightRa/5903046 to your computer and use it in GitHub Desktop.
A nice combinatoric problem.
object Math extends App {
case class ResultSet(n1: Int, n2: Int) {
lazy val result = n1 * n2
override def equals(obj: Any): Boolean = obj match {
case r: ResultSet => (n1 == r.n1 && n2 == r.n2) || (n1 == r.n2 && n2 == r.n1)
case _ => false
}
override def toString: String = s"($n1,$n2)"
}
def noCommonDigits(n1: Int, n2: Int): Boolean =
if (n1 == 0) true
else if (hasDigit(n2, n1 % 10)) false
else noCommonDigits(n1 / 10, n2)
def hasDigit(num: Int, digit: Int): Boolean =
if (num == 0) digit == 0
else if (num % 10 == digit) true
else hasDigit(num / 10, digit)
def combinationsRange(n: Int) = (1 to 9).combinations(n).map(_.foldLeft(0)((rest, digit) => rest * 10 + digit)).toList
def combinationsString(n: Int) = "123456789".combinations(n).map(_.toInt).toList
def combinationsPermutations(n: Int): List[Int] =
(for {
combination <- (1 to 9).combinations(n)
permutation <- combination.permutations
} yield permutation.mkString("").toInt).toList
def combinations(n: Int) = combinationsPermutations(n)
def nCombinations(n: Int): IndexedSeq[Int] =
for {
x <- 1 to n
comb <- combinations(x)
} yield comb
def allNumbers: IndexedSeq[Int] = nCombinations(4)
def multi =
for {
num1 <- allNumbers
num2 <- allNumbers
if (noCommonDigits(num1, num2))
} yield new ResultSet(num1, num2)
def groups = multi.groupBy(resultSet => resultSet.result).map {
case (result, seq) => (result, seq.toSet)
}.filter {
case (result, set) => set.size != 1
}
for ((product, answerList) <- groups.toList.sortBy(_._2.size)) {
println(s"Pairs: ${answerList.mkString("[", ",", "]")}, Product: $product")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment