68
\$\begingroup\$

Input: Two integers. Preferably decimal integers, but other forms of numbers can be used. These can be given to the code in standard input, as arguments to the program or function, or as a list.

Output: Their sum. Use the same format for output integers as input integers. For example, the input 5 16 would lead to the output 21.

Restrictions: No standard loopholes please. This is , answer in lowest amount of bytes wins.

Notes: This should be fairly trivial, however I'm interested to see how it can be implemented. The answer can be a complete program or a function, but please identify which one it is.

Test cases:

1 2 -> 3
14 15 -> 29
7 9 -> 16
-1 8 -> 7
8 -9 -> -1
-8 -9 -> -17

Or as CSV:

a,b,c
1,2,3
14,15,29
7,9,16
-1,8,7
8,-9,-1
-8,-9,-17

Leaderboard

var QUESTION_ID=84260,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

\$\endgroup\$
3
  • 31
    \$\begingroup\$ This is quite trivial, but not really simpler than, e.g., the Hello World catalog. Given that the ability to add integers is one of our two requirements for programming languages, I'd say it's worthwhile to have if properly specified. \$\endgroup\$
    – Dennis
    Commented Jul 2, 2016 at 0:48
  • 2
    \$\begingroup\$ Can the answer take input with preceding zeros as default? e.g. 5 16 is inputted as 005 016 \$\endgroup\$
    – FinW
    Commented Dec 4, 2016 at 11:56
  • 1
    \$\begingroup\$ @FinW Sure. As long as they don't get interpreted as octal. \$\endgroup\$
    – anna328p
    Commented Dec 4, 2016 at 20:47

237 Answers 237

1
2 3 4 5
8
81
\$\begingroup\$

Minecraft 1.10, 221 characters (non-competing)

See, this is what we have to deal with when we make Minecraft maps.

Aside: There's no way to take a string input in Minecraft, so I'm cheating a bit by making you input the numbers into the program itself. (It's somewhat justifiable because quite a few maps, like Lorgon111's Minecraft Bingo, require you to copy and paste commands into chat in order to input a number.)

Thank you abrightmoore for the Block Labels MCEdit filter.

a

scoreboard objectives add a dummy
scoreboard players set m a 6
scoreboard players set n a 8
scoreboard players operation r a += m a
scoreboard players operation r a += n a
tellraw @a {"score":{"name":"r","objective":"a"}}

Non-competing due to difficulties in input, and I have no idea how to count bytes in this thing (the blytes system is flawed for command blocks).

\$\endgroup\$
10
  • 6
    \$\begingroup\$ This is by far the best one. Amazing. \$\endgroup\$
    – anna328p
    Commented Jul 3, 2016 at 1:13
  • 3
    \$\begingroup\$ Yeah, there's zero text input in MC, besides "please copy and paste this command". A number keypad is possible with a /tellraw, but will be barely usable all golfed, not to mention 500kb thanks to /tellraw's obscenely strict syntax. I guess an alternative would be for it to count something in-world, like pigs+cows, or red wool+blue wool. \$\endgroup\$
    – quat
    Commented Jul 4, 2016 at 5:51
  • 1
    \$\begingroup\$ @quat As we're usually using hopper to count things in minecraft, I guesse it would be the way to go. An other way to deal with this would be doable in pure redstone too by using levers. As we don't have any restriction, and the bit is the biggest natural value reachable in minecraft, that would result in simply adding two bits with an output of two bits (possibility : 0,1,2. An other solution would be to take in 2 bytes and output on 9 wire, but would be much less golfy. \$\endgroup\$
    – Katenkyo
    Commented Jul 4, 2016 at 7:08
  • 2
    \$\begingroup\$ There is now an MC Standard for bytecount. \$\endgroup\$
    – mbomb007
    Commented Oct 10, 2016 at 20:23
  • 1
    \$\begingroup\$ Umm, are y'all aware of /trigger? \$\endgroup\$
    – rydwolf
    Commented Aug 26, 2018 at 14:03
56
\$\begingroup\$

Jelly, 1 byte

+

Try it online!

Also works in 05AB1E, Actually, APL, BQN, Brachylog, Braingolf, Chocolate, ,,, (Commata), dc, Deorst, Factor, Fig**, Forth, Halfwit*, HBL*, Implicit, J, Julia, K, kdb+, Keg, Ly, MathGolf, MATL, Pyke, Q, Racket, Scheme, Swift, Thunno**, Thunno 2, tinylisp 2, Uiua, and Vyxal.

* Language uses a half-byte code page, and therefore + counts as 0.5 bytes.

** In Fig and Thunno, this is \$\log_{256}(96)\approx\$ 0.823 bytes.

\$\endgroup\$
3
  • 4
    \$\begingroup\$ Pyth as well @Zacharý \$\endgroup\$
    – Stan Strum
    Commented Oct 9, 2017 at 0:18
  • 1
    \$\begingroup\$ @StanStrum This does not work in Pyth, it adds the first input to itself in Pyth. \$\endgroup\$
    – isaacg
    Commented Feb 1, 2020 at 0:18
  • 2
    \$\begingroup\$ @isaacg Nice to see the Pyth lord pop up in my inbox again. My understanding of Pyth was always a little rusty, thank you. \$\endgroup\$
    – Stan Strum
    Commented Feb 1, 2020 at 4:05
46
\$\begingroup\$

Binary lambda calculus, 4.125 bytes

Input and output as Church numerals.

00000000 01011111 01100101 11101101 0

In lambda calculus, it is λm. λn. λf. λx. m f (n f x).

De Bruijn index: λ λ λ λ 4 2 (3 2 1)


Lambda calculus is a concise way of describing a mapping (function).

For example, this task can be written as λx. λy. x + y

The thing to note is, that this is not a lambda (function) which takes two arguments. This is actually a nested lambda. However, it behaves like a lambda which takes two arguments, so it can be informally described as such. Every lambda formally only takes one argument.

For example, if we apply this lambda to 3 and 4:

x. λy. x + y) 3 4 ≡ (λy. 3 + y) 4 ≡ 3 + 4 = 7

