Skip to content

Instantly share code, notes, and snippets.

@sungkmi
Created June 10, 2016 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sungkmi/1316c04cbac12e46998e046350381b86 to your computer and use it in GitHub Desktop.
Save sungkmi/1316c04cbac12e46998e046350381b86 to your computer and use it in GitHub Desktop.
object CoinJam extends App {
def next(n: BigInt): Stream[BigInt] = n #:: next(n + 2)
lazy val primes = {
def next(n: BigInt): Stream[BigInt] = n #:: next(n + 1)
def sieve(s: Stream[BigInt]): Stream[BigInt] = s.head #:: sieve(s.tail.filter(_ % s.head != 0))
sieve(next(2))
}
def findDivisor(n: BigInt): Option[BigInt] = {
primes.takeWhile(_ < 10000).filter(p => n % p == 0).headOption
}
def coinJam(n: Int, j: Int): Seq[(String, Seq[Int])] = {
for {
s <- next(BigInt("1" ++ "0" * (n-2) ++ "1", 2))
ns = (2 to 10).map(r => BigInt(s.toString(2), r))
if (ns.forall(n => !n.isProbablePrime(4)))
_ <- Seq(println(s"Trying: ${s.toString(2)}"))
divisiors = ns map findDivisor
if divisiors forall (_.nonEmpty)
} yield (s.toString(2), divisiors.map(_.get.toInt))
}.take(j).toList
def process(lineOut: String => Unit) = {
lineOut("Case #1:")
val ans = coinJam(16, 500)
ans foreach { case (s, divisors) =>
lineOut(s"$s$s ${divisors mkString " "}")
}
}
val filename = "C-large-practice"
val writer = new java.io.PrintWriter(filename + ".out")
try {
process{ s =>
writer.println(s); writer.flush()
}
} finally {
writer.flush(); writer.close()
}
}
import org.scalatest._
import CoinJam._
class CoinJamTest extends FunSuite with Matchers {
test("findDivisor") {
assert(findDivisor(4) === Some(2))
assert(findDivisor(11) === None)
}
test("coinJam") {
val ans = coinJam(6, 3)
assert(ans.size === 3)
ans foreach { case (s, divisors) =>
for((r, divisor) <- (2 to 10) zip divisors) { assert(BigInt(s, r) % divisor === 0) }
}
}
def lineComparison(input: Iterator[String], expected: Iterator[String]): Unit = {
process(input) { s =>
for (line <- s.lines) assert(line.trim === expected.next().trim)
}
assert(expected.hasNext === false, "Finished too fast.")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment