diff --git a/day26/README.md b/day26/README.md new file mode 100644 index 0000000..64f39d3 --- /dev/null +++ b/day26/README.md @@ -0,0 +1,48 @@ +question of the day: https://codefights.com/challenge/ChcFLSa3rfJsKNgkC + +The fight on whether to store numbers starting with their most +significant digit or their least significant digit has been going +on for years. It even got a name and is called the Endian War by +some specialists. + +Joe Stoy in his (excellent, by the way) book "Denotational Semantics", +tells the following story about Alan Turing: "...One early British +computer had numbers running from right to left (because the spot +on an oscilloscope tube runs from left to right, but in serial +logic the least significant digits are dealt with first). Turing +used to mystify audiences at public lectures when, quite by +accident, he would slip into this mode even for decimal arithmetic, +and write things like 73+42=16...". + +You are given an expression that was presumably written by Alan Turing. +Return true if it is a correct expression written in the little-endian +decimal format, or return false otherwise. + +## Example + +For expression = 73+42=16, the output should be +endianWar(expression) = true. + +In the little-endian decimal format, the expression becomes +37 + 24 = 61, which is correct. + +For expression = "5+8=13", the output should be +endianWar(expression) = false. + +In the little-endian decimal format, the result of the expression should +be 31. + +## Ideas + +Let's break the expression string up and check the math. Reverse the +two addends and sum them, then check against the reversed little-endian +sum. + +`O(n)` to do the splits on the expression, `O(n)` to reverse the numbers +and convert into ints. `O(1)` to check the math of the expression. + +## Code + +[Python](./endianWars.py) + +## Follow up diff --git a/day26/endianWars.py b/day26/endianWars.py new file mode 100644 index 0000000..04e0ca6 --- /dev/null +++ b/day26/endianWars.py @@ -0,0 +1,30 @@ +def endianWar(expression): + a, _ = expression.split("+") + b, c = _.split("=") + return int(a[::-1]) + int(b[::-1]) == int(c[::-1]) + +def testEndianWar(): + # little endian + assert endianWar("73+42=16") + assert endianWar("10+20=30") + assert endianWar("11+44=55") + assert endianWar("2466+7=9466") + assert endianWar("2+19=39") + assert endianWar("4+3=7") + assert endianWar("714+8=524") + assert endianWar("47+17=541") + assert endianWar("99+54962=44072") + + # not little endian + assert not endianWar("8861+81209=90070") + assert not endianWar("5+8=13") + assert not endianWar("649+68072=68721") + assert not endianWar("65+72825=72890") + assert not endianWar("930+70374=71304") + +def main(): + testEndianWar() + +if __name__ == "__main__": + return main() + \ No newline at end of file