So, the first lambda actually returns another lambda.


Church numerals is a way of doing away with the extra signs, leaving with only lambda symbols and variables.

Each number in the Church system is actually a lambda that specifies how many times the function is applied to an item.

Let the function be f and the item be x.

So, the number 1 would correspond to λf. λx. f x, which means apply f to x exactly once.

The number 3, for example, would be λf. λx. f (f (f x)), which means apply f to x exactly three times.


Therefore, to add two Church numerals (say, m and n) together, it is the same as applying f to x, m + n times.

We can observe that this is the same as first applying f to x, n times, and then applying f to the resulting item m times.

For example, 2 would mean f(f(x)) and 3 would mean f(f(f(x))), so 2 + 3 would be f(f(f(f(f(x))))).

To apply f to x, n times, we have n f x.

You can view m and n as functions taking two arguments, informally.

Then, we apply f again to this resulting item, m times: m f (n f x).

Then, we add back the boilerplate to obtain λm. λn. λf. λx. m f (n f x).


Now, we have to convert it to De Bruijn index.

Firstly, we count the "relative distance" between each variable to the lambda declaration. For example, the m would have a distance of 4, because it is declared 4 lambdas "ago". Similarly, the n would have a distance of 3, the f would have a distance of 2, and the x would have a distance of 1.

So, we write it as this intermediate form: λm. λn. λf. λx. 4 2 (3 2 1)

Then, we remove the variable declarations, leaving us with: λ λ λ λ 4 2 (3 2 1)


Now, we convert it to binary lambda calculus.

The rules are:

  • λ becomes 00.
  • m n (grouping) becomes 01 m n.
  • numbers i becomes 1 i times + 0, for example 4 becomes 11110.

λ λ λ λ 4 2 (3 2 1)

≡ λ λ λ λ 11110 110 (1110 110 10)

≡ λ λ λ λ 11110 110 0101 111011010

≡ λ λ λ λ 0101 111101100101111011010

00 00 00 00 0101 111101100101 111011010

000000000101111101100101111011010

\$\endgroup\$
5
  • 22
    \$\begingroup\$ I would like to see the 4.125 byte source file that you pass to the interpreter/compiler. \$\endgroup\$ Commented Jul 2, 2016 at 6:41
  • 8
    \$\begingroup\$ @MartinEnder Say that to every answer here. \$\endgroup\$
    – Leaky Nun
    Commented Jul 2, 2016 at 7:09
  • 5
    \$\begingroup\$ I would like to see a 0.875 byte solution please. \$\endgroup\$
    – Mr Lister
    Commented Jul 3, 2016 at 9:42
  • 5
    \$\begingroup\$ By meta consensus, unless you can store the program as a file with a fractional amount of bytes, you have to round up. \$\endgroup\$
    – Pavel
    Commented Jan 24, 2017 at 16:11
  • \$\begingroup\$ @Pavel That is not the consensus. This is the consensus. \$\endgroup\$ Commented Sep 4, 2023 at 15:59
27
\$\begingroup\$

Stack Cats, 8 + 4 = 12 bytes

]_:]_!<X

Run with the -mn flags. Try it online!

Golfing in Stack Cats is highly counterintuitive, so this program above was found with a few days of brute forcing. For comparison, a more intuitive, human-written solution using the *(...)> template is two bytes longer

*(>-_:[:)>

with the -ln flags instead (see the bottom of this post for an explanation).

Explanation

Here's a primer on Stack Cats:

  • Stack Cats is a reversible esoteric language where the mirror of a snippet undoes the effect of the original snippet. Programs must also be mirror images of itself — necessarily, this means that even-length programs are either no-ops or infinite loops, and all non-trivial terminating programs are of odd length (and are essentially a conjugation of the central operator).
  • Since half the program is always implied, one half can be left out with the -m or -l flag. Here the -m flag is used, so the half program above actually expands to ]_:]_!<X>!_[:_[.
  • As its name suggests, Stack Cats is stack-based, with the stacks being bottomless with zeroes (i.e. operations on an otherwise empty stack return 0). Stack Cats actually uses a tape of stacks, e.g. < and > move one stack left and one stack right respectively.
  • Zeroes at the bottom of the stack are swallowed/removed.
  • All input is pushed to an initial input stack, with the first input at the top and an extra -1 below the last input. Output is done at the end, using the contents of the current stack (with an optional -1 at the bottom being ignored). -n denotes numeric I/O.

And here's a trace of the expanded full program, ]_:]_!<X>!_[:_[:

    Initial state (* denotes current stack):
      ... [] [-1 b a]* [] [] ...
]   Move one stack right, taking the top element with you
      ... [] [-1 b] [a]* [] ...
_   Reversible subtraction, performing [x y] -> [x x-y] (uses an implicit zero here)
      ... [] [-1 b] [-a]* [] ...
:   Swap top two
      ... [] [-1 b] [-a 0]* [] ...
]   Move one stack right, taking the top element with you
      ... [] [-1 b] [-a] []* ...
_   Reversible subtraction (0-0, so no-op here)
!   Bit flip top element, x -> -x-1
      ... [] [-1 b] [-a] [-1]* ...
<   Move one stack left
      ... [] [-1 b] [-a]* [-1] ...
