Re: HHC 2013 programming contest winners Message #53 Posted by David Hayden on 26 Sept 2013, 11:39 p.m., in response to message #1 by Brian Walsh
Over the past couple of days I've put together a solution to the RPL problem that takes a different approach. This converts the digits to binary and then does carry-free addition with bit twiddling.
At 281 bytes, it's huge, but because there are NO LOOPS it's very fast.
For base 2 you just XOR the numbers.
For base 8, you covert the octal digits as a hex number (e.g., 77. to #77h), thus there is one extra bit to the left of each octet. Now you can add the numbers and any carry goes into the extra bit, which is then masked out.
Base 10... oh you silly base 10.... As with base 8, I convert the digits in hex mode (e.g., 94. to #94h). So each digit occupies 4 bits. The trick is to add them while subtracting 10 from the sum in such a way that the sum is never greater than 15, which would cause it to spill over to the next digit's bits. If two digits are A and B, the code says "if A is greater than 5 then subtract 5 from it and add 5 to B. If B is now greater than 10 then subtract 10 from it. Now A is in the range [0..5] and B is [0..9], so you can add them and the result is [0..14] which still fits in 4 bits. If the sum is greater than 10 then subtract 10." All of this is done with bit manipulation on all digits simultaneously.
I may write this up in a Datafile article.
Replace the ">" characters with the right arrow. Sorry, I keep forgetting now to convert a listing to ascii. :(
«
{ { R¨>I ¨>STR "#" SWAP + OBJ¨> }
SWAP OVER EVAL UNROT EVAL } @ You now have binaries with the same digits
SWAP CASE
DUP 2. == THEN
@ This is easy. Convert to binary and XOR together
BIN DROP EVAL
XOR
END
DUP 8. == THEN
HEX DROP EVAL
ADD #7777777777777777h AND
END
@ It better be 10
HEX DROP EVAL
DUPDUP SL AND @ a & (a<<1)
OVER SR OR #4444444444444444h AND @ x.4 = a.8 | (a.4 & a.2)
@ level 1 now contains 4 if a>5. subtract from a and add
@ to b
SWAP OVER -
UNROT +
@ b a
{ DUPDUP SL OR @ b | (b<<1)
SL OVER AND @ b.8 & (b.4 | b.2)
#8888888888888888h AND
DUP SR SR OR
-
}
SWAP OVER EVAL @ sub10(b)
@ b Sub10 a
ROT + @ a+b Sub10
SWAP EVAL @ here is the answer, but in hex
END
@ Level 1 contains a binary number reprenting the answer.
@ convert the digits to a real.
¨>STR
DUP SIZE 1. - 2. SWAP SUB @ take off the h
OBJ¨>
»
|