The plus-minus sequence

27

1

The plus-minus sequence

The plus-minus sequence is one that starts with two seeds, a(0) and b(0). Each iteration of this sequence is the addition and subtraction of the previous two members of the sequence. That is, a(N) = a(N-1) + b(N-1) and b(N) = a(N-1) - b(N-1).

Objective Produce the plus-minus sequence, in infinitude or the first K steps given K. You may do this using an infinite output program, a generator, or a function/program that gives the first K steps. The output order does not matter, so long as it is consistent. (I.e., b(K) a(K) or a(K) b(K), with some non-numeric, non-newline separator in between.) The output must start with the input.

Test cases

For inputs 10 2 (of a(0) b(0), this is a possible output for the first K approach (or a subsection of the infinite approach):

10     2
12     8
20     4
24     16
40     8
48     32
80     16
96     64
160    32
192    128
320    64
384    256
640    128
768    512
1280   256
1536   1024
2560   512
3072   2048
5120   1024
6144   4096
10240  2048
12288  8192
20480  4096
24576  16384
40960  8192
49152  32768
81920  16384
98304  65536

For inputs 2 20 10 (a(0) b(0) k):

2     20
22   -18
4     40
44   -36
8     80
88   -72
16    160
176  -144
32    320
352  -288

This is a , so the shortest program in bytes wins.

Catalog

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes

<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><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="language-list"> <h2>Shortest Solution 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> <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> <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><script>var QUESTION_ID = 76983; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>

Conor O'Brien

Posted 2016-04-03T20:29:56.413

Reputation: 36 228

I notice a(2n) = a(0)·2ⁿ and b(2n) = n(0)·2ⁿ, but that's probably not useful here. – Neil – 2016-04-03T21:18:45.333

Can the non-numeric separator between a and b be a newline? – Suever – 2016-04-03T22:32:17.220

@Suever No, it cannot. – Conor O'Brien – 2016-04-03T22:33:15.883

@CᴏɴᴏʀO'Bʀɪᴇɴ Thanks for the clarification! – Suever – 2016-04-03T22:34:01.570

@Suever Always my pleasure :) – Conor O'Brien – 2016-04-03T22:40:23.503

We need to output the input? – msh210 – 2016-04-04T16:46:31.713

@msh210 Yes, you do. – Conor O'Brien – 2016-04-04T17:08:26.927

Can I output the terms in a list as [a,b]? – Rɪᴋᴇʀ – 2016-04-05T14:55:00.823

@EasterlyIrk Yes, you can. – Conor O'Brien – 2016-04-05T14:57:54.047

Does the order of the input seeds matter? For example, could I take input as b(0) a(0)? – Mego – 2016-04-11T06:16:32.640

@Mego that's fine – Conor O'Brien – 2016-04-11T11:08:07.043

It's notable that both of these sequences have standalone generation functions! WolframAlpha will even tell you what they are if you just copy paste the sequence in haha. Granted, those generation functions can be quite a few bytes. Here's one for the second column in your example. http://www.wolframalpha.com/input/?i=Table%5B%5B%2F%2Fmath:2%5E(x%2F2-1%2F2)+(1-(-1)%5Ex%2B2+sqrt(2)%2B2+(-1)%5Ex+sqrt(2))%2F%2F%5D,%7Bx,%5B%2F%2Fmath:1%2F%2F%5D,%5B%2F%2Fmath:15%2F%2F%5D,%5B%2F%2Fmath:1%2F%2F%5D%7D%5D

– Albert Renshaw – 2016-10-15T22:53:54.480

I'm a bit confused on requirements based on comments. Do we have to output a string, or is just returning a sequence of paired values acceptable? – user0721090601 – 2019-06-28T06:35:50.903

1Returning a sequence is fine @guifa – Conor O'Brien – 2019-06-28T14:24:17.987

Answers

14

Jelly, 5 bytes

ṄI;Sß

This is a recursive approach. Due to tail call optimization, the only limit is the ability to fit both integers into memory. Output is one list per line.

Try it online!

How it works

ṄI;Sß  Main link. Argument: [b[n], a[n]] (n = 0 for original input)

Ṅ      Print [b[n], a[n]] to STDOUT.
 I     Compute the increments of the list, i.e., [a[n] - [b[n]].
   S   Compute the sum of the list, i.e., b[n] + a[n].
  ;    Concatenate the results to the left and to the right.
    ß  Recursively call the main link.

Dennis

Posted 2016-04-03T20:29:56.413

Reputation: 196 637

Wow. That is quite impressive. – Conor O'Brien – 2016-04-03T22:23:51.153

What does Main link actually mean? – cat – 2016-04-03T22:26:20.597

4@cat It's like C's main function. Every line defines a different function/link, but the last one gets called automatically when the program is executed. – Dennis – 2016-04-03T22:27:20.170

ockquote>

Jelly programs consist of up to 257 different Unicode characters.

Isn't there 256 bits in a byte? – thepiercingarrow – 2016-04-04T01:44:46.067

@MarkWright and linefeeds can be used interchangeably. You can use both in UTF-8 mode, but there's only \x7f to represent them in Jelly's code page. – Dennis – 2016-04-04T01:48:23.470

So, the interpreter can read your file stored as 5 bytes? – thepiercingarrow – 2016-04-04T01:52:54.083

@MarkWright Yes, and I wouldn't claim a score of 5 otherwise. With the custom encoding, the source code consists of the bytes c9 49 3b 53 15. – Dennis – 2016-04-04T01:55:51.103

Ah, I see, thanks. – thepiercingarrow – 2016-04-04T02:11:07.223

5

Python 2, 31 bytes

def f(a,b):print a,b;f(a+b,a-b)

Prints forever. Well, eventually you exceed the recursion limit, but that's a system limitation.

xnor

Posted 2016-04-03T20:29:56.413

Reputation: 115 687

How long do you think this can go on for before a recursion error is raised? – R. Kap – 2016-04-04T00:17:58.810

@R.Kap it is ~1000. You can set this limit to whatever you want via sys.setrecursionlimit

– Mathias711 – 2016-04-04T06:22:08.057

@R.Kap It takes about 10 seconds on my machine. – xnor – 2016-04-04T06:58:56.887

10 seconds before raising a recursion error? Wow. In Python 3, I let mine go on for 30 minutes straight, and no error was raised whatsoever. I was able to print over 2000 digits for one of the numbers! I guess a while loop behaves differently than what you're doing. – R. Kap – 2016-04-04T07:00:51.383

I tried using this with a lambda but it took more bytes (f=lambda a,b:print(a,b)or f(a+b,a-b)) – MilkyWay90 – 2019-06-29T17:58:47.363

5

MATL, 10 bytes

`tDtswPdhT

This version will output an infinite number of elements in the plus-minus sequence.

Try it Online! (stop it after running due to infinite loop)

Explanation

    % Implicitly grab input as a two-element array [a,b]
`   % do...while loop
tD  % Duplicate and display the top of the stack
ts  % Duplicate [a,b] and add them together
w   % Swap the top two elements on the stack
P   % Swap the order of b and a in preparation for diff
d   % Compute the difference between b and a
h   % Horizontally concatenate [a+b, a-b]
T   % Explicit TRUE to make it an infinite loop
    % Implicit end of the do...while loop

Suever

Posted 2016-04-03T20:29:56.413

Reputation: 10 257

Does this automatically convert all very large numbers into scientific notation? – R. Kap – 2016-04-04T00:19:59.263

@R.Kap It looks like it does. That doesn't appear to be explicitly forbidden in the original problem statement. – Suever – 2016-04-04T00:25:29.033

Wow, that's pretty cool. In Python, if you have very big numbers, it still prints out all the digits, one at a time, so it gets a bit tedious looking at all that. I just thought that most other languages did that too, but it looks like Python is the unique one in this case. – R. Kap – 2016-04-04T00:29:08.900

Well so in MATLAB (which MATL uses under the hood), you can change the output format to be whatever you want. The default of MATL is to display up to 15 numbers before switching to scientific notation. – Suever – 2016-04-04T00:33:12.303

OOPS my bad, sorry, deleted ;) – thepiercingarrow – 2016-04-04T01:44:19.440

You can save a byte using a for loop, :"ttswPdh so you can use the implicit display. – David – 2016-04-04T05:21:33.027

