44
\$\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\$
  • 26
    \$\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 '16 at 0:48
  • 1
    \$\begingroup\$ Can the answer take input with preceding zeros as default? e.g. 5 16 is inputted as 005 016 \$\endgroup\$ – FinW Dec 4 '16 at 11:56
  • \$\begingroup\$ @FinW Sure. As long as they don't get interpreted as octal. \$\endgroup\$ – dkudriavtsev Dec 4 '16 at 20:47

188 Answers 188

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\$
  • \$\begingroup\$ Also valid in ES6 \$\endgroup\$ – proud haskeller Jul 5 '16 at 16:34
  • \$\begingroup\$ You missed the ending ; \$\endgroup\$ – aloisdg Jul 10 '16 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 '16 at 14:24
  • \$\begingroup\$ @TuukkaX I think we should use it. It feels more valid. :) \$\endgroup\$ – aloisdg Jul 10 '16 at 14:40
  • \$\begingroup\$ @aloisdg Techinally it is required in this case, so I'll keep it. \$\endgroup\$ – Yytsi Jul 10 '16 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\$
  • \$\begingroup\$ Welcome to PPCG! This is perfectly valid! \$\endgroup\$ – NoOneIsHere Oct 27 '16 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 '16 at 18:23
4
\$\begingroup\$

Bubblegum, 98 bytes

00000000: 6672 6f6d 206d 6174 6820 696d 706f 7274  from math import
00000010: 2066 6163 746f 7269 616c 2061 7320 4623   factorial as F#
00000020: 0a74 7279 3a6e 3d69 6e74 2869 292d 313b  .try:n=int(i)-1;
00000030: 6f3d 6e2a 2846 286e 2925 2d7e 6e3d 3d6e  o=n*(F(n)%-~n==n
00000040: 290a 6578 6365 7074 3a6f 3d73 756d 286d  ).except:o=sum(m
00000050: 6170 2869 6e74 2c69 2e73 706c 6974 2829  ap(int,i.split()
00000060: 2929                                     ))

Try it online! (Note that the online interpreter takes input in xxd format)

Bubblegum is really good at three things:

  1. Compressing large outputs,

  2. Testing for primality, and

  3. Adding a sequence of numbers.

It's really really really bad at everything else.

\$\endgroup\$
4
\$\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\$
  • 1
    \$\begingroup\$ [?~-!-~]| should work, and it is stack clean \$\endgroup\$ – MildlyMilquetoast Mar 22 '17 at 4:30
  • \$\begingroup\$ @MistahFiggins 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 '17 at 4:45
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\$
  • \$\begingroup\$ Weird, I would've thought a language called Add++ would be at... well... adding :D \$\endgroup\$ – Beta Decay Jun 4 '17 at 21:39
  • \$\begingroup\$ Right tool for the job \$\endgroup\$ – Robert Fraser Aug 6 '17 at 8:55
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\$
3
\$\begingroup\$

05AB1E, 1 byte

Code:

+

Try it online!.

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

Golfscript, 9 2 bytes

~+

~ casts to int[], and + adds.

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

Labyrinth, 5 bytes

??+!@

Try it online!

Very straightforward: read input, read input, add, print, terminate.

\$\endgroup\$
3
\$\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\$
3
\$\begingroup\$

Befunge, 5 bytes

&&+.@

  • & takes an integer as input and puts it on the stack
  • + pops two numbers from the stack and puts the sum back on the stack
  • . pops a number from the stack and outputs it as an integer
  • @ ends the program

Try it: http://www.quirkster.com/iano/js/befunge.html

\$\endgroup\$
3
\$\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
    \$\begingroup\$ Dude, this is code golf. No need for templates, or the needlessly complicated addition, or even using typename instead of class... \$\endgroup\$ – proud haskeller Jul 5 '16 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 '16 at 17:21
