Given an array of positive integers, calculate the sum of each number raised to its own power. For example, given 4,6,7
, the code needs to return \$4^4+6^6+7^7=870455\$.
This is code-golf, so shortest code wins.
Given an array of positive integers, calculate the sum of each number raised to its own power. For example, given 4,6,7
, the code needs to return \$4^4+6^6+7^7=870455\$.
This is code-golf, so shortest code wins.
+.$^
+.$^ # full program
+x$^$$ # with implicit variables shown
+ # sum of
. # map over
$ # each element of input
^ # x to the power of y:
$ # x is each element
$ # y is each element
-3 bytes thanks to Albert.Lang.
lambda l:sum(map(pow,l,l))
lambda l: # Anonymous lambda
sum( ) # Sum of...
map(pow, ) # Exponentiation of...
l,l # element ** element for each element
lambda l:sum(map(pow,l,l))
\$\endgroup\$
Commented
Jul 11 at 22:08
map
could only have 2 arguments...
\$\endgroup\$
Commented
Jul 11 at 22:13
[S S S N
_Push_sum=0][N
S S N
_Create_Label_OUTER_LOOP][S N
S _Duplicate_sum][S N
S _Duplicate_sum][T N
T T _Read_STDIN_as_Integer][T T T _Retrieve_input][S N
S _Duplicate_input][N
T S T N
_If_0_Jump_to_Label_PRINT][S N
S _Duplicate_input][S N
S _Duplicate_input][N
S S S N
_Create_Label_INNER_LOOP][S S S T N
_Push_1][T S S T _Subtract_top_two][S N
S _Duplicate][N
T S S S N
_If_0_Jump_to_Label_RETURN][S N
T _Swap_top_two][S T S S T S N
_Copy_0-based_2nd_input_to_top][T S S N
_Multiply_top_two][S N
T _Swap_top_two][N
S N
S N
_Jump_to_INNER_LOOP][N
S S S S N
_Create_Label_RETURN][S N
N
_Discard_top_0][S N
T _Swap_top_two][S N
N
_Discard_top_input][T S S S _Add_top_two][N
S N
N
_Jump_to_OUTER_LOOP][N
S S T N
_Create_Label_PRINT][S N
N
_Discard_top_0][T N
S T _Print_as_Integer]
Letters S
(space), T
(tab), and N
(new-line) added as highlighting only.
[..._some_action]
added as explanation only.
Since Whitespace can only read input one character/integer at a time, the input must contain a trailing 0
so we'll know when we're done reading inputs.
Try it online (with raw spaces, tabs and new-lines only).
Explanation in pseudo-code:
Integer sum = 0
Start OUTER_LOOP:
Integer input = Read STDIN as integer
If (input == 0):
Stop OUTER_LOOP, and jump to PRINT
Integer product = input
Integer count = input
Start INNER_LOOP:
count = count - 1
If (count == 0):
Stop INNER_LOOP, and jump to RETURN
product = product * input
Go to next iteration of INNER_LOOP
RETURN:
sum = sum + product
Go to next iteration of OUTER_LOOP
PRINT:
Print sum as integer to STDOUT
(implicitly stop the program with an error: No exit defined)
~x=sum(x.^x)
This solution showcases how operations in Julia can be vectorized with a dot. I've redefined a single-character operator, but an anonymous function x->sum(x.^x)
could also be used for the same score.
By the way, sum
can accept a subfunction to be called on each element before summation. For example, if A
is a vector, sum(sqrt.(x))
can be shortened to sum(sqrt,x)
. It's not helpful in this case, since there's no unary definition for ^
, but this method has been useful for most of my solutions involving sum
, often saving bytes over solutions involving count
.
!x=x'x.^.~-x
is a fun alternative at the same length
\$\endgroup\$
$=>[∑map&'x->x^x]
$=>[] ; a function where input is assigned to &
∑ ; sum of...
map&'x-> ; map over input and assign current elt to x
x^x ; x to the x power
Tr[#^#]&
Try it online! Unnamed function taking a list like {4, 6, 7}
as input. The exponentiation operator ^
automatically distributes over arrays of the same length, and Tr
of a one-dimensional list is its sum.
IΣXθθ
Try it online! Link is to verbose version of code.
θ Input array
X Vectorised raised to power
θ Input array
Σ Take the sum
I Cast to string
Implicitly print
Edit: Saved 2 bytes because I forgot that Power
is one of the four (five on ATO) operators that auto-vectorises if both parameters are lists.
7 bytes to take input as a string:
IΣEAXιι
Try it online! Link is to verbose version of code. Explanation: Power
auto-casts strings to integer, so I don't need to write Iι
twice.
*`S
*`S
* Raise to
` its own [4,6,7] => [256, 46656, 823543]
S Sum [256, 46656, 823543] => 870455
sum.map((^)<*>id)
The (^)<*>id
is point-free for \x->x^x
. A list-comprehension solution is the same length.
f l=sum[x^x|x<-l]
sum.map(join(^))
saves one byte.
\$\endgroup\$
Commented
Jul 13 at 19:06
-rz
, s!.*!sed -r 'h;G;:r;s/.\\n./\\n/;x;s/\\n.*//;t;:b;s/.*/\&\\n\&/m;:;t;x;s/^#//;x;tb;G;h;s/\\n(.)/\\1/g;T;s/\\n../\&/;tr'<<<'&'!e
s/\n..//g
This essentially calls a second instance of sed with a snipit of the script I used for this question to calculate the powers, and then concats everything together at the end.
=sort(sum(if(A:A,A:A^A:A)))
Uses sort
as an array enabler, and if()
to weed out blanks. In Google Sheets, the numeric value of a blank is zero, and the self-exponents of a blank column would thus sum up to the number of rows in the column.
{^↙?}ᵐ+
Rare use of ↙
. There is a less elegant version also for 7 bytes: gjz^₎ᵐ+
{ }ᵐ Map for each integer:
^ Raise to the power...
↙? ...of itself
+ Sum
1#.^~
^~
, called with one argument, raises that argument to the power of itself. When that argument is an array the operation is applied to each cell.
1#.
means "from base-1." As it turns out, interpreting a list of integers as the digits of a base-1 number is equivalent to summing them.
This is because #.
in J doesn't care whether the digits it is given are greater than the base itself - it just treats them as any other digit, multiplying them by their place value, and summing the results. In this "base-1", the place value is always 1, so this is equivalent to just summing the array.
Thanks to Conor for showing me this trick, saving a byte over the more trivial +/@:
I had earlier.
1#.^~
, link
\$\endgroup\$
Commented
Jul 13 at 4:21
c**c
instead of Math.pow(c,c)
\$\endgroup\$
Commented
Jul 13 at 22:47
-mx
, 2 bytespU
:Implicit map of each U in the input array
pU :Raise U to the power of U
:Implicit output of sum of resulting array
-m
runs the program on each argument and collects the results; -x
returns the sum of the program's output. pU
implicitly does UpU
which says raise U to the power of U.
\$\endgroup\$
Commented
Jul 13 at 16:54
-3 bytes thanks to ovs
: ^ 1 TUCK +DO OVER * LOOP * ; : s 0 SWAP DUP @ 0 DO DUP I 1+ CELLS + @ DUP ^ ROT + SWAP LOOP DROP ;
No exponentiation in Forth so I first define ^
word and then the s
word to compute the sum.
The idea:
addrTab
0 addrTab
\ enter the loop
0 addrTab addrElt1
0 addrTab Elt1
0 addrTab Elt1 Elt1
0 addrTab Elt1^Elt1
addTab 0+Elt1^Elt1
0+Elt1^Elt1 addrTab
...
0+Elt1^Elt1+...+EltN^EltN addrTab
\ exit the loop
0+Elt1^Elt1+...+EltN^EltN
: ^ 1 TUCK +DO OVER * LOOP * ;
\$\endgroup\$
+DO
can be replaced by DO
, no?
\$\endgroup\$
DO
would break for input 1
, 1 1 DO LOOP
is an infinite loop.
\$\endgroup\$
:sum+~:**
Expansion of J-uby code to standard Ruby:
:sum + ~:** # with spaces
->(a) {:sum.(a, &~:**)} # (F + G).(*args) == F.(*args, &G)
->(a) {:sum.(a, {|x| (~:**).(x)})} # definition of &
->(a) {:sum.(a, {|x| :**.(x, x)})} # (~F).(x) == F.(x,x)
->(a) {a.sum {|x| x ** x}} # :F.(x, y) == x.F(y)
for i;{
let t+=i**i
}
echo $t
use as a function or bash script. takes the array as an arbitrary number of arguments, outputs to stdout.
explanation:
for i;{ # in bash, if the 'in array' part is not provided to 'for elem in array', it implicitly loops over all arguments
let t+=i**i # bash variables are initialized to 0, the rest is simple enough
}
echo $t
s^V
s^V
s # sum of
^V # vectorized power with itself using the (implicit) input-list twice
💎
Created with the help of Luminespire.
-join($args|%{'+1'
"*$_"*$_})|iex
Builds the expression as a string, e.g.
+1*4*4*4*4+1*6*6*6*6*6*6+1*7*7*7*7*7*7*7
Then evaluate it
DoubleStream
as input, it can be just 32 bytes: l->l.map(x->Math.pow(x,x)).sum()
- Try it online.
\$\endgroup\$
Commented
Jul 12 at 7:05
~["L$`^¶$.("|""L$`.+
*$($&$*)_
Try it online! Explanation:
L$`.+
Loop over each input integer.
*$($&$*)_
Write that integer followed by a *
, repeated (implicitly) that many times, then finally followed by a _
. For example, 3
becomes 3*3*3*_
, which is how you would calculate 3*3*3
in Retina.
|""
Join the calculations together, implicitly summing them.
["L$`^¶$.("
Turn the calculation into a command that replaces the input with the result of the calculation converted to decimal. (Retina 1 is clever enough not to actually do the calculation in unary if it knows that it will be converting the result to decimal.)
~`
Evaluate the resulting calculation.
For example, for inputs of 4
, 6
and 7
, the resulting calculation looks like this:
L$`^
$.(4*4*4*4*_6*6*6*6*6*6*_7*7*7*7*7*7*7*_
(The K
command doesn't perform calculations so L$`^
is the easiest way.)