X   Swap the stack to the left and right
      ... [] [-1] [-a]* [-1 b] ...
>   Move one stack right
      ... [] [-1] [-a] [-1 b]* ...
!   Bit flip
      ... [] [-1] [-a] [-1 -b-1]* ...
_   Reversible subtraction
      ... [] [-1] [-a] [-1 b]* ...
[   Move one stack left, taking the top element with you
      ... [] [-1] [-a b]* [-1] ...
:   Swap top two
      ... [] [-1] [b -a]* [-1] ...
_   Reversible subtraction
      ... [] [-1] [b a+b]* [-1] ...
[   Move one stack left, taking the top element with you
      ... [] [-1 a+b]* [b] [-1] ...

a+b is then outputted, with the base -1 ignored. Note that the trickiest part about this solution is that the output stack must have a -1 at the bottom, otherwise an output stack of just [-1] would ignore the base -1, and an output stack of [0] would cause the base zero to be swallowed (but an output stack of [2], for example, would output 2 just fine).


Just for fun, here's the full list of related solutions of the same length found (list might not be complete):

]_:]^!<X
]_:]_!<X
]_:]!^<X
]_:!]^<X
[_:[^!>X
[_:[_!>X
[_:[!^>X
[_:![^>X

The *(>-_:[:)> solution is longer, but is more intuitive to write since it uses the *(...)> template. This template expands to <(...)*(...)> when used with the -l flag, which means:

<       Move one stack left
(...)   Loop - enter if the top is positive and exit when the top is next positive again
        Since the stack to the left is initially empty, this is a no-op (top is 0)
*       XOR with 1 - top of stack is now 1
(...)   Another loop, this time actually run
>       Move one stack right

As such, the *(...)> template means that the first loop is skipped but the second is executed. This allows more straightforward programming to take place, since we don't need to worry about the effects of the loop in the other half of the program.

In this case, the inside of the loop is:

>       Move one stack right, to the input stack
-       Negate top, [-1 b a] -> [-1 b -a]
_       Reversible subtraction, [-1 b -a] -> [-1 b a+b]
:       Swap top two, [-1 b a+b] -> [-1 a+b b]
[       Move one stack left, taking top of stack with you (removing the top b)
:       Swap top two, putting the 1 on this stack on top again

The final > in the template then moves us back to the input stack, where a+b is outputted.

\$\endgroup\$
0
25
\$\begingroup\$

Dominoes, 38,000 bytes or 37 tiles

This is created in Tabletop Simulator. Here is a video and here is the file. It is a standard half-adder, composed of an and gate for the 2^1 place value and an xor gate for the 2^0 place value.

enter image description here

Details

  • I/O
    • Start - This is included for clarity (not counted towards total) and is what 'calls' or 'executes' the function. Should be 'pressed' after input is given [Yellow].
    • Input A - This is included for clarity (not counted towards total) and is 'pressed' to indicated a 1 and unpressed for 0 [Green].
    • Input B - This is included for clarity (not counted towards total) and is 'pressed' to indicated a 1 and unpressed for 0 [Blue].
    • Output - This is counted towards total. These dominoes declare the sum. The left is 2^1 and the right is 2^0 [Black].
  • Pressing
    • To give input or start the chain, spawn the metal marble
    • Set the lift strength to 100%
    • Lift the marble above the desired domino
    • Drop the marble
\$\endgroup\$
4
  • 1
    \$\begingroup\$ ...how? \$\endgroup\$
    – anna328p
    Commented Mar 14, 2017 at 5:13
  • 5
    \$\begingroup\$ @Mendeleev Once you have all the binary logic gates, everything else falls into place xD. \$\endgroup\$ Commented Mar 14, 2017 at 12:13
  • \$\begingroup\$ why is that 38,000 bytes? seems like a lot to store 37 dominoes. \$\endgroup\$ Commented Sep 4, 2023 at 16:00
  • \$\begingroup\$ It is the size of the Tabletop Simulator, Steam upload. There was a metadiscussion on how to measure stuff in the real world. The consensus was that it needs to be digitized so that it is repeatable. \$\endgroup\$ Commented Sep 6, 2023 at 21:57
24
\$\begingroup\$

Common Lisp, 15 bytes

(+(read)(read))
\$\endgroup\$
4
  • 2
    \$\begingroup\$ Welcome to Programming Puzzles & Code Golf! \$\endgroup\$
    – Dennis
    Commented Jul 3, 2016 at 1:06
  • \$\begingroup\$ I'm relatively unfamiliar with CLisp, but would it be possible to remove the spaces? (+(read)(read)) \$\endgroup\$
    – user45941
    Commented Jul 3, 2016 at 1:39
  • \$\begingroup\$ @Mego You're right, it is possible. I didn't know that because I'm also new to Common Lisp, thanks for the info! I edited the source \$\endgroup\$ Commented Jul 3, 2016 at 2:57
  • 3
    \$\begingroup\$ I guess we both learned something here! Welcome aboard to PPCG! \$\endgroup\$
    – user45941
    Commented Jul 3, 2016 at 3:20
21
\$\begingroup\$

Brain-flak, 6 bytes

({}{})

Try it online!

Brain-flak is a really interesting language with two major restrictions on it.

  1. The only valid characters are brackets, i.e. any of these characters:

     (){}[]<>
    
  2. Every single set of brackets must be entirely matched, otherwise the program is invalid.

A set of brackets with nothing between them is called a "nilad". A nilad creates a certain numerical value, and all of these nilads next to each other are added up. A set of brackets with something between them is called a "monad". A monad is a function that takes an numerical argument. So the brackets inside a monad are evaluated, and that is the argument to the monad. Here is a more concrete example.

The () nilad equals 1. So the following brain-flak code:

()()()

Is evaluated to 3. The () monad pushes the value inside of it on the global stack. So the following

(()()())

pushes a 3. The {} nilad pops the value on top of the stack. Since consecutive nilads are always added, a string of {} sums all of the top elements on the stack. So my code is essentially:

push(pop() + pop())
\$\endgroup\$
15
\$\begingroup\$

Minecraft 1.10.x, 924 512 bytes

Thanks to @quat for reducing the blytecount by 48 points and the bytecount by 412.

Alright, so, I took some of the ideas from this answer and made a version of my own, except that this one is capable of accepting non-negative input. A version may be found here in structure block format.

group

(new version looks kinda boring tbh)

Similar commands as the other answer:

scoreboard objectives add a dummy
execute @e[type=Pig] ~ ~ ~ scoreboard players add m a 1
execute @e[type=Cow] ~ ~ ~ scoreboard players add n a 1
scoreboard players operation n a += m a
tellraw @a {"score":{"name":"n","objective":"a"}}

To input numbers, spawn in a number of cows and pigs. Cows will represent value "n" and pigs will represent value "m". The command block system will progressively kill the cows and pigs and assign values as necessary.

This answer assumes that you are in a world with no naturally occurring cows or pigs and that the values stored in "n" and "m" are cleared on each run.

\$\endgroup\$
7
  • \$\begingroup\$ For negative integers, you could use 2 other kinds of animals as "neganimals" - 5 horses could represent -5, for example. \$\endgroup\$
    – user45941
    Commented Jul 6, 2016 at 9:32
  • \$\begingroup\$ @Mego Then it would be four inputs, not 2. \$\endgroup\$ Commented Jul 6, 2016 at 22:52
  • \$\begingroup\$ It would still be two inputs - it's the equivalent of using two's complement for negative numbers. Slightly different format, but still one input. At least, that's my two cents. \$\endgroup\$
    – user45941
    Commented Jul 7, 2016 at 0:07
  • \$\begingroup\$ Might be able to save on blocks by using execute @e[type=Pig] ~ ~ ~ scoreboard players add m a 1, so you don't need any form of clock. \$\endgroup\$
    – quat
    Commented Jul 7, 2016 at 20:57
  • \$\begingroup\$ @quat Ooh. Nice. \$\endgroup\$ Commented Jul 7, 2016 at 20:58
13
\$\begingroup\$

Retina, 42 bytes

\d+
$*
T`1p`-_` |-1+
+`.\b.

^(-)?.*
$1$.&

Try it online!

Explanation

Adding numbers in unary is the easiest thing in the world, but once you introduce negative numbers, things get fiddly...

\d+
$*

We start by converting the numbers to unary. This is done by matching each number with \d+ and replacing it with $*. This is a Retina-specific substitution feature. The full syntax is count$*character and inserts count copies of character. Both of those can be omitted where count defaults to $& (i.e. the match itself) and character defaults to 1. So for each input n we get n ones, and we still have potential minus signs in there, as well as the space separator. E.g. input 8 -5 gives:

11111111 -11111

Now in order to deal with negative numbers it's easiest to use a separate -1 digit. We'll use - for that purpose.

T`1p`-_` |-1+

This stage does two things. It gets rid of the space, the leading minus signs, and turns the 1s after a minus sign into - themselves. This is done by matching |-1+ (i.e. either a space or a negative number) and performing a transliteration on it. The transliteration goes from 1p to -_, but here, p expands to all printable ASCII characters and _ means delete. So 1s in those matches get turned into -s and minuses and spaces get removed. Our example now looks like this:

11111111-----
+`.\b.

This stage handles the case where there's one positive and one negative number in the input. If so, there will be 1s and -s in the string and we want them to cancel. This is done by matching two characters with a word-boundary between them (since 1s is considered a word character and - isn't), and replacing the match with nothing. The + instructs Retina to do this repeatedly until the string stops changing.

Now we're left with only 1s or only -s.

^(-)?.*
$1$.&

To convert this back to decimal, we match the entire input, but if possible we capture a - into group 1. We write back group 1 (to prepend a - to negative numbers) and then we write back the length of the match with $.& (also a Retina-specific substitution feature).

\$\endgroup\$
6
  • 2
    \$\begingroup\$ This is very clever. \$\endgroup\$
    – user45941
    Commented Jul 4, 2016 at 2:14
  • \$\begingroup\$ Now if only there were an easy way to implement range in Retina. I've tried a few times, but the negatives are a pain. \$\endgroup\$
    – mbomb007
    Commented Jul 6, 2016 at 18:33
  • \$\begingroup\$ It takes over 40 bytes to add two numbers in this language?? \$\endgroup\$
    – anna328p
    Commented Sep 24, 2016 at 2:10
  • 3
    \$\begingroup\$ @DmitryKudriavtsev well, Retina has no concept of numbers... \$\endgroup\$ Commented Sep 24, 2016 at 7:42
  • \$\begingroup\$ @DmitryKudriavtsev, and that's just integers.... \$\endgroup\$
    – msh210
    Commented Oct 31, 2016 at 9:15
13
\$\begingroup\$

Geometry Dash - 15 objects

Finally done.
15 objects aren't much, but it was still a nightmare to do this (especially because of the negative numbers).

enter image description here

Because I would have to insert 15 images here for how to reproduce this, I just uploaded the level. The level ID is 5216804. The description tells you how to run it and you can copy it since it is copyable.

Explanation:

The top-left trigger (Instant Count 2) checked if the first addend was 0. If it was, it then checked if the second addend was positive or negative. If it was positive, it transferred the value from the second addend to the sum (BF-style, using loops) and if it was negative, it would do the same thing.

The reason why we need to check if the second addend is positive or negative is that we would need to subtract one from the second addend and add one to the sum or add one to the second addend and subtract one from the sum respectively.

If the first addend is not zero, it tests whether it is positive or negative using the process above. After one iteration in the while loop, it tests to see if the first addend is zero and if it is, it does the process described at the beginning of the explanation.

Since Geometry Dash is remarkably similar to BF, you could make a BF solution out of this.

\$\endgroup\$
13
\$\begingroup\$

APOL, 6 bytes

+(i i)

I AM BOT FEED ME BUTTER

\$\endgroup\$
5
  • \$\begingroup\$ Good first answer (lol). Hope you will stay here. \$\endgroup\$
    – math scat
    Commented Jan 9, 2022 at 19:13
  • \$\begingroup\$ Sends you to the Bakery :p \$\endgroup\$
    – rydwolf
    Commented Jan 9, 2022 at 19:54
  • \$\begingroup\$ no butter just memes. Is that okay? \$\endgroup\$
    – lyxal
    Commented May 5, 2022 at 1:17
  • \$\begingroup\$ @lyxal YOU. ME. BUTTER. NOW. \$\endgroup\$
    – Myōga
    Commented May 5, 2022 at 12:25
  • \$\begingroup\$ @GingerBot no butter for you! \$\endgroup\$ Commented May 13, 2023 at 12:09
12
\$\begingroup\$

Mathematica, 4 2 bytes

Tr

Crossed out 4 is still regular 4... Tr applied to a one-dimensional list takes the sum of said list's elements.

\$\endgroup\$
11
\$\begingroup\$

JavaScript (ES6), 9 bytes

a=>b=>a+b
\$\endgroup\$
3
  • \$\begingroup\$ I don't think a nested function counts as a two-input function in javascript \$\endgroup\$ Commented Jul 5, 2016 at 16:34
  • 7
    \$\begingroup\$ @proudhaskeller yes it does \$\endgroup\$ Commented Jul 5, 2016 at 16:45
  • 2
    \$\begingroup\$ This one works in C# also. \$\endgroup\$
    – Grax32
    Commented Oct 12, 2016 at 17:59
11
\$\begingroup\$

Haskell, 3 bytes

(+)

The parentheses are here because it needs to be an prefix function. This is the same as taking a section of the + function, but no arguments are applied. It also works on a wide range of types, such as properly implemented Vectors, Matricies, Complex numbers, Floats, Doubles, Rationals, and of course Integers.

Because this is Haskell, here is how to do it on the type-level. This will be done at compile time instead of run time:

-- This *type* represents Zero
data Zero
-- This *type* represents any other number by saying what number it is a successor to.
-- For example: One is (Succ Zero) and Two is (Succ (Succ Zero))
data Succ a

-- a + b = c, if you have a and b, you can find c, and if you have a and c you can find b (This gives subtraction automatically!)
class Add a b c | a b -> c, a c -> b

-- 0 + n = n 
instance Add Zero n n
-- If (a + b = c) then ((a + 1) + b = (c + 1))
instance (Add a b c) => Add (Succ a) b (Succ c)

Code adapted from Haskell Wiki

\$\endgroup\$
1
  • 3
    \$\begingroup\$ fun fact: this is a polyglot with Cheddar :D \$\endgroup\$
    – Downgoat
    Commented Jul 17, 2016 at 22:15
10
\$\begingroup\$

Shakespeare Programming Language, 155 152 bytes

.
Ajax,.
Ford,.
Act I:.
Scene I:.
[Enter Ajax and Ford]
Ajax:
Listen to thy heart
Ford:
Listen to THY heart!You is sum you and I.Open thy heart
[Exeunt]

Ungolfed:

Summing Two Numbers in Verona.

Romeo, a numerical man.
Juliet, his lover and numerical counterpart.

Act I: In which Italian addition is performed.

Scene I: In which our two young lovers have a short chat.

[Enter Romeo and Juliet]

Romeo:
  Listen to thy heart.

Juliet:
  Listen to THY heart! Thou art the sum of thyself and I. Open thy heart.

[Exeunt]

I'm using drsam94's SPL compiler to compile this. To test:

$ python splc.py sum.spl > sum.c
$ gcc sum.c -o sum.exe
$ echo -e "5\n16" | ./sum
21
\$\endgroup\$
1
  • \$\begingroup\$ Just warning you, this is not valid SPL. “You is sum you and I.” is not valid in the actual compiler. I’m not sure where you got the compiler you’re using. In the actual compiler you can save some bytes with “Listen tothy.” and “Open heart” \$\endgroup\$ Commented Jan 7, 2020 at 14:45
9
\$\begingroup\$

dc, 2 bytes

+f

Adds top two items on stack (previously taken from stdin), then dumps the stack's contents to stdout.

EDIT: Upon further consideration, it seems there are several ways this might be implemented, depending on the desired I/O behaviour.

+        # adds top two items and pushes on stack
+n       # adds top two and prints it, no newline, popping it from stack
+dn      # ditto, except leaves result on stack
??+      # takes two inputs from stdin before adding, leaving sum on stack

I suppose the most complete form for the sum would be this:

??+p     # takes two inputs, adds, 'peeks'
         #  (prints top value with newline and leaves result on stack)

Wait! Two numbers can be taken on the same line, separated by a space! This gives us:

?+p
\$\endgroup\$
3
  • \$\begingroup\$ I can't see how to use the first example +f , dc -e "?+p" works ok here. \$\endgroup\$
    – Jasen
    Commented Jan 9, 2017 at 21:38
  • 1
    \$\begingroup\$ @Jasen The +f version works if you've already put (exactly two) numbers on the stack. I didn't really know whether dc's I/O is supposed to be std(in|out) or the stack. In retrospect, that was the least sensible option to put at the top of the post. :/ \$\endgroup\$
    – juh
    Commented Jan 10, 2017 at 6:12
  • \$\begingroup\$ the rules say stack is OK so far as I can tell, \$\endgroup\$
    – Jasen
    Commented Jan 10, 2017 at 7:04
9
\$\begingroup\$

Plumber, 244 176 bytes

  []  []      []
      ][=][]
  []=][][=][
[]=]===]]
][]][=[=]]    =]]
[]][   ][===[=[]
 ]][]=][[[=]=]][][
  []]=]=]=]=[]
  ][]=[]][
  []]=][=][]