@David Luis and I had played with that a little bit but the issue is that when you specify k=5, you get the first 6 elements rather than 5 due to the seed. This is different than the example in the problem statement. You would have to add a q to the beginning bring it back to 10 bytes. – Suever – 2016-04-04T12:48:59.230

Ahh didn't notice that, sorry. – David – 2016-04-04T22:47:59.943

4

Haskell, 19 bytes

a#b=a:b:(a+b)#(a-b)

Produces an infinite sequence of numbers. Usage example:

Prelude> take 20 $ 2#20

[2,20,22,-18,4,40,44,-36,8,80,88,-72,16,160,176,-144,32,320,352,-288]

nimi

Posted 2016-04-03T20:29:56.413

Reputation: 34 639

3

MathGolf, 8 bytes

ô`αp‼+-∟

Try it online!

Takes input in reverse order, but that's simply because that's how they are pushed onto the stack. Otherwise it'd be 1 byte longer. 2-3 bytes comes from the output. Without the need of actually printing one pair per line, the program could be æ`‼+-∟ (fills the stack with the elements of the sequence indefinitely), or É‼+-∟ (prints all elements of the sequence except the first one to debug, as long as -d flag is active).

Explanation

ô      ∟   do-while-true
 `         duplicate the top two items
  αp       wrap last two elements in array and print
    ‼      apply next two operators to the top stack elements
     +     pop a, b : push(a+b)
      -    pop a, b : push(a-b)

maxb

Posted 2016-04-03T20:29:56.413

Reputation: 5 754

Hi Max. Not sure since when, but currently the MathGolf version on TIO doesn't accept string input at all anymore.. Doesn't matter what builtin I use, even without any code for the program at all, if a string input is given like for example ABC, I get an error on line stdin = StdIn(line) in the Python code.. – Kevin Cruijssen – 2019-07-01T07:26:22.347

1

@KevinCruijssen Hi! String input should be given as 'ABC' or "ABC". Internally, ast.literal_eval is used to parse the input. There are still some quirks that need to be ironed out, but you should be able to do this.

– maxb – 2019-07-01T07:31:40.637

Ah ok, that makes sense. Btw, is there a builtin to split a string/number into parts of certain size or some amount of equal-sized parts? I.e. ABCDEF to [AB, CD, EF]? – Kevin Cruijssen – 2019-07-01T07:34:43.653

Nvm, apparently there isn't, but I've been able to find a way to do so: 2ô_2<\1>] (hard-coded to input-length 6 and split into parts of size 2, since that was what I needed, but should probably be modifiable to work for generic input-sizes and part-sizes). – Kevin Cruijssen – 2019-07-01T10:05:58.080

1

Perhaps you have overlooked the behavior of the division operator for strings? / does exactly what you say, split into chunks of $n$ characters. Check it out

– maxb – 2019-07-01T11:46:41.583

Oh, I have indeed looked past that. -7 bytes right there, thanks. :) – Kevin Cruijssen – 2019-07-01T11:51:52.877

3

Pyth, 10 9 bytes

Thanks to @isaacg for 1 byte.

#=Q,s
Q-F

Prints an infinite sequence of pairs.

$ pyth plusminus.p <<< "[10,2]" | head -n 15
[10, 2]
[12, 8]
[20, 4]
[24, 16]
[40, 8]
[48, 32]
[80, 16]
[96, 64]
[160, 32]
[192, 128]
[320, 64]
[384, 256]
[640, 128]
[768, 512]
[1280, 256]

PurkkaKoodari

Posted 2016-04-03T20:29:56.413

Reputation: 16 699

1The first and last Qs can be removed - Pyth will fill them in implicitly. – isaacg – 2016-04-04T03:44:50.363

@isaacg So that got implemented then? Cool. I tried removing the first one, but that didn't work. – PurkkaKoodari – 2016-04-04T12:27:45.173

That's strange, removing the first one worked on my machine. – isaacg – 2016-04-04T12:29:02.970

3

05AB1E, 7 bytes

Uses the first-k method. Input in the following for:

k
[a, b]

Code:

FD=OsƂ

Explanation:

F        # For N in range(0, k).
 D=      # Duplicate top of the stack and print without popping.
   O     # Sum up the array.
    sÆ   # Swap and perform a reduced subtraction.
      ‚  # Pair the top two elements. a, b --> [a, b]

Uses the CP-1252 encoding. Try it online!

Adnan

Posted 2016-04-03T20:29:56.413

Reputation: 41 965

1The code is vaguely reminiscent of the language name... – Conor O'Brien – 2016-04-04T13:52:51.757

@CᴏɴᴏʀO'Bʀɪᴇɴ Hahaha, both unreadable – Adnan – 2016-04-04T13:56:11.973

3

C, 81 bytes

a,b;main(c){for(scanf("%d%d%d",&a,&b,&c);c--;a+=b,b=a-b-b)printf("%d %d\n",a,b);}

mIllIbyte

Posted 2016-04-03T20:29:56.413

Reputation: 1 129

3

k, 12

{(+;-).\:x}\

.

k){(+;-).\:x}\[10;10 2]
10  2
12  8
20  4
24  16
40  8
48  32
80  16
96  64
160 32
192 128
320 64

Could also be called in the form of

k)10{(+;-).\:x}\10 2

tmartin

Posted 2016-04-03T20:29:56.413

Reputation: 3 917

11 bytes – streetster – 2019-06-27T06:59:54.517

3

APL, 37 chars

{⍺←3⊃3↑⍵⋄⎕←z←2↑⍵⋄⍺=1:⋄(⍺-1)∇(+/,-/)z}

Can be used as

    {⍺←3⊃3↑⍵⋄⎕←z←2↑⍵⋄⍺=1:⋄(⍺-1)∇(+/,-/)z} 10 2
10 2
12 8
20 4
24 16
40 8
48 32
80 16
[...]

or

      {⍺←3⊃3↑⍵⋄⎕←z←2↑⍵⋄⍺=1:⋄(⍺-1)∇(+/,-/)z} 10 2 6
10 2
12 8
20 4
24 16
40 8
48 32

lstefano

Posted 2016-04-03T20:29:56.413

Reputation: 850

2

Perl 6, 23 bytes (infinite)

Edit: thanks to JoKing, the sequence version is now the shortest (also removed .say per clarification from OP:

{@_,{.sum,[-] |$_}...*}

TIO:InfiniteSeq

Old functional answer

->\a,\b {(a,b).say;f(a+b,a -b)}

TIO:InfiniteFunc

Note that Perl 6 has no per se recursion limit, it is purely based upon memory available, so this will reach the millions before bombing out.

user0721090601

Posted 2016-04-03T20:29:56.413

Reputation: 928

23 bytes for infinite – Jo King – 2019-06-28T06:26:24.123

@Joking: Nice! I feel rather silly for not thinking of .sum . I think the requirements obligate outputing in the function (I've asked for clarification, but most others seem to have that, that gives 28 with https://tio.run/##K0gtyjH7n1upoJamYPu/2iFep1qvOLHSWq@4NFcnWjdWoUYlvlZPT0@r9j9QWCFNw9BAx0gzOs7QIPY/AA )

– user0721090601 – 2019-06-28T06:37:59.930

2

Reng v.3.2, 9 bytes (self-answer, non-competing)

ii¤ææö±2.

Takes two inputs (a b) and outputs b a. Try it here!

i takes input twice, ¤ duplicates the stack, æ prints a number and a space (and does so twice, there being two), ö prints a newline, ± does what you might expect, and 2. skips the next two characters, wrapping around the input getting characters.

Conor O'Brien

Posted 2016-04-03T20:29:56.413

Reputation: 36 228

2Hmm, would you mind explaining what each of those hieroglyphics do to a newb like me? :) – Kevin Cruijssen – 2016-04-04T09:06:30.113

@KevinCruijssen I have explained the mystery. :) – Conor O'Brien – 2016-04-04T11:20:50.773

2

Batch, 54 bytes

@echo %1 %2
@set/aa=%1+%2
@set/ab=%1-%2
@%0 %a% %b%

Note that CMD.EXE is limited to 32-bit signed integers, so it will quickly overflow and print garbage and error messages.

Neil

Posted 2016-04-03T20:29:56.413

Reputation: 95 035

1Always love to see a batch answer around here! :D – Conor O'Brien – 2016-04-03T21:24:15.933

1@CᴏɴᴏʀO'Bʀɪᴇɴ I wrote it especially for you. – Neil – 2016-04-03T21:43:38.750

2

Python 3.5, 55 43 bytes:

def q(a,b):
 while 1:print(a,b);a,b=a+b,a-b

Prints out the correct sequence seemingly forever. I have been able to let this go on for about 30 minutes without any error being raised, and the program had printed out 2301 digits for the first number, and 1150 digits for the second! Based on this, I guessing that, being provided sufficient hardware to run on, this can go on for WAY longer and print out WAY more digits, and also has theoretically no recursion limit, courtesy of the while loop!

R. Kap

Posted 2016-04-03T20:29:56.413

Reputation: 4 730

I think you're supposed to print out the current values at the beginning of the loop, so that the first output is the same as the input. Also, as this is code golf, you should optimise away the parentheses and intermediate variables. Finally, as a style nit, I think you should consider naming the variables a and b to match the question. – Neil – 2016-04-04T08:45:45.860

@Neil Thanks for the tips. :) – R. Kap – 2016-04-04T08:56:59.790

I'm confused; you've got both a while and a recursive call now... – Neil – 2016-04-04T08:58:27.660

@Neil Yeah, I did not notice that. Now it's fixed, and just a while loop, with theoretically no limits whatsoever. – R. Kap – 2016-04-04T09:06:14.750

2

Python 2.7, 56, 42 bytes:

a,b=input()
while 1:print a,b;a,b=a+b,a-b

Simple loop that either prints forever(ish).

Serdalis

Posted 2016-04-03T20:29:56.413

Reputation: 141

You can use a single space for the indent level to save bytes. Also, you do not have to do both methods, just one or the other, so you can remove the default parameter. – Conor O'Brien – 2016-04-04T00:58:47.397

Oh damn didn't notice notepad was making my tab into 4 spaces, and sure thing i'll restrict it to one, Thanks. – Serdalis – 2016-04-04T01:00:05.013

If you make this a program by changing the first line to a,b=input(), you can remove the indent. – xnor – 2016-04-04T06:29:17.267

@xnor Thanks, only saves 1 byte but it's not ugly anymore! – Serdalis – 2016-04-04T07:40:32.317

2

Julia, 25 bytes

a<|b=[a b]|>show<a+b<|a-b

Maximum syntax abuse. Julia is weird. Try it online!

Alternate version, 29 bytes

Note that the output will eventually overflow unless you call <| on a BigInt. Unfortunately, show will prefix each array with BigInt in this case. At the cost of four more bytes, we can generated whitespace-separated output for all numeric types.

a<|b="$a $b
"|>print<a+b<|a-b

Try it online!

How it works

We define the binary operator <| for out purposes. It is undefined in recent versions of Julia, but still recognized as an operator by the parser. While \ (not explicitly defined for integers) is one byte shorter, its high precedence would require replacing a+b<|a-b with (a+b)\(a-b) (+3 bytes) or \(a+b,a-b) (+2 bytes).

When a<|b is executed, it starts by calling show to print [a b] to STDOUT. Then, a+b<|a-b recursively calls <| on the sum or the difference.

Since the recursion is (supposed to be) infinite, the comparison < is never performed; it sole purpose is chaining the two parts of the code. This saves two bytes over the more straightforward alternative ([a b]|>show;a+b<|a-b).

Dennis

Posted 2016-04-03T20:29:56.413

Reputation: 196 637

1

Perl 5 -a, 41 bytes

@F=($F[0]+$F[1],$F[0]-$F[1])while say"@F"

Try it online!

Outputs the sequence infinitely.

Xcali

Posted 2016-04-03T20:29:56.413

Reputation: 7 671

1

dc, 27 bytes

rfr[rd3Rd_3R+p_3R-plxx]dsxx

Try it online!

jnfnt

Posted 2016-04-03T20:29:56.413

Reputation: 373

1

JavaScript - 4438/120 Bytes

38 Bytes from n = 0 to infinity

f=(a,b)=>{console.log(a,b);f(a+b,a-b)}

Try it online!

120 Bytes from n = 0 to n = k

f(10,2,20);
f(2,20,20);

function f(a,b,k){for(o=[[a,b]],i=1;i<k;i++)o.push([o[i-1][0]+o[i-1][1],o[i-1][0]-o[i-1][1]]);console.log(o.join("\n"))}

Pascal - 71 70 Bytes

program A;

procedure F(a:integer;b:integer);begin WriteLn(a,' ',b);F(a+b,a-b)end;

begin { main program }
   F(10,2);
   F(2,20);
end.

Try it online!

pixma140

Posted 2016-04-03T20:29:56.413

Reputation: 135

1

Forth (gforth), 46 bytes

: f 0 do 2dup swap . . cr 2dup + -rot - loop ;

Takes in A(0) B(0) and K

Try it online!

Code Explanation

: f           \ start a new word definition
  0 do        \ loop from 0 to k-1 (inclusive)
    2dup      \ duplicate A(n) and B(n)
    swap . .  \ print them out (swap the order so we get A(n) first)
    cr        \ print a newline
    2dup      \ duplicate A(n) and B(n) again
    + -rot -  \ Add A(n) and B(n), move the result, then subtract B(n) from A(n)
  loop        \ end the counted loop
;             \ end the word definition

reffu

Posted 2016-04-03T20:29:56.413

Reputation: 1 361

1

Stax, 8 bytes

≈└i≈√=æ`

