Interview Question
Country: United States
Interview Type: Written Test
// ZoomBA
def term_parse( s ){
term = [ 0.0 , '' ]
p = tokens('^[\+\-]?(\d+(\.\d+)?)?')
m = p.matcher( s ) ; m.find() // true always
opts = { '' : 1.0 , '+' : 1.0 , '-' : -1.0 }
if ( m.group @ opts ) {
term[0] = opts[ m.group ]
} else {
term[0] = float( m.group )
}
inx = index ( s.value ) :: { str($.item) =~ '[a-zA-Z]' }
term[1] = s[ (inx < 0 ? 0 : inx) : -1 ]
if ( inx < 0 ){ term[1] = '' }
term
}
def gen_expr( s ){
l = tokens(s, '[\+\-]?[^\+\-]+') -> { term_parse( $.item ) }
d = mset ( l ) -> { $.item.1 }
}
def normalize( s ){
s = s.replace(' ','')
#(l,r) = s.split('=')
ld = gen_expr ( l )
rd = gen_expr ( r )
// merge
u = ld.keys | rd.keys // union
poly = list ( u ) -> {
k = $.item ; coeff = 0.0
if ( k @ ld ){ coeff += sum ( ld[k] )->{ $.item[0] } }
if ( k @ rd ){ coeff -= sum ( rd[k] )->{ $.item[0] } }
[ k , coeff ]
}
sortd ( poly ) :: { #(l,r) = $.item ; l.0 < r.0 }
str( poly , '' ) -> { #(k,c) = $.item ; str( '%+f%s' , c , k ) }
}
x = normalize ( 'x^2 + 3.5xy + y = y^2 - xy + y + 10' )
println ( x )
Parsed input into list of Term object (coefficient and mapping from var name to its power value), recursively parsing inside parentheses. Combined likes by mapping from strings representing terms without coefficients (x2y3z) to List<Term>. Sorted by term's highest power value.
- kanukadze October 18, 2016