= =]=]][[=[==
][=]=]=]=]===][=

Old Design (244 bytes)

  []                []
            [][=[]
 [[=[][]  [][]  ][]][=
][[]  ][[=]]]][]=[[]
[]===][]  ][===][]
][][  []    ][  ]     [][]
      [     ][]=][[[===][[
][]]]=][[]=[=]=]=]]==]=]][
  ][=]=]]==]=][]  ][
    [][=][=[[][[=]][
   ==]=]][[=[= =

I thought I had a good solution for a while...except it didn't work with 0 or 1 as the first input. This program consists of three parts: incrementer, decrementer, and outputter.

The decrementer is on the left, and holds the first value. It is incremented, since a 0 would cause an infinite loop (as the program tries to decrement to 0 and gets a negative value). It will decrement the stored value at execution, and send a packet to the incrementer.

The incrementer is on the right, and stores the second input. When the decrementer sends a packet, it increments its stored value, and sends a packet back to the decrementer.

Whenever the decrementer sends the packet to the incrementer, it is checked by the outputter. If the packet is 0, execution stops and the value of the incrementer is read and outputted. It uses a NOT gate, one of the most complicated parts of the program.

Older design (doesn't work with some inputs), 233 bytes

          []          []
          [][]  [][]  =][]
    []=][]=][[=]][
      [][===][  [][===[]
[][]   [        []    ][][
] [===][=]][     ]
][[=[=[=[=[=]=[]][=[[[][
    ][[=[=[=[==[[=[=][
          []]=][=][]
        = =]=]][[=[== 

The new one is flipped to save bytes, and it's really confusing me. This design is the one I worked with for a week or so when designing the interpreter.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ I pity any plumber who has to work on the plumbing in your home. \$\endgroup\$
    – user
    Commented Jul 4, 2021 at 14:48
8
\$\begingroup\$

Brachylog, 2 bytes

+.

Expects a list with the two numbers as input

Alternatively, if you want the answer to STDOUT:

+w
\$\endgroup\$
0
8
\$\begingroup\$

Python, 11 3 bytes

sum

int.__add__

A simple special operator.

\$\endgroup\$
0
7
\$\begingroup\$

Cheddar, 3 bytes

(+)

This is a cool feature of Cheddar called "functionized operators". Credit for this idea goes to @CᴏɴᴏʀO'Bʀɪᴇɴ.

Here are more examples of functionized operators:

(+)(1,2) // 3
(/)(6,2) // 3
(-)(5)   // -5
\$\endgroup\$
7
\$\begingroup\$

C, 35 bytes

s(x,y){return y?s(x^y,(x&y)<<1):x;}

What I've done here is defined addition without the use of boolean or arithmetic operators. This recursively makes x the sum bits by 'xor', and y the carry bits by 'and' until there is no carry. Here's the ungolfed version:

int sum(int x,int y){
    if(y==0){
        //anything plus 0 is itself
        return x;
    }
    //if it makes you happier imagine there's an else here
    int sumBits=x^y;
    int carryBits=(x&y)<<1;
    return sum(sumBits,carryBits);
}
\$\endgroup\$
5
  • \$\begingroup\$ Why don't you just add directly? \$\endgroup\$ Commented Mar 19, 2017 at 19:51
  • 3
    \$\begingroup\$ I found that to be boring, the fully golfed version is trivial. \$\endgroup\$
    – Bijan
    Commented Mar 19, 2017 at 21:56
  • 1
    \$\begingroup\$ "All answers should show some effort towards reaching a better score. For instance, answers to code golf challenges should try to be as short as possible (within the constraints of the chosen language)." (from codegolf.meta.stackexchange.com/a/7073/61384) \$\endgroup\$ Commented Mar 20, 2017 at 2:12
  • 4
    \$\begingroup\$ Obviously I thought of just adding the numbers, and I did put effort into making it shorter, only under alternate restraints. I think since this is an unconventional question, it deserves an unconventional answer. Following that rule word for word, there would be no reason to ever put up an answer if someone has already put up a shorter one. If you put up your 20 byte python solution and someone already has a 4 byte version up then you're proving that you don't know how to copy and paste. People put up 20 byte solutions, because we value originality. \$\endgroup\$
    – Bijan
    Commented Mar 20, 2017 at 3:40
  • 2
    \$\begingroup\$ It is implied that it is competitive in the language you are choosing. However, having read up on meta, it seems that I cannot claim that your answer is invalid ("An answer may implement any algorithm, even if golfier ones exist"), so I guess I'll drop it. \$\endgroup\$ Commented Mar 20, 2017 at 5:00
6
\$\begingroup\$

MATL, 1 byte

s

Accepts an array of two integers as input and sums them. While the simple program of + also works, that has already been shown for other languages.

Try it Online

\$\endgroup\$
6
\$\begingroup\$

PHP, 20 bytes

Surprisingly short this time:

<?=array_sum($argv);

Runs from command line, like:

$ php sum.php 1 2
\$\endgroup\$
7
  • \$\begingroup\$ Your script also accepts php sum.php 1 2 3 4 5 6 so I'm not 100% sure if that's ok. \$\endgroup\$
    – Paper
    Commented Oct 6, 2016 at 16:43
  • \$\begingroup\$ @timmyRS The submission should work for a specific input format – two integers. I don't think it should handle other inputs, too. \$\endgroup\$ Commented Oct 6, 2016 at 17:02
  • \$\begingroup\$ What if the source file name starts with a digit? :) \$\endgroup\$ Commented Oct 12, 2016 at 17:57
  • \$\begingroup\$ @AlexHowansky Psssssssst – don't tell anybody. ;) This is the quirk, when running from a file. You can still execute it using the -r flag – then it's not a problem anymore. \$\endgroup\$ Commented Oct 12, 2016 at 17:59
  • \$\begingroup\$ it works only for some particular filenames, but 1.php will miss the answer. \$\endgroup\$
    – user111777
    Commented Apr 1, 2022 at 22:06
6
\$\begingroup\$

Fuzzy Octo Guacamole, 1 byte

a

A function that takes inputs from the top of the stack and outputs by pushing to the stack.

Example running in the REPL:

>>> 8 9 :
[8,9]
>>> a :
17
\$\endgroup\$
6
\$\begingroup\$

x86_32 machine code, 2 bytes

08048540 <add7>:
 8048540:   01 c8                   add    %ecx,%eax

Assuming the two values are already in the ecx and eax registers, performing the add instruction will add the values of the two registers and store the result in the destination register.

You can see the full program written in C and inline assembly here. Writing the wrapper in C makes it easier to provide inputs and do testing, but the actual add function can be reduced down to these two bytes.

\$\endgroup\$
8
  • 3
    \$\begingroup\$ This isn't a function, just a snippet. You need a ret instruction as well (one byte). And that's assuming a custom calling convention where eax is used as an arg-passing register. (The Irvine32 asm teaching library does that, but no standard calling conventions for x86-32 or x86-64 do that, unlike on ARM where the return-value register r0 is also the first arg-passing register.) Custom calling conventions are fine in asm functions though, so you don't need to change it to 3 byte lea (%ecx, %edx), %eax + 1 byte ret for Microsoft __fastcall or gcc -mregparm. \$\endgroup\$ Commented Dec 17, 2017 at 19:20
  • 1
    \$\begingroup\$ It's an interesting challenge for a stack-args calling convention, though. pop is only 1 byte, but esp-relative addressing modes need a SIB byte. So a caller-pops calling convention might pop %ecx (the return address), pop %eax / pop %edx / add %edx, %eax (2 bytes) / jmp *%ecx (2 bytes) = 7 bytes total. vs. mov 4(%esp), %eax (4B) / add 8(%esp), %eax (4B) / ret = 9 bytes, or 11 bytes for a caller-pops version of that using ret imm16, if I did that right. It's an extra 1 byte for the SIB with ESP as a base, and an extra 1 byte for the disp8 in each insn. \$\endgroup\$ Commented Dec 17, 2017 at 19:26
  • \$\begingroup\$ @PeterCordes late reply since I haven't been on this site in years, but per the rules which you have even commented on, assembly submissions may take input and output from registers. \$\endgroup\$
    – davey
    Commented Dec 18, 2021 at 2:26
  • \$\begingroup\$ The meta Q&A you linked says an answer might consist of a subroutine. An x86 subroutine ends with a ret (or a jmp or something). Just like a C answer must be foo(x){return x+x;} not x+x. Yes, such functions are fully allowed to take args in registers, as per Tips for golfing in x86/x64 machine code, like a function with a custom calling convention. \$\endgroup\$ Commented Dec 18, 2021 at 2:32
  • \$\begingroup\$ Forgive me- I'm sure you're more educated on this topic than me, but while ending a subroutine in assembly with a ret or jmp may be conventional, there's nothing that really requires that. I think it's perfectly reasonable to put a label at the top of some n lines and call it a subroutine. Further, I did include a link to a full running program. \$\endgroup\$
    – davey
    Commented Dec 18, 2021 at 2:45
5
\$\begingroup\$

Perl 5.10, 8 bytes

The two numbers to add must be on 2 separate lines for this one to work:

say<>+<>

Try this one here.

One with input on the same line (14 + 1 bytes for -a flag)

say$F[0]+$F[1]

Try it here!

One with input on the same line (19 + 1 bytes for -a flag)

map{$s+=$_}@F;say$s

Try this one here.

Another one, by changing the array default separator (19 + 1 bytes for -a flag as well)

$"="+";say eval"@F"

Try this one here!

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Hey, another good example (if this will end up being a catalogue challenge) is the method outlined by Dennis in this post: codegolf.stackexchange.com/q/32884 (ab)using the the -p flag. \$\endgroup\$ Commented Jul 13, 2016 at 15:51
  • \$\begingroup\$ Instead of say$F[0]+$F[1], say pop()+pop works (tested in Strawberry 5.20.2 with -E) and saves you a byte. \$\endgroup\$
    – msh210
    Commented Oct 31, 2016 at 9:11
5
\$\begingroup\$

Batch, 25 18 16 bytes

@cmd/cset/a%1+%2

Edit: saved 7 9 bytes by using my trick from Alternating Sign Sequence.

\$\endgroup\$
5
\$\begingroup\$

PowerShell v2+, 17 bytes

$args-join'+'|iex

Takes input as two separate command-line arguments, which get pre-populated into the special array $args. We form a string with the -join operator by concatenating them together with a + in the middle, then pipe that string to Invoke-Expression (similar to eval).


Thanks to @DarthTwon for reminding me that when dealing with such minimal programs, there are multiple methods of taking input all at the same byte-count.

$args[0]+$args[1]
param($a,$b)$a+$b

PowerShell is nothing if not flexible.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Yeah, I'm just stalking you here :P Alternate answers: $args[0]+$args[1] and param($a,$b)$a+$b \$\endgroup\$ Commented Jul 27, 2016 at 15:32
5
\$\begingroup\$

><>, 7 6 3 bytes

+n;

Online interpreter

Or try it on TIO with the -v flag.

Try it online

\$\endgroup\$
6
  • \$\begingroup\$ Since the question lets you define a function, I believe a simple + would be enough : it would pop two numbers from the stack and put the result of their addition back on the stack. The cost of -v could also be avoided, since reading the numbers could have been done beforehand the function invocation. \$\endgroup\$
    – Aaron
    Commented Jul 4, 2016 at 7:22
  • 1
    \$\begingroup\$ @Aaron: True. But as that solution is already posted for several other languages already I'll keep this as a full program. \$\endgroup\$
    – Emigna
    Commented Jul 4, 2016 at 8:48
  • 1
    \$\begingroup\$ I thought the v flag would be a maximum of +1 byte but either way you could use the fishlanguage.com interpreter and your total would be 3 bytes (it doesn't need -v). \$\endgroup\$ Commented Jan 9, 2017 at 15:53
  • \$\begingroup\$ @redstarcoder: Everyone always specifies the flag as 3 bytes for fish (and 1 byte for all other languages it seems). Not sure why it's different but I assume it is for a valid reason. \$\endgroup\$
    – Emigna
    Commented Jan 9, 2017 at 20:10
  • \$\begingroup\$ Regardless, you don't need the flag if you just use the fishlanguage.com interpreter. Do you have a link to the meta? I haven't seen any ><> program get added bytes for using integers on the initial stack (I've done it too). \$\endgroup\$ Commented Jan 9, 2017 at 20:22
5
\$\begingroup\$

Alchemist, 253 211 205 bytes

_->u+v+2r
u+r->In_a+In_x
v+r->In_b+In_y
a+b->Out_"-"
0_+0r+0d+0a+0b->d
0d+0a+x+b+y->b
0r+0d+a+0b+0y->d+Out_"-"
0r+0d+0b+a+0x->d
a+x+0b+y->a
0r+0d+0a+b+0x->d+Out_"-"
0r+0d+0a+b+0y->d
d+x->d+y
d+y->d+Out_"1"

Since Alchemist can't handle negative numbers (there can't be a negative amount of atoms) this takes 4 inputs on stdin in this order:

  • sign of x (0 -> + and 1 -> -)
  • the number x itself
  • sign of y (0 -> + and 1 -> -)
  • the number y itself

Output is in unary, try it online!

(for your convenience, here is a wrapper, converting inputs and returning decimal outputs)

Explanation & ungolfed

Since Alchemist applies the rules non-deterministically we need a lot of 0-rules.. Initially there is only one _ atom, so we use that to read the inputs:

_->u+v+2r
u+r->In_a+In_x
v+r->In_b+In_y

The following rules can't be applied because they all require 0r, now we have a, b as the signs of x and y respectively.

# Case -x -y: we output the sign and remove a,b
# therefore we will handle them the same as +x +y
0_+0r+0d+a+b->Out_"-"        #: 0_+0r+0d ⇐ a+b

# Case +x +y: doesn't need anything done
0_+0r+0d+0a+0b->d

# Case +x -y:
## remove one atom each
0_+0r+0d+0a+x+b+y->b         #: 0_+0r ⇐ x+b
## if we had |y| > x: output sign and be done
0_+0r+0d+a+0b+0y->d+Out_"-"  #: 0_ ⇐ 0r+a
## else: be done
0_+0r+0d+0b+a+0x->d          #: 0_ ⇐ 0r+a

# Case -x +y is symmetric to the +x -y case:
0_+0r+0d+a+x+0b+y->a         #: 0_+0r+0d ⇐ a+y
0_+0r+0d+0a+b+0x->d+Out_"-"  #: 0_ ⇐ 0r+b
0_+0r+0d+0a+b+0y->d          #: 0_ ⇐ 0r+b

# All computations are done and we can output in unary:
0_+d+x->d+Out_"1"            #: 0_ ⇐ d
0_+d+y->d+Out_"1"            #: 0_ ⇐ d

To the right of some rules I marked some golfs with #: y ⇐ x which should read as: "The conditions x imply y at this stage and thus we can remove it without changing the determinism"

\$\endgroup\$
7
  • 1
    \$\begingroup\$ ew. better output pls \$\endgroup\$
    – ASCII-only
    Commented Jan 29, 2019 at 10:06
  • \$\begingroup\$ ew. rules are rearranged based on alphabetical order so input is in wrong order if you try to combine them \$\endgroup\$
    – ASCII-only
    Commented Jan 29, 2019 at 10:09
  • \$\begingroup\$ wip \$\endgroup\$
    – ASCII-only
    Commented Jan 29, 2019 at 10:10
  • \$\begingroup\$ 154? \$\endgroup\$
    – ASCII-only
    Commented Jan 29, 2019 at 10:35
  • 1
    \$\begingroup\$ 131 \$\endgroup\$
    – ASCII-only
    Commented Jan 30, 2019 at 8:57
1
2 3 4 5
8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.