67
\$\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
    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
    Dec 4, 2016 at 11:56
  • 1
    \$\begingroup\$ @FinW Sure. As long as they don't get interpreted as octal. \$\endgroup\$
    – anna328p
    Dec 4, 2016 at 20:47

231 Answers 231

1
2
3 4 5
8
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
    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
    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\$ 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
    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\$ Jan 9, 2017 at 20:22
5
\$\begingroup\$

Vim, 5 bytes

DJ@"<C-a>

Note that <C-a> is one byte: 0x01, which is an unprintable character.

Since V is mostly backwards compatible, you can Try it online!

Explanation:

D           " Delete this line. 
            " By default this will save it into the unnamed register (@")
 J          " Get rid of this empty line
  @"        " Run the unnamed register as if it was typed.
            " Since it's a number, it will provide a count to the next command
    <C-a>   " Increment the next number on this line
\$\endgroup\$
5
\$\begingroup\$

Wise, 12 bytes (non-competing)

Mistah Figgins has me beat here

[:??:?^?&<]|

I just made this language so I thought I would try the basics.

Try it online

Explanation

[   ...   ]      #Loop until our carry is zero
 :               #Duplicate the top
  ??             #Roll the top two to the bottom
    :            #Duplicate the top
     ?           #Roll to the bottom

At this point we have n m m n on the stack

      ^          #Xor n and m
       ?         #Roll that to the bottom
        &        #And n and m to create the carry over
         <       #Bitshift to the left
           |     #Remove the extra zero with an or
\$\endgroup\$
2
  • 1
    \$\begingroup\$ [?~-!-~]| should work, and it is stack clean \$\endgroup\$ Mar 22, 2017 at 4:30
  • \$\begingroup\$ @MercyBeaucou Nice answer. I like my answer as is because it uses cool bitwise properties do add and yours is sufficiently different so I would recommend making your own answer to the question. \$\endgroup\$
    – Wheat Wizard
    Mar 22, 2017 at 4:45
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
    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
    Jan 29, 2019 at 10:09
  • \$\begingroup\$ wip \$\endgroup\$
    – ASCII-only
    Jan 29, 2019 at 10:10
  • \$\begingroup\$ 154? \$\endgroup\$
    – ASCII-only
    Jan 29, 2019 at 10:35
  • 1
    \$\begingroup\$ 131 \$\endgroup\$
    – ASCII-only
    Jan 30, 2019 at 8:57
5
\$\begingroup\$

Intel 8080 machine code, Altair 8800, 22 bytes

This will add two integers of nearly any size (16, 32, 64-bit, etc) using an Intel 8080 8-bit CPU (c. 1974). This is implemented as a full program, running on a MITS Altair 8800.

Code listing and programming instructions:

Step    Switches 0-7    Control Switch  Instruction Comment
1                       RESET
2       00 001 110      DEPOSIT         MVI  C, 2   ; loop counter set to word size
3       00 000 010      DEPOSIT NEXT                ; value is 2
4       00 010 001      "               LXI  D, 16H ; load address of first term into E:D
5       00 010 110      "                           ; at memory address 16H
6       00 000 000      "          
7       00 100 001      "               LXI  H, 18H ; load address of second term into H:L
8       00 011 000      "                           ; memory address 16H + word size = 18H
9       00 000 000      "          
10      10 101 111      "               XRA  A      ; clear accumulator
11      00 011 010      "               LOOP:LDAX D ; load [E:D] into A
12      10 001 110      "               ADC  M      ; add [H:L] + previous carry, to A
13      00 010 010      "               STAX D      ; store result in A to [E:D]
14      00 001 101      "               DCR  C      ; decrement loop counter
15      11 001 010      "               JZ   DONE   ; if counter is zero, end addition
16      00 010 101      "                           ; jump to step 23
17      00 000 000      "       
18      00 010 011      "               INX  D      ; first term next byte
19      00 100 011      "               INX  H      ; second term next byte
20      11 000 011      "               JMP  LOOP   ; restart loop
21      00 001 001      "                           ; jump to step 11
22      00 000 000      "           
23      01 110 110      "               DONE:HLT    ; halt CPU
24      00 001 110      "                           ; Term 1 low byte (14) 
25      00 000 000      "                           ; Term 1 high byte (0)
26      00 001 111      "                           ; Term 2 low byte (15)         
27      00 000 000      "                           ; Term 2 high byte (0)    
31                      RESET                       ; Reset program counter to beginning
32                      RUN
33                      STOP            
34      00 010 110      EXAMINE                     ; low byte of output displayed on D7-D0
35                      EXAMINE NEXT                ; high byte of output displayed on D7-D0