Run and debug it

Takes input in the form a(0) b(0) k.

recursive

Posted 2016-04-03T20:29:56.413

Reputation: 8 616

1

Factor, 62 bytes

:: f ( a b -- x ) a b "%s %s" printf a b + a b - f ; recursive

recursive, or else the callstack runs out too quickly.

cat

Posted 2016-04-03T20:29:56.413

Reputation: 4 989

1

Ruby, 25 bytes

Based on xnor's Python solution. Perhaps I'll make a generator in another answer, but this will print a, then b, then the new a, then the new b, ad infinitum.

f=->a,b{p a,b;f[a+b,a-b]}

Sherlock9

Posted 2016-04-03T20:29:56.413

Reputation: 11 664

1

Python 3, 42 bytes

I wanted to write a generator for this function, and so I did.

def f(a,b):
 while 1:yield a,b;a,b=a+b,a-b

In Python 3, the sequence is generated in this way:

>>> gen = f(2, 20)
>>> next(gen)
(2, 20)
>>> next(gen)
(22, -18)
>>> next(gen)
(4, 40)
>>> next(gen)
(44, -36)
>>> next(gen)
(8, 80)

Sherlock9

Posted 2016-04-03T20:29:56.413

Reputation: 11 664

1

Common Lisp, 57

(lambda(a b)(loop(print`(,a,b))(psetf a(+ a b)b(- a b))))

Uses psetf, which affects values to variables in parallel, and the simple loop syntax.

coredump

Posted 2016-04-03T20:29:56.413

Reputation: 6 292

1

bash + GNU coreutils, 75 bytes

a=$1
b=$2
for i in `seq $3`;{ echo -e "$a\t$b";c=$a;a=$((c+b));b=$((c-b));}

Invocation:

./codegolf.sh 2 10 5

rexkogitans

Posted 2016-04-03T20:29:56.413

Reputation: 589

1

CP/M 8080, 47 bytes

z80 mnemonics but nothing the 8080 doesn't have, source commented once I decided to count the output rather than the input but terse function names retained, hand assembled so forgive the 'xx's where I know the number of bytes but haven't worked out the output addresses or offsets:

# setup
ld c, 2     0e 02

# loop
.s

# update H (temporarily in B)
ld a, h     7c
add l       85
daa         27
ld b, a     46

# update L
ld a, h     7c
sub l       95
daa         27
ld l, a     6f

# copy B back to H, output H
ld h, b     60
call +o     cd xx xx

# output L
ld b, l     45
call +o     cd xx xx

# repeat
jr -s       18 xx

# output a two-digit BCD value followed by a space
.o

# output high digit
ld a, b     78
rra         1f
rra         1f
rra         1f
rra         1f
call +ob    cd xx xx

# output low digit
ld a, b     78
call +ob    cd xx xx

# output a space
ld e, #$20  1e 20
call 5      cd 00 05

# return
ret         c9

# output a single BCD digit
.ob
and #$f     e6 0f
add #$30    c6 30
ld e, a     5f
call 5      cd 00 05
ret         c9

Tommy

Posted 2016-04-03T20:29:56.413

Reputation: 111

1

Clojure, 44 bytes

#(iterate(fn[[a b]][(+ a b)(- a b)])[%1 %2])

Function that produces an infinite lazy sequence.

MattPutnam

Posted 2016-04-03T20:29:56.413

Reputation: 521

1

Perl 5, 40 bytes

requires -E (free)

sub a{say"@_";($c,$d)=@_;a($c+$d,$c-$d)}

or (same length)

$_=<>;{say;/ /;$_=$`+$'.$".($`-$');redo}

(I struck through the latter because it should have rounding errors for some iterations.)

Hat-tip.

But I suspect there must be a shorter Perl 5 solution.

msh210

Posted 2016-04-03T20:29:56.413

Reputation: 3 094

1If there is a shorter solution, Ton Hospel will find it. :P – Conor O'Brien – 2016-04-04T18:11:58.913

Took a while, but I found a shorter way:

– Xcali – 2019-06-27T02:46:58.913

1

RETURN, 21 bytes

[¤.' ,$.'
,¤¤+2ª-F]=F

Try it here.

Recursive operator-lambda. Usage:

[¤.' ,$.'
,¤¤+2ª-F]=F10 2F

Explanation

[                 ]=F  declare function F for recursion
 ¤.' ,$.'␊,            output top 2 stack items along with trailing newline
           ¤¤+2ª-      get plus and minus of top 2 stack items
                 F     recurse!

Mama Fun Roll

Posted 2016-04-03T20:29:56.413

Reputation: 7 234

1

><>, 26 bytes

:?!;1-r:n48*o:@@:nao:@+}-$

