Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

Return to Revisions

5 of 9
added 2320 characters in body
Ilmari Karonen
  • 21k
  • 5
  • 55
  • 101

##Perl (no +/-, no tie-breakers, 41 chars)##

s!!xx!;s!x!$"x<>!eg;print y!!!c;print"\n"

As a bonus, you can make the code sum more than two numbers by adding more xs to the s!!xx!.

Alternatively, here are two 26-char solutions with 3 and 5 tie-breakers respectively

print length$"x<>.$"x<>,$/
print log exp(<>)*exp<>,$/

I'm assuming that the output needs to end with a newline. If this is not required, the last 10 chars from the 41-char solution, and the last 3 chars from the 26-char solutions, can be omitted.


How does the 41-char solution work?

  • s!!xx! is a regexp replacement operator, operating by default on the $_ variable, which replaces the empty string with the string xx. (Usually / is used as the regexp delimiter in Perl, but really almost any character can be used. I chose ! since it's not a tie-breaker.) This is just a fancy way of prepending "xx" to $_ — or, since $_ starts out empty (undefined, actually), it's really a way to write $_ = "xx" without using the equals sign (and with one character less, too).

  • `s!x!$"x!eg` is another regexp replacement, this time replacing each `x` in `$_` with the value of the expression `$" x `. (The `g` switch specifies global replacement, `e` specifies that the replacement is to be evaluated as Perl code instead of being used as a literal string.) `$"` is a [special variable](http://perldoc.perl.org/perlvar.html#$LIST_SEPARATOR) whose default value happens to be a single space; using it instead of `" "` saves one char. (Any other variable known to have a one-character value, such as `$&` or `$/`, would work equally well here, except that using `$/` would cost me a tie-breaker.)

    The `` [line input operator](http://perldoc.perl.org/perlop.html#I%2fO-Operators), in scalar context, reads one line from standard input and returns it. The `x` before it is the Perl [string repetition operator](http://perldoc.perl.org/perlop.html#Multiplicative-Operators), and is really the core of this solution: it returns its left operand (a single space character) repeated the number of times given by its right operand (the line we just read as input).

  • y!!!c is just an obscure way to (ab)use the transliteration operator to count the characters in a string ($_ by default, again). I could've just written print length, but the obfuscated version is one character shorter. :)

  • Finally, print "\n" just prints a newline; there's nothing mysterious going on here. Usually, I would've golfed that down to print $/, as I did in the 26-char solutions, but since / is a tie-breaker, the ungolfed version actually scores better for this challenge.

Ilmari Karonen
  • 21k
  • 5
  • 55
  • 101

AltStyle によって変換されたページ (->オリジナル) /