The Base in the mix
Python 3, 40 bytes
lambda a:sum(map(int,map(str,a),[10]+a))
Tests are at ideone
map(str, a)
creates a generator, G
, that calls str
on each value in a
, converting to strings
map(int, G, [10]+a)
creates a generator that calls int(g, v)
for pairs across G
and [10]+a
int(g, v)
converts the string g
from the integer base v
(if v
is in [2,36]
and g
is valid)
sum
does what it says on the tin
Python 2, 48 bytes
lambda a:sum(int(`x`,y)for x,y in zip(a,[10]+a))
Tests are at ideone
zip(a,[10]+a)
traverses pairs of the values in a
, and the previous value or 10
for the first
the backticks
in the int
call convert x
to a string, s
int(s, y)
converts the string s
from the integer base y
(if y
is in [2,36]
and s
is valid)
sum
does what it says on the tin
Perl, 35 34 33 bytes
Includes +2 for -ap
Run with the list of numbers on STDIN:
basemix.pl <<< "4 12 34 20 14 6 25 13 33";echo
basemix.pl
:
#!/usr/bin/perl -ap
$\+=$&+"$`$& 10"*/.$/*$`for@F}{
I've been waiting for ages for a chance to use this abuse...
Explanation
The input numbers can have at most 2 digits. A number xy
in base b
is simply b*x+y
. I'm going to use the regex /.$/
so the first digit ends up in $`
and the last digit in $&
, so the contribution to the sum is $&+$b*$`
.
I abuse the fact that for
does not properly localize the regex variables (like for example map
and while
do) so the results of a match in the previous loop is still available in the current loop. So if I'm careful about the order in which I do the operations the base is available as "$`$&"
, except for the very first loop where I need the base to be 10. So I use "$`$& 10"
instead
The way the first $&
works is an abuse too since it is actually changed by the /.$/
while it is already on the stack waiting to be added.
The final abuse is the }{
at the end which changes the loop implied by -p
from
LINE: while (defined($_ = <ARGV>)) {
...code..
}
continue {
die "-p destination: $!\n" unless print $_;
}
to
LINE: while (defined($_ = <ARGV>)) {
...code..
}
{
}
continue {
die "-p destination: $!\n" unless print $_;
}
Which means $_
will be undefined in the print, but it still adds $\
in which I accumulated the sum. It is also a standard golf trick to get post-loop processing