Call with a, b, n on the stack, where n is the number of turns or a negative value for infinite output. Outputs a and b separated by a space.

As an explanation, here is how the stack evolves during runtime :

abn
nba
nbaa
naab
naabb
nabab
nab+
+nab
+n-
+-n

You can try it on the online interpreter with a positive amount of turns but you will need to use the official python interpreter to test the infinite mode.

$ python fish.py -c ':?!;1-r:n48*o:@@:nao:@+}-$' -t 0.01 -v 10 2 -1
10 2
12 8
20 4
24 16
40 8
48 32
80 16
96 64
160 32
192 128
320 64
384 256
640 128
768 512
1280 256
1536 1024
2560 512
3072 2048
5120 1024
6144 4096
10240 2048
12288 8192
20480 4096
24576 16384
40960 8192
49152 32768
81920 16384
98304 65536
163840 32768
196608 131072
327680 65536
393216 262144
655360 131072
786432 524288
1310720 262144
[...]

Aaron

Posted 2016-04-03T20:29:56.413

Reputation: 3 689

1

Fuzzy Octo Guacamole, 17 16 bytes

(non-competing, uses features later than the challenge)

^^(:C.Zs.aZ.s.-)

This was hard to make, due to client-side errors. But I got it!

Walkthrough:

^^                # Get input twice, pushes it to the stack.
  (               # Start a infinite loop.
   :              # Prints the stack, and since it has [a,b] is just the output.
    C             # Copy the active stack to the inactive stack.
     .            # Shift the active stack.
      Z           # Reverse the stack.
       s          # Move the top item on the active stack to the top of the inactive.
        .         # Switch stacks again.
         a        # Add the top 2 items, giving the first new item.
          Z       # Reverse the stack, so we keep the 'a' safe and prepare for the 'b'.
           .      # Switch stacks.
            s     # Move the top item on the active stack to the top of the inactive stack.
             .    # Switch stacks.
              -   # Minus the top 2 items, giving 'b'.
               )  # End infinite loop.

