CodeGolf - Heads or Tails
C, 18 bytes
Pretty easy, but let's do it just for fun...
puts("-1"+*i/8%2);
Given the string char *i
it prints 1 for heads
and -1 for tails
, with trailing newline.
Explanation
In C, "-1" + 1
points to 1 character forward, so it is the same as "1"
. Let's take a look at the first characters:
"heads"[0] = 'h' = 104 = 0b01101000
"tails"[0] = 't' = 116 = 0b01110100
If we count the bits from the rightmost one starting at zero, bit 3 is 1 in heads
and 0 in tails
: summing it to "-1"
gives the right string. It looks like this:
"-1" + ((i[0] >> 3) & 1)
Now, substitute i[0]
with *i
and the right shift with the power-of-two division to save some bytes. Also remove useless parentheses:
"-1" + (*i / 8 & 1)
Now, & 1
can be substituted with % 2
. The character count is the same, but the modulus has higher priority, allowing to drop the parentheses. Remove the whitespace:
"-1"+*i/8%2
Bonus
I think the shortest way to get an integer 1 or -1 (not a string) in C is:
18-*i/6
Explanation:
'h' = 104
't' = 116
('h' + 't') / 2 = 110
110 - 'h' = 6
110 - 't' = -6
(110 - 'h') / 6 = 1
(110 - 't') / 6 = -1
Apply distributive property (integer division):
18 - 'h' / 6 = 1
18 - 't' / 6 = -1
CJam, 4 bytes
I'e#
Assumes that the variable I
holds the input, since i
isn't a valid identifier in CJam.
Try it online.
This is equivalent to the JavaScript code I.indexOf('e')
.
Ruby, 8 (6 without output)
p ?t<=>i
Rocketship operator!