Will I tip over?
JavaScript (ES6), 116 111 108 106 bytes
-5 bytes by summing via eval(array.join`+`)
instead of array.reduce()
.
-3 bytes by defaulting to 1
instead of 32 - 31
, allowing parentheses to be removed.
-2 bytes since pivot point is the length of the last line - 1
(s,[t,r,b]=s.split`
`)=>Math.sign(eval([...r].map((_,i)=>(t.charCodeAt(i)-31||1)*(i-b.length+1)).join`+`))
Outputs -1
, 0
, or 1
, for left, balanced, or right, respectively. Ended up similar to Chas Brown's python answer, so credit goes there.
Can save 4 bytes if the first line is padded to match the length of the rod by using
(31-t.charCodeAt(i))*(b.length+~i)
.
Test Snippet
Includes additional output (Left
/Balanced
/Right
) along with the number.
f=
(s,[t,r,b]=s.split`
`)=>Math.sign(eval([...r].map((_,i)=>(t.charCodeAt(i)-31||1)*(i-b.length+1)).join`+`))
<textarea id=I rows=3 cols=20></textarea><br><button onclick="O.value=I.value?`${x=f(I.value)} (${['Left','Balanced','Right'][x+1]})`:''">Run</button> <input id=O disabled>
Another 106 byte method
(s,[t,r,b]=s.split`
`)=>Math.sign(eval(r.replace(/./g,(_,i)=>"+"+(t.charCodeAt(i)-31||1)*(i-b.length+1))))
Instead of join
ing an array on +
s, we create a string of numbers, each prefixed by +
. The leading +
gets ignored.
Python 2, 112 110 bytes
def f(s):w,b,p=s.split('\n');return cmp(sum((ord((w+' '*-~i)[i])-31)*(i-p.find('|'))for i in range(len(b))),0)
Try it online!
EDIT: Finally managed to eliminate the enumerate
and rjust
for a measly 2 bytes... meh!
Takes in a string; outputs -1,0, or 1 for falls left, balances, falls right, respectively.
First pass at 112 bytes was:
def f(s):w,b,p=s.split('\n');return cmp(sum((ord(c)-31)*(i-p.find('|'))for i,c in enumerate(w.rjust(len(b))),0)
Haskell, 212 171 bytes (188 if take input as one string)
o!p=map(fst)(zip[p-0,p-1..]o)
x#p=sum(zipWith(\c w->(max(fromEnum c-32)0)*w)x(x!p))+sum(x!p)
x?c=length(takeWhile(==c)x)
171 bytes variant
r a b c=signum(take(b?'=')(a++repeat ' ')#(c?' '))
188 bytes variant
x%y=lines x!!y
r i=signum(take(i%1?'=')(i%0++repeat ' ')#(i%2?' '))
Explanation
o!p=map(fst)(zip[p-0,p-1..]o) Creates weights coefs list.
o - list, p - pivot position
for list "abcdf" and p=3 (pivot under 'd')
outputs [3,2,1,0,-1]
x#p Calculates total balance
x-list of "objects" on lever, p-pivot place
sum(zipWith sum of zipped lists
(\c w->(max(fromEnum c-32)0)*w) weight of ascii "object" times
distance from pivot
x(x!p)) x-ascii objects,
(x!p)-distances list(weight coefs)
+sum(x!p) balance of lever ("==") itself
x?c=length(takeWhile(==c)x) length of list before non c element met
used to find '|' position
and length of "===" lever
before right whitespaces met
r a b c= Sums it all up =)
a-ascii objects, b-lever, c-pivot line
signum( 1-tips left, 0-balance, -1-tips right
take(b?'=')(a++repeat ' ') takes all object on lever
plus whitespaces up to length of the lever
# calculate the balance
(c?' ') determine place of pivot