3
\$\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\$
  • 1
    \$\begingroup\$ You could make this a lambda function and make it a lot shorter: (long a,long b)->a+b;. \$\endgroup\$ – Mego Jul 2 '16 at 3:31
  • 10
    \$\begingroup\$ Not golfing your code as much as possible is anathema to the point of code golf. \$\endgroup\$ – Mego Jul 2 '16 at 3:35
  • 2
    \$\begingroup\$ No, it's a lambda function. \$\endgroup\$ – Mego Jul 4 '16 at 2:30
  • 3
    \$\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\$ – Mego Jul 4 '16 at 3:07
  • 2
    \$\begingroup\$ It's too bad this got downvoted. This is the shortest java answer I've ever seen. \$\endgroup\$ – DJMcMayhem Jul 17 '16 at 21:43
3
\$\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\$
3
\$\begingroup\$

Brainfuck, 224 bytes

+[-->++++++[-<------>]+>>,----------]<,[<+++++[->-------
-<]+[<<<]>>[-]>[>[-<<<+<[-]+>>>>]>>]<<,]<-<<<[>[->+<]>[-
<+>[-<+>[-<+>[-<+>[-<+>[-<+>[-<+>[-<+>[-<+>[-<[-]<<+<<[-
]+>>>>>[-<+>]]]]]]]]]]]<<<<<]>>>[+++++[->++++++++<]>.>>]

Try it online!

Arbitrary precision. Input is taken newline separated, null terminated.

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

Perl 6, 3 bytes

*+*

A lambda that takes two arguments and returns their sum.

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

C, 19 bytes

f(a,b){return a+b;}
\$\endgroup\$
  • \$\begingroup\$ 17 bytes: f(a,b){b+=a;a=b;} \$\endgroup\$ – Johan du Toit Dec 7 '17 at 14:55
  • 1
    \$\begingroup\$ @JohanduToit In C language, in how it is defined as language you have to use return if the function has to return its result. If one compiler put in eax or rax that result : It is too much fragile (possible change some optimization flag, or change the compiler or the Os or the Pc etc: and the result will be different) \$\endgroup\$ – RosLuP Dec 7 '17 at 18:40
  • \$\begingroup\$ @JohanduToit: This is a C answer, not an "x86 gcc -O0" answer (or whatever you're programming for), so you can't use some silly hack that happens to generate machine code leaving a value in eax. \$\endgroup\$ – Peter Cordes Dec 17 '17 at 19:29
3
\$\begingroup\$

Turing Machine Simulator, 342 bytes

0 _ * r 1
0 * * r *
1 _ * r *
1 * * * 2
2 0 _ r *
2 * * * 3
3 _ * l 4
3 * * r *
4 _ * * halt
4 0 9 l *
4 1 0 l 5
4 2 1 l 5
4 3 2 l 5
4 4 3 l 5
4 5 4 l 5
4 6 5 l 5
4 7 6 l 5
4 8 7 l 5
4 9 8 l 5
5 _ * l 6
5 * * l *
6 _ * l *
6 * * * 7
7 _ 1 r 0
7 0 1 r 0
7 1 2 r 0
7 2 3 r 0
7 3 4 r 0
7 4 5 r 0
7 5 6 r 0
7 6 7 r 0
7 7 8 r 0
7 8 9 r 0
7 9 0 l *

Try it!

Input: Two decimal integers. These can be given to the code in standard input, as arguments to the program or function, or as a list.

Ugh...

\$\endgroup\$
  • 2
    \$\begingroup\$ Explanation, please? \$\endgroup\$ – Kritixi Lithos Dec 3 '16 at 12:12
3
\$\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\$
3
\$\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 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\$
  • \$\begingroup\$ Unfortunately, this doesn't seem to work with negative numbers. \$\endgroup\$ – Riley Oct 10 '16 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 '16 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\$ – Toby Speight Oct 11 '16 at 7:50
3
\$\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\$
3
\$\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\$
3
\$\begingroup\$

Lost, 9 bytes

v<<<
>%+@

Try it online!

Explanation

This is about as simple as lost programs get. Since the start location and direction are random we need to have a stream around the edges to catch the ip we then direct it into the %+@ which will perform the addition.

Alternative version

////
\%+@

Try it online!

\$\endgroup\$
  • \$\begingroup\$ So the IP can spawn at any random position on the top row and left column of the playing field? \$\endgroup\$ – MD XF Sep 26 '17 at 4:08
  • \$\begingroup\$ @MDXF The ip can spawn anywhere including the top row and left column. \$\endgroup\$ – Wheat Wizard Sep 26 '17 at 4:15
  • \$\begingroup\$ So what happens if the location starts on @? \$\endgroup\$ – caird coinheringaahing Oct 31 '17 at 21:48
  • \$\begingroup\$ @cairdcoinheringaahing It depends on the direction, but you can follow it out for yourself, the only one that takes a bit is the one traveling left, which goes all the way to the mirror before getting bounced back. Remember that in Lost % needs to be encountered before the program can exit on a @. \$\endgroup\$ – Wheat Wizard Oct 31 '17 at 22:52
  • \$\begingroup\$ @WheatWizard Ah, didn't know about the % rule. Interesting language! \$\endgroup\$ – caird coinheringaahing Oct 31 '17 at 23:11
3
\$\begingroup\$

AWK - 11 bytes

The code:

{$0=$1+$2}1

Can run as:

awk '{$0=$1+$2}1' <<< "98.342 77.123"

Could also store the code in a file sum.awk and run as:

awk -f sum.awk <<< "98.342 77.123"

If you wanted a program that wouldn't require knowing that you were using awk, you could create a file sum that looks like:

#!/bin/awk -f
{$0=$1+$2}1

Assuming of course that the awk executable is located at /bin/awk. If this file is made executable, it could simply be run as:

 sum <<< "98.342 77.123"

or

echo "98.342 77.123" | sum

Or place the numbers in a file, DATA, and run as:

sum DATA

A tiny bit of explanation. $0 represents a single line of input that is also automatically split into numbered fields. This line is then overwritten by the assignment. The lone 1 acts as a label that always evaluates to true and its default action is to simply print the current $0.

\$\endgroup\$
  • 1
    \$\begingroup\$ Wouldn't you still have to run it as sum <<< "98.342 77.123", or echo | sum? \$\endgroup\$ – Peter Cordes Dec 17 '17 at 19:46
  • \$\begingroup\$ You are correct. It would work better if the data were placed in a file, or as you suggested. \$\endgroup\$ – Robert Benson Dec 20 '17 at 19:56
3
\$\begingroup\$

Java, 11 10 9 bytes

a->b->a+b 

Ungolfed test code

public static void main(String[] args) {
    Function<Integer, Function<Integer, Integer>> func = (a -> b -> a + b);

    System.out.println(func.apply(5).apply(10));
}
\$\endgroup\$
  • \$\begingroup\$ You can save 1 byte: a->b->a+b; \$\endgroup\$ – TuxCrafting Oct 8 '16 at 11:09
  • \$\begingroup\$ The count is 9 bytes, not 10 bytes. The final semicolon is not to be counted because it's not part of the lambda expression. For example: one could pass the lambda as someLambdaAcceptingMethod(a->b->a+b). \$\endgroup\$ – Olivier Grégoire Jun 3 '18 at 7:41
3
\$\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\$
3
\$\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\$
  • 1
    \$\begingroup\$ ew. better output pls \$\endgroup\$ – ASCII-only Jan 29 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 at 10:09
  • \$\begingroup\$ wip \$\endgroup\$ – ASCII-only Jan 29 at 10:10
  • \$\begingroup\$ 154? \$\endgroup\$ – ASCII-only Jan 29 at 10:35
  • \$\begingroup\$ 135? \$\endgroup\$ – ASCII-only Jan 29 at 10:52
3
\$\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\$
2
\$\begingroup\$

Minkolang 0.15, 5 bytes

nn+N.

Try it here.

Explanation

nn       Take two numbers from input
  +      Add
   N.    Output as number and stop.
\$\endgroup\$
2
\$\begingroup\$

Silicon, 3 bytes

II+

Simple enough. Takes input and converts it to an integer twice and adds them together. Output is implicit.

\$\endgroup\$

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.