Rɪᴋᴇʀ

Posted 2016-04-03T20:29:56.413

Reputation: 7 410

I don't know FOG all that well, but can't you move the : to the beginning of the loop and eliminate the need for printing twice? – Conor O'Brien – 2016-04-05T15:29:25.647

oooooh @CᴏɴᴏʀO'Bʀɪᴇɴ thanks. – Rɪᴋᴇʀ – 2016-04-05T16:06:22.230

Don't forget to update the explanation ;) – Conor O'Brien – 2016-04-05T16:45:14.313

@CᴏɴᴏʀO'Bʀɪᴇɴ whadda ya mean? :P – Rɪᴋᴇʀ – 2016-04-05T18:41:03.700

1

Seriously, 12 bytes

,,1WX■@│+)-1

Outputs an infinite stream, format is b(n) a(n), one pair of outputs per line.

No online link because TryItOnline doesn't do so well with infinite loops.

Explanation:

,,1WX■@│+)-1
,,1           push a(0), push b(0), push 1
   W          while loop:
    X           discard the 1 (only used to make sure the while loop always runs)
     ■          print all stack elements, separated by spaces, without popping
      @│        swap, duplicate entire stack
        +)      push a(n) + b(n) (a(n+1)) and move it to the bottom of the stack
          -     push a(n) - b(n) (b(n+1))
           1    push 1 to make sure the loop continues

Mego

Posted 2016-04-03T20:29:56.413

Reputation: 32 998

1

J, 16 12 bytes

0&(]+/,-/)~<

Produces only the first k values for the sequence based on the given seeds.

Saved 4 bytes using the trick (or syntactic sugar) shown by @randomra in this comment.

Usage

   f =: 0&(]+/,-/)~<
   2 20 f 10
  2   20
 22  _18
  4   40
 44  _36
  8   80
 88  _72
 16  160
176 _144
 32  320
352 _288

miles

Posted 2016-04-03T20:29:56.413

Reputation: 15 654

1

C#, 50 bytes

f=(a,b)=>{Console.WriteLine(a+" "+b);f(a+b,a-b);};

Full source, including test case:

using System;
using System.Numerics;

namespace PlusMinusSequence
{
    class Program
    {
        static void Main(string[] args)
        {
            Action<BigInteger,BigInteger>f=null;
            f=(a,b)=>{Console.WriteLine(a+" "+b);f(a+b,a-b);};
            BigInteger x=10, y=2;
            f(x,y);
        }
    }
}

The BigInteger data type is used so the numbers don't overflow and become 0. However, since it is a recursive solution, expect a stack overflow.

adrianmp

Posted 2016-04-03T20:29:56.413

Reputation: 1 592

1

R, 41 bytes

The recursive solution, based on xnor's python solution:

f=function(a,b){cat(a,b,"\n");f(a+b,a-b)}

For the first-k method, the code size doubles to 82 bytes:

function(a,b,k=Inf,i=1){cat(a,b,"\n");while(i<k){cat(a<-a+b,b<-a-b*2,"\n");i=i+1}}

This function takes a and b as input, plus optionally k. If k is unspecified, it continues forever. (Well, until i overflows, which is a very big number, much larger than the recursion limit.)

rturnbull

Posted 2016-04-03T20:29:56.413

Reputation: 3 689

0

JavaScript (Node.js), 44 bytes, finite

k=>F=(a,b)=>k--&&F(a+b,a-b,console.log(a,b))

Try it online!

The function should be called with currying syntax (k)(a,b).

Shieru Asakoto

Posted 2016-04-03T20:29:56.413

Reputation: 4 445

0

Mathcad, 52 bytes

Two versions: one uses Mathcad's range variables (a form of iterator) and the second uses a for-loop inside a function.

enter image description here

The Mathcad user interface is a 2D "whiteboard", wherein expressions (which may be equations, text, plots or results) are evaluated in left-to-right, top-to-bottom order. Identifier names are usually typed letter-by-letter, but there are also many combinations that allow the user to enter Mathcad specific operators. For example, typing "=" will enter the definition operator (:=) and ";" will enter the range operator (..). Typing ctl-m brings up the matrix dialog, and typing the number of row and columns will create a matrix of that size. For golfing purposes, a Mathcad "byte" is taken to be the number of keyboard characters necessary to enter a letter/number/operator.

{the augment function is just there to make the display more table like but doesn't count to the byte total}

Stuart Bruff

Posted 2016-04-03T20:29:56.413

Reputation: 501