Created
October 29, 2022 04:42
-
-
Save MishaelRosenthal/376577b21ce1d8210b728e2c9f82be49 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Digit = Int | |
def toDigits(i: Int) = i.toString.map(_.asDigit).reverse | |
def fromDigits(digits: Seq[Digit]) = digits.reverse.dropWhile(_ == 0).map(_.toString).reduce(_ + _).toInt | |
case class FullAdder(inCarry: Digit, i: Digit, j: Digit) { | |
val asDigits = toDigits(inCarry + i + j) | |
def sum() = asDigits(0) | |
def carry() = if(asDigits.length > 1) asDigits(1) else 0 | |
} | |
def longAddition(x: Int, y: Int) = { | |
val xDigits = toDigits(x) ++ Seq(0) | |
val yDigits = toDigits(y) ++ Seq(0) | |
val zipped = xDigits.zipAll(yDigits, 0, 0) | |
val adders = zipped.scanLeft(FullAdder(0, 0, 0)) { case (acc, (i, j)) => FullAdder(acc.carry(), i, j)}.tail | |
fromDigits(adders.map(_.sum())) | |
} | |
val x = 145678 | |
val y = 7865 | |
val res = longAddition(x, y) | |
println("res is " + res + ", res equals x + y is " + (x + y == res)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment