Lever Simulator 2015
Javascript ES6, 62 Bytes
s=>Math.sign([...s].reduce((p,c,i)=>p+~~c*(i-s.indexOf`^`),0))
-1
if left is heavier0
if balanced1
if right is heavier
Ungolfed:
s=>
Math.sign( // output sign of weight of lever
[...s].reduce((p,c,i)=> // split and reduce input
p+~~c*(i-s.indexOf`^`),0)) // add weights of all elements
// (elements left of pivot are negatively weighted)
Test runs (assigning anonymous function to f
):
>> f("11 ^9")
<< 0
>> f("321^ 12")
<< -1
>> f("9^ 1")
<< 1
- -11 bytes: changed output from
R B L
to-1 0 1
- -3 bytes: changed
e.split``
to[...e]
(thanks @Vɪʜᴀɴ) - -33 bytes: changed algorithm to use negative weights rather than splitting at pivot
- -9 bytes: removed pivot check (apparently,
~~'^'
evaluates to0
...) - -2 bytes: made function anonymous (thanks @cᴏɴᴏʀ-obʀɪᴇɴ)
Python 2, 69 bytes
lambda s:cmp(sum(ord(c)%16*(i-s.find('^'))for i,c in enumerate(s)),0)
The modulus ord(c)%16
extracts the value of a digit character while getting 0 for space. For each character, its torque contribution is computed as its weight times the signed distance to the pivot i-s.find('^')
, and these are summed and compared to 0, producing one of -1,0,1
. The character ^
is computed to have weight 14, but that doesn't matter because it's on the pivot.
An 18-byte Pyth port by Maltysen:
._s.e*-kxz\^%Cb16z
For the Python code, if a full program is required, here's 79 bytes. The idea is to start the index i
shifted by s.find('^')
, and have it count down.
s=raw_input()
t=0;i=s.find('^')
for c in s:t-=ord(c)%16*i;i-=1
print cmp(t,0)
APL, 39 30 bytes
{×+/(10|⍵⍳⍨∊⍕¨⍳9)×(⍳⍴⍵)-⍵⍳'^'}
After rereading the rules, I've changed this to output -1
0
1
instead of L
B
R
, saving nine bytes.
Try it here.