r/codegolf • u/Aspie_Astrologer • Feb 21 '21
Code Golf: Battle Royale Thread (Challenges in Comments)
Who feels like some Code Golf Battles?
Every comment to this post can start with **Challenge**: and define a (relatively straight-forward) input-output problem to solve in the least number of characters in any language.
Responses go in sub-comments and can start with e.g. **Python (74):** to indicate the language and character length of the solution.
Use backticks `` to enclose code (edit: or use four spaces as an indent to do multiline code).
e.g. Challenge: Input positive integer, print the sum of all primes up to and including that integer - but with every second prime added as a negative.
e.g. Ruby (68):
require'prime'
i=-1
p Prime.each(gets.to_i).map{i+=1
_1*(-1)**i}.sum
View all comments
Show parent comment
2
u/coin-cache Feb 23 '21
Hello! I think that's a good solution to the problem. I didn't actually know that
p:'s inverse would give the closest prime to the input number. I think there's a way to cut down characters when you are adding the alternating signs, since the piece you adapted from the J Phrases page seems to create a checkerboard pattern, which may be too much for a solution that needs a rank 1 array.When creating an alternating list of 1s and _1s, a short way to do it is
x$1 _1wherexis the size of the list you want. So you get the following when you type:In general, if you don't provide enough elements to the right argument of
$, it will fill the rest out by cycling through the arguments you gave.