Try it online!

If entered correctly, RAM contents should look like:

0000    0e 02 11 16 00 21 18 00 af 1a 8e 12 0d ca 15 00 
0010    13 23 c3 09 00 76 0e 00 0f 00

I/O:

The above program adds two 16-bit integers, located in memory address 16H and 18H. This could accept larger integers, for example 32-bit integers by changing steps 3 and 8 to values 4 and 20H respectively, and then input would be in 16H and 20H. Numbers are represented in memory as little endian.

Output is displayed on lights D7-D0.

Example: 14 + 15 = 29 = 00 011 101

enter image description here

Example: 1234 + 4321 = 5555 = 00 010 101, 10 110 011

enter image description here

enter image description here

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

Microsoft PowerPoint (macro-free), 176 animations, 73 shapes on main slide

(Numbers estimated from XML explorer)

I made a 2-bit adder with carry input and carry output. Numbers represented in binary. Get the PPTX here. Directions are included in the presentation.

I'm thinking this is very golf-able, but it's a fun proof of concept anyway. Obviously, this can be extended to more bits, but frankly, programming in PowerPoint is extremely tedious with its current UI, so I'm going to move on to other things.

How it works

When the presentation starts, it is in input mode. The switches toggle a motion path animation back and forth to indicate 1 or 0.

When the Run button is clicked, it steps through each of the input bits and uses the K-maps for the carry and result bits. If there is a value dependent on the result (such as the carry bit over the second column), it uncovers a button that allows the machine to read that bit. When the final digit is clicked, the machine enters a halt state, displaying the final result in the bottom row.

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

Quantum Circuit 6*Nbits+1 Gates (25 for two 4-bit numbers)

Circuit Diagram

Based on the ripple adder of Cuccaro et al

  • Qubits 0/9 should be left as 0
  • 1:3 represent A in binary
  • 5:8 represent B in binary
  • Answer appears in qubits 5:9

Try it online!

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

in floop, 17 bytes

r+o?+n?-[r-]r[o;]

Try it online!

in floop is a language created by Redwolf Programs which runs in an infinite loop. It's a true tarpit, and incredibly hard to program in. It also has four variables (n, o, r, s), three of which we use here, and a tape.

  o?+             Take an input into variable o and increment it
                  ? does nothing if all input is consumed
     n?-          Ditto with n, but decrement it
r+                Increment r
        [  ]      If n is nonzero
         r-       Decrement r
                  If n is nonzero, r will be zero, and vice versa
            r[  ] If r is nonzero (n is zero)
              o;  Output o

In other words, this decrements n and increments o until n is zero, then outputs o.

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

sed, 275 bytes

s/[1-9]/0&/g
s/[5-9]/4&/g
s/[89]/4&/g
s/[2367]/xx&/g
s/[13579]/x/g
s/4/xxxx/g
s/[1-8]//g
s/$/ /
:a
s/\(.*\)0\(x*\) \(.*\)0\(x*\) /\1 \3 0\2\4/
ta
s/  *//g
:c
s/0xxxxxxxxxx/x0/g
tc
s/0x/-x/g
s/xx/2/g
y/x/1/
s/22/4/g
s/44/8/g
s/81/9/g
s/21/3/g
s/42/6/g
s/43/7/g
s/41/5/g
s/-//g

Takes 2 space-separated non-negative decimal integers on standard input; prints their sum to standard output

Explanation

We represent each input in unary-coded decimal, using x as our digit, and 0 as separator. For example, 42 is written 0xxxx0xx.

#!/bin/sed -f

# Convert to unary decimal
s/[1-9]/0&/g
s/[5-9]/4&/g
s/[89]/4&/g
s/[2367]/xx&/g
s/[13579]/x/g
s/4/xxxx/g
s/[1-8]//g

# Append space to separate second input from output
s/$/ /
# Consume the smallest of each digit from input, and push
# the sum to output
:add
s/\(.*\)0\(x*\) \(.*\)0\(x*\) /\1 \3 0\2\4/
tadd

# Everything is now accumulated in output; remove the spaces
s/  *//g
# Add carry to the next position
:carry
s/0xxxxxxxxxx/x0/g
tcarry

# Back to decimal
s/0x/-x/g
s/xx/2/g
y/x/1/
s/22/4/g
s/44/8/g
s/81/9/g
s/21/3/g
s/42/6/g
s/43/7/g
s/41/5/g
s/-//g

The extension to support decimal fractions is left as an exercise for the reader.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Unfortunately, this doesn't seem to work with negative numbers. \$\endgroup\$
    – Riley
    Oct 10, 2016 at 21:32
  • \$\begingroup\$ Also, if you're okay with using GNU sed, labels can be blank. :;b is an infinite loop. Using -r you don't need the \ in \( and \). And you might be able to get rid of the label :c entirely by jumping to :a everytime, but I'm not sure. \$\endgroup\$
    – Riley
    Oct 10, 2016 at 21:36
  • \$\begingroup\$ @Riley - I overlooked that the numbers might be negative (I was reusing something I already had). I'll have a look at implementing that when I can. As for GNU sed; yes, I do often use the GNU implementation, but for this answer I chose to go the POSIX route. \$\endgroup\$ Oct 11, 2016 at 7:50
5
\$\begingroup\$

Objective-Java*#++--Script.NETnotation.sh, 12 bytes.

.cmd.vbs.txt

Try it online!

How it works:

.cmd         # Gets the input and pushes it to the stack
    .vbs     # Adds the top two items on the stack
        .txt # Prints the top item on the stack
\$\endgroup\$
3
  • \$\begingroup\$ Welcome to Code Golf, and nice answer! The link in the header 404s for me, but looks like an interesting language \$\endgroup\$ Jun 27 at 2:28
  • \$\begingroup\$ @RadvylfPrograms Oops, I forgot to make the repository public. It should be fixed now. \$\endgroup\$
    – aketon
    Jun 28 at 0:55
  • \$\begingroup\$ Looks like a cool language! Being based on file extensions is an interesting concept. \$\endgroup\$ Jun 28 at 1:10
4
\$\begingroup\$

05AB1E, 1 byte

Code:

+

Try it online!.

\$\endgroup\$
0
4
\$\begingroup\$

Fishing, 22 bytes

v+CCCCCCCC
  In{In}aP

Explained

Sets casting direction down and casting length to 1.
Read input to the first 2 cells on the tape and convert to numbers.
Add the first 2 cells together and print.

\$\endgroup\$
4
\$\begingroup\$

MATLAB, 4 bytes

1 byte removed thanks to @LeakyNun

@sum

This is an anonymous function that takes an array and gives the sum. Example use:

>> f = @sum
f = 
    @sum
>> f([3 4])
ans =
     7
\$\endgroup\$
8
  • \$\begingroup\$ What about sum? \$\endgroup\$
    – Leaky Nun
    Jul 2, 2016 at 2:06
  • \$\begingroup\$ @LeakyNun Thanks, good idea! \$\endgroup\$
    – Luis Mendo
    Jul 2, 2016 at 9:56
  • \$\begingroup\$ 43 bytes? xD BTW: I thought we have to have full program or a function, so I'd say only @sum is a valid answer. Or is there another meta consensus? \$\endgroup\$
    – flawr
    Jul 2, 2016 at 18:19
  • \$\begingroup\$ @flawr I think there is, yes. But I couldn't find it \$\endgroup\$
    – Luis Mendo
    Jul 2, 2016 at 18:20
  • 4
    \$\begingroup\$ Wooah, I helped you reduce from 43 to 4 bytes XD \$\endgroup\$
    – flawr
    Jul 3, 2016 at 10:34
4
\$\begingroup\$

GoLScript, 1 byte (non-competiting)

K

Adds the top 2 numbers on the stack. That's it.

Now how to push them on to the stack, I have no clue. I don't think it's possible.. cough @CᴏɴᴏʀO'Bʀɪᴇɴ cough

\$\endgroup\$
2
  • \$\begingroup\$ Explanation soon to be coming. -- Riker Jul 3 '16 \$\endgroup\$
    – MD XF
    Sep 26, 2017 at 4:42
  • \$\begingroup\$ +1 for a Game of Life language. \$\endgroup\$
    – null
    Sep 27, 2019 at 5:29
4
\$\begingroup\$

C++ – 56 bytes

Should work on all unsigned integer types:

template<typename U>U f(U a,U b){return b?f(++a,--b):a;}

This is multiplication in the same style:

template<typename U>U g(U a,U b){return b>1?f(g(a,--b),a):(b?a:0);}

Finally exponentiation:

template<typename U>U h(U a,U b){return b>1?g(h(a,--b),a):(b?a:1);}
    

To test:

#include <iostream>

template<typename U>U f(U a,U b){return b?f(++a,--b):a;}
template<typename U>U g(U a,U b){return b>1?f(g(a,--b),a):(b?a:0);}
template<typename U>U h(U a,U b){return b>1?g(h(a,--b),a):(b?a:1);}

int main()
{
    std::cout << f(3, 4) << std::endl;
    std::cout << g(3, 4) << std::endl;
    std::cout << h(3, 4) << std::endl;
    return 0;
}

Output:

7
12
81
\$\endgroup\$
2
  • 2
    \$\begingroup\$ Dude, this is code golf. No need for templates, or the needlessly complicated addition, or even using typename instead of class... \$\endgroup\$ Jul 5, 2016 at 16:36
  • 5
    \$\begingroup\$ OP indicated he was "interested to see how it can be implemented". Thought it was an interesting approach to express addition, multiplication and even exponentiation as increment operations. \$\endgroup\$
    – user15259
    Jul 5, 2016 at 17:21
4
\$\begingroup\$

Shakespeare Programming Language (SPL) , 137 135 bytes

Complete program, golfed:

.
A.
B.
Act I
Scene I
[Enter A and B]
A: Listen to your heart!
B: Listen to your heart! You are the sum of me and you. Open your heart! 

And a brief explanation:

----
.                                 <- Title, everything before the first 
                                     full stop is considered as the tittle and treated as a comment
----
A.                                <- Dramatis personae. Here are introduced the characters in the play.
                                     |Characters are treated as variables.   
B.                                <--
----
Act I                             <- Acts and scenes are used to divide a program into smaller
                                     chunks in order to be able to refer to them later.
                                     |
Scene I                           <--
----
[Enter A and B]                   <- Characters on stage in the current scene, which are the              
                                     variables the program will have access to.
----
A: Listen to your heart!          <- Line of code. All of them have the same structure
                                     Variable: code. In this case, the concrete sentence
                                    "Listen to your heart!" reads an input number and stores it
                                     on the character (variable) refered to.
B: Listen to your heart!          <- Same as above 
   You are the sum of me and you. <- Sum the values of itself and the caharacter (variable)
                                     refered to.
   Open your heart!               <- Output the value of the character (value) refered to.

I am not actualy sure this is the shortest it can go. Check the official page for more info.

Edit 1: Removed the : after Act I and Scene I as it seems that everything after the roman numeral is ignored, thus saving 2 bytes.

\$\endgroup\$
2
  • 7
    \$\begingroup\$ This is not valid. The characters have to be from Shakespeare's plays and the :s do have to be there. Also, you need a comma after each character's name for a description. \$\endgroup\$
    – Oliver Ni
    Oct 13, 2016 at 18:19
  • \$\begingroup\$ You should be testing your code on TIO. \$\endgroup\$ Jan 7, 2020 at 14:47
4
\$\begingroup\$

Java, 31 bytes

int A(int b,int B){return b+B;}

Making the above snippet code compilable costs 9 bytes, resulting in a 40-byte program:

class a{int A(int b,int B){return b+B;}}

The "equivalent" monolithic program that can also handle numbers between 231 and 263-1 (inclusive) is 98 bytes long:

interface a{static void main(String[]A){System.out.print(Long.valueOf(A[0])+Long.valueOf(A[1]));}}

Java (lambda expression), 11 bytes

(a,b)->a+b;

This is a java.util.function.BinaryOperator<Integer>. It can also be a java.util.function.BinaryOperator<Long> if you have to add larger numbers.

\$\endgroup\$
17
  • 10
    \$\begingroup\$ Not golfing your code as much as possible is anathema to the point of code golf. \$\endgroup\$
    – user45941
    Jul 2, 2016 at 3:35
  • 2
    \$\begingroup\$ No, it's a lambda function. \$\endgroup\$
    – user45941
    Jul 4, 2016 at 2:30
  • 4
    \$\begingroup\$ @dorukayhan The point is, it's a function submission. We allow those. You don't need an enclosing class, and you don't need to worry about the necessary boilerplate for capturing the function. \$\endgroup\$
    – user45941
    Jul 4, 2016 at 3:07
  • 2
    \$\begingroup\$ @dorukayhan If you look closely at the question, it states that standalone functions are allowed. \$\endgroup\$
    – anna328p
    Jul 4, 2016 at 7:58
  • 2
    \$\begingroup\$ It's too bad this got downvoted. This is the shortest java answer I've ever seen. \$\endgroup\$
    – DJMcMayhem
    Jul 17, 2016 at 21:43
4
\$\begingroup\$

Hexagony, 9 bytes

?{?+@/!'/

Embiggened:

   ? { ?
  + @ / !
 ' / . . .
  . . . .
   . . .

Try it online!

Interestingly, this is only 2 bytes shorter than (what I think is) the most basic version, which is:

   ? { ?
  . . . .
 ' + ! @ .
  . . . .
   . . .

This requires 7 commands, of which one (?, which reads a number from STDIN). Now, as 7 is the 2nd centered hexagonal number, it might be able to fit inside a hexagon of side length 2, if you can use a single flow control character and reuse the ?. I've not been able to figure that out yet though :o(

\$\endgroup\$
4
\$\begingroup\$

C# - 11 10 bytes

a=>b=>a+b;

Apparently works in ES6 with no semicolon: 10 bytes

(a,b)=>a+b

A lambda expression.

\$\endgroup\$
9
  • \$\begingroup\$ Also valid in ES6 \$\endgroup\$ Jul 5, 2016 at 16:34
  • \$\begingroup\$ You missed the ending ; \$\endgroup\$
    – aloisdg
    Jul 10, 2016 at 14:16
  • \$\begingroup\$ @aloisdg I was unsure whether I should add a semicolon to end it or not :P Edited. \$\endgroup\$
    – Yytsi
    Jul 10, 2016 at 14:24
  • \$\begingroup\$ @TuukkaX I think we should use it. It feels more valid. :) \$\endgroup\$
    – aloisdg
    Jul 10, 2016 at 14:40
  • \$\begingroup\$ @aloisdg Techinally it is required in this case, so I'll keep it. \$\endgroup\$
    – Yytsi
    Jul 10, 2016 at 14:52
4
\$\begingroup\$

awk, 14 bytes

{print $1+$2}

I am not sure if this is acceptable because the arguments must be passed through a pipe using echo, or through the stdin stream in a file like so:

[user@localhost ~]$ echo '15 6' | awk -E add.awk
21
[user@localhost ~]$ echo '15 6' > numbers
[user@localhost ~]$ awk -E add.awk < numbers 
21

Permissible or not, I am excited to take my first swing at code golf!

\$\endgroup\$
2
  • \$\begingroup\$ Welcome to PPCG! This is perfectly valid! \$\endgroup\$ Oct 27, 2016 at 18:19
  • \$\begingroup\$ Of course is allowed to take input through STDIN. :) The other awk solution works the same way, just using here-string syntax in the sample run. (Some of us are finding it more readable.) BTW, the space after print is not necessary. \$\endgroup\$
    – manatwork
    Oct 27, 2016 at 18:23
4
\$\begingroup\$

Alice, 7 6 bytes

Thanks to Sp3000 for saving 1 byte.

+/
o@i

Try it online!

Explanation

Someone say again that golfing addition in languages that have an addition built-in is trivial...

A quick primer on Alice:

  • Alice has two modes: if the instruction pointer moves orthogonally, Alice is in Cardinal mode and can perform operations on integers. If the instruction pointer moves diagonally, Alice is in Ordinal mode and can perform operations on strings.
  • Data type conversion happens automatically when a value of the wrong type is popped from the stack.
  • Mirrors (\ and /) reflect the path of the IP through 67.5 degrees and switch between Cardinal and Ordinal mode. Here is a diagram of every possible reflection.
  • In Cardinal mode, if the IP hits the boundary of the grid it wraps around, as it does in many other 2D languages. If in Ordinal mode, the IP is reflected off the boundary instead.

The instruction pointer bounces all over the place in this solution:

+   Adds two implicit zeros on the stack, but effectively does nothing.
/   Send the IP southeast. Switch to Ordinal mode.
i   Read all input as a single string.
    We're in Ordinal mode, so the IP bounces off the corner of the grid
    and moves back northwest.
/   Send the IP west. Switch to Cardinal mode.
    We're in Cardinal mode, so the IP wraps to the end of the first line.
+   Try to add two numbers. The top of the stack is a string though, so Alice
    implicitly replaces it with the integers contained in the string, and
    then adds those two numbers.
/   Send the IP northwest. Switch to Ordinal mode.
    We're in Ordinal mode, so the IP immediately bounces off the top boundary
    and moves southwest instead.
o   Print a string to STDOUT. Since the top of the stack is a number, that
    number is first implicitly converted to its decimal string representation.
    We're in Ordinal mode, so the IP bounces off the corner of the grid
    and moves back northwest.
/   Send the IP south. Switch to Cardinal mode.
@   Terminate the program.
\$\endgroup\$
4
\$\begingroup\$

Add++, 7 bytes

+?
+?
O

Try it online!

+? adds the input to the accumulator and the O outputs it as a number.

A function is 1 byte longer at

D,f,@@,+
\$\endgroup\$
2
  • \$\begingroup\$ Weird, I would've thought a language called Add++ would be at... well... adding :D \$\endgroup\$
    – Beta Decay
    Jun 4, 2017 at 21:39
  • \$\begingroup\$ Right tool for the job \$\endgroup\$ Aug 6, 2017 at 8:55
4
\$\begingroup\$

R, 3 bytes

"+"

or

sum

"+" can be called as a function like so: "+"(a,b) because the R interpreter will interpret it (with the parentheses) as the primitive addition function .Primitive("+"). Alternatively, sum will add arbitrary arguments. These are both functions.

Try it online!

\$\endgroup\$
0
4
\$\begingroup\$

Piet - 5 Codels

I didn't see one in Piet, so I decided to post one.

It's really the code!

Hold on, let me scale that up a bit for you to see.

Codel size 25

The codel size is 25.

I tested this on npiet. When run, the program will ask for a number, then for another, and then print it out. Due to the nature of Piet, it will continue this cycle until you interrupt it.

There are 17 other variants of the same code. Everything is relative in Piet, so changing the start color will change the rest of the colors. Breaking down the code is as follows:

Light Red - Does nothing.

Dark Blue (hue shift 4, darkness shift 2) - Pushes a number from STDIN.

Green (hue shift 4, darkness shift 2) - Pushes a number from STDIN.

Teal (hue shift 1, darkness shift 0) - Pushes the sum of the top two numbers in the stack.

Dark Green (hue shift 5, darkness shift 1) - Writes top of stack to STDOUT as a number.

\$\endgroup\$
4
\$\begingroup\$

Bit, 985 bytes (non-competing)

I spent 2 hours on this, I present to you, an answer in Bit.

Behavior is undefined if one of the input numbers OR the sum of them is >= 10000, each of the 4 digits should be written aka 5 -> 0005, STDIN is read 2 times to get the 2 numbers.

Done without using extra files (that's an achievement for Bit programs, because no extra files means no if statements)

BIT 1
BYTE 1
BIT 0
BIT 1
BYTE 2
BIT 1
BIT 1
BYTE 3
BIT 0
BIT 1
BIT 0
BIT 1
BYTE a
BYTE b
BYTE c
BIT 0
BIT 0
BIT 0
BIT 0
BIT 1
BIT 1
BYTE d
BYTES 1 e
POWER a 2 b
POWER a 3 c
STORE 4 i
BYTE n
BYTE r
BYTE 0
BYTE t
BYTE y
BYTES 1 m
IN e i
DUMP_ARRAY i
SUBTRACT d
SHIFT
SUBTRACT d
MULTIPLY a
SHIFT
SUBTRACT d
MULTIPLY b
SHIFT
SUBTRACT d
MULTIPLY c
SHIFT
ADD
ADD
ADD
PUSH n
IN e i
DUMP_ARRAY i
SUBTRACT d
SHIFT
SUBTRACT d
MULTIPLY a
SHIFT
SUBTRACT d
MULTIPLY b
SHIFT
SUBTRACT d
MULTIPLY c
SHIFT
ADD
ADD
ADD
DUMP n
ADD
PUSH r
DIVIDE r a
DUP
TRUNC 0
FLIP
SUBTRACT
MUlTIPLY a
DUP
PUSH m
PUSH t
DIVIDE r b
DUP
TRUNC 0
FLIP
SUBTRACT
MUlTIPLY b
DUP
PUSH y
SUBTRACT t
DIVIDE a
PUSH m
DIVIDE r c
DUP
TRUNC 0
FLIP
SUBTRACT
MUlTIPLY c
DUP
PUSH t
SUBTRACT y
DIVIDE b
PUSH m
SUBTRACT r t
DIVIDE c
PUSH m
DUMP_ARRAY m
FLIP
ADD d
SHIFT
ADD d
SHIFT
ADD d
SHIFT
ADD d
SHIFT
OUTOF
PRINT
PRINTLN
\$\endgroup\$
4
\$\begingroup\$

BitCycle, 49 bytes

?Av
?v<>  \Cv
~=B/Av
 ^+  <
+ B\^v /~v
   >  /! <

Try it online!

Made so much more complicated by the signed numbers, otherwise it could just be:

?!
?^

This takes input and outputs as signed unary, though the -U flag is used to translate to decimal.

Explanation:

?Av  From input 1
?v<  And input 2
~=B  Push positive numbers into the top B collector
 ^
+ B  Invert bits of negative numbers and push into the bottom B collector
   >   \   Filter one bit from each collector
  B/Av     And the rest go into the A collector
  +  <     And then back into the B collectors
  B\^      If both positive and negative, then both bits are destroyed
   >   /   Otherwise they reflect off the > and go right of each of the \/
   >   \Cv    Collect the remainder of negative bits in the C collector

              Invert the bits and output
      v /~v   Send one of the 0s to output to represent a negative number
   >   /! <   Positive remainders go straight to output
\$\endgroup\$
4
\$\begingroup\$

TypeScript Compiler, 244 bytes

Yes, you read that right. Not TypeScript, but specifically its compiler.

type R<T,U,V>=T extends U?V:T
type N<T>=R<R<R<R<R<R<R<R<R<R<T,9,null>,8,9>,7,8>,6,7>,5,6>,4,5>,3,4>,2,3>,1,2>,0,1>
type P<T>=R<R<R<R<R<R<R<R<R<T,1,0>,2,1>,3,2>,4,3>,5,4>,6,5>,7,6>,8,7>,9,8>
type A<T,U>=T extends 0?U:A<P<T>,N<U>>
let x:A<1,2>=[]

Playground link

Enter the inputs as the type parameters of A (where I put 1 and 2) and the inferred type of x is their sum. It only takes one-digit inputs, and the output will be null if the addition overflows. It is in theory infinitely extendible, but in practice the compiler will just stop computing it if you allow numbers bigger than 20 (or 21 without overflow handling).

Because the inferred type gets erased by the compiler, I use the last three characters (=[]) to trigger a type error (TS2322), which contains the answer. For example, the error message may read

Type 'never[]' is not assignable to type '3'.

As for how this works:

R<T, U, V> returns V if T is U, and T otherwise.
N<T> returns T + 1. P<T> returns T - 1.
A<T, U> returns U if T is 0, and A<T - 1, U + 1> otherwise. Recursion!

One neat thing this can do is handle adding elements from two sets. For example, A<1|2,4|7> evaluates to 5 | 6 | 8 | 9.

\$\endgroup\$
2
  • \$\begingroup\$ Nice solution, but unfortunately this does not work for negative numbers, but I don't think it's possible at all with TypeScript's type system :/ Also, this is a much shorter solution for implementing addition with natural numbers: type T<N,U extends 0[]=[]>=U['length']extends N?U:T<N,[...U,0]>;type A<X,Y>=[...T<X>,...T<Y>]['length']: typescriptlang.org/play?#code/… \$\endgroup\$
    – ruohola
    Oct 3, 2021 at 13:03
  • \$\begingroup\$ This isn't the only one that doesn't work for negatives, reading through the other answers. And I'll admit this probably isn't the shortest you can get, since this is just the addition part stripped out of my answer to the "Peano Arithmetic at Compile Time" challenge. \$\endgroup\$
    – Bbrk24
    Oct 3, 2021 at 16:59
4
\$\begingroup\$

SPDT, 1168 bytes

p 0
t 0 1
t 0 2
t 0 3
t 0 4
t 0 5
t 0 6
t 0 7
t 0 8
t 0 9
t 0 10
t 0 11
t 0 12
t 0 13
t 0 14
t 0 15
t 0 16
r 1 0 33 34
r 9 34 33 17
r 1 0 35 36
r 9 18 36 35
r 2 0 40 41
r 10 37 41 40
r 37 0 42 43
r 17 20 43 42
r 2 0 44 45
r 10 45 44 38
r 37 0 46 47
r 17 47 46 39
r 38 0 48 19
r 39 0 48 19
r 3 0 52 53
r 11 49 53 52
r 49 0 54 55
r 19 22 55 54
r 3 0 56 57
r 11 57 56 50
r 49 0 58 59
r 19 59 58 51
r 50 0 60 21
r 51 0 60 21
r 4 0 64 65
r 12 61 65 64
r 61 0 66 67
r 21 24 67 66
r 4 0 68 69
r 12 69 68 62
r 61 0 70 71
r 21 71 70 63
r 62 0 72 23
r 63 0 72 23
r 5 0 76 77
r 13 73 77 76
r 73 0 78 79
r 23 26 79 78
r 5 0 80 81
r 13 81 80 74
r 73 0 82 83
r 23 83 82 75
r 74 0 84 25
r 75 0 84 25
r 6 0 88 89
r 14 85 89 88
r 85 0 90 91
r 25 28 91 90
r 6 0 92 93
r 14 93 92 86
r 85 0 94 95
r 25 95 94 87
r 86 0 96 27
r 87 0 96 27
r 7 0 100 101
r 15 97 101 100
r 97 0 102 103
r 27 30 103 102
r 7 0 104 105
r 15 105 104 98
r 97 0 106 107
r 27 107 106 99
r 98 0 108 29
r 99 0 108 29
r 8 0 112 113
r 16 109 113 112
r 109 0 114 115
r 29 32 115 114
r 8 0 116 117
r 16 117 116 110
r 109 0 118 119
r 29 119 118 111
r 110 0 120 31
r 111 0 120 31
l 18
l 20
l 22
l 24
l 26
l 28
l 30
l 32
l 31

Try it: https://radvylfprograms.com/spdt


SPDT is an esolang I've been wanting to make for a while now. Aside from I/O, it consists entirely of Single Pole Double Throw, or Form C, relays. This answer, which is possibly imperfectly golfed since I used a custom transpiler with macros to generate it, consists of relays arranged into AND, OR, and XOR gates, which are arranged into half adders and full adders, which are then used to make an 8-bit adder. This could be scaled up arbitrarily, at an \$n\log(n)\$ byte count for \$n\$ input bits.

I generated it with the following SPDT-c code, with SPDT-c being a transpiled language I made shortly after that makes it easier to design complex circuits (run it at https://radvylfprograms.com/spdt/c):

t 0 1
t 0 2
t 0 3
t 0 4
t 0 5
t 0 6
t 0 7
t 0 8

t 0 11
t 0 12
t 0 13
t 0 14
t 0 15
t 0 16
t 0 17
t 0 18

add 1 11 c1 21
addc 2 12 c1 c2 22
addc 3 13 c2 c3 23
addc 4 14 c3 c4 24
addc 5 15 c4 c5 25
addc 6 16 c5 c6 26
addc 7 17 c6 c7 27
addc 8 18 c7 29 28

l 21
l 22
l 23
l 24
l 25
l 26
l 27
l 28
l 29

and i i2 o:
    r i 0 - c
    r i2 c - o

or i i2 o:
    r i 0 - o
    r i2 0 - o

xor i i2 o:
    r i 0 1 2
    r i2 o 2 1

add i i2 o1 o2:
    and i i2 o1
    xor i i2 o2

addc i i2 c o1 o2:
    xor i i2 x
    xor x c o2
    and i i2 a
    and x c a2
    or a a2 o1

The transpiler currently lacks any optimizations, and the wire names it generates are numbers, while SPDT technically allows any non-whitespace combination of characters to be used. I didn't change that for this answer, as it's not a particularly interesting optimization, but it will be coming soon.

\$\endgroup\$
4
\$\begingroup\$

Positionally, 33 bytes

 / v


 +  
   ,
      ;

   <  /

Try It Online!

Positionally is a language I made where there are only two commands - space and non-space. The instruction run depends on the position of the IP.

The characters in the above could be any character aside from spaces. Positionally has implicit input, so the + command adds two numbers from input. Then, , prints it, before ; halts the program.

\$\endgroup\$
3
\$\begingroup\$

Golfscript, 9 2 bytes

~+

~ casts to int[], and + adds.

\$\endgroup\$
4
  • \$\begingroup\$ Just do this. \$\endgroup\$
    – Leaky Nun
    Jul 2, 2016 at 2:23
  • \$\begingroup\$ @LeakyNun Input must be in the form m n not m<newline>n. \$\endgroup\$ Jul 2, 2016 at 2:24
  • \$\begingroup\$ It is the same. \$\endgroup\$
    – Leaky Nun
    Jul 2, 2016 at 2:26
  • \$\begingroup\$ @NoOneIsHere It can be any whitespace character. \$\endgroup\$
    – anna328p
    Jul 2, 2016 at 3:25
1
2
3 4 5
8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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