Counter-Fibonacci Sequences

13

1

Given three numbers m,n and p, your task is to print a list/array of length p starting with m and n and each element after p represents the difference of the 2 numbers before it, m-n (Counter-Fibonacci Sequence)

For this challenge you can either use a function to return or print the result or a full program.

Input

Three integers, m,n and p, separated by newlines/spaces/commas, whatever your language supports, but you should specify your input format. Code insertion is disallowed.

Output

The numbers contained by the Counter-Fibonacci Sequence, in any of the following formats (this example: m = 50, n = 40, p = 6):

  • 50,40,10,30,-20,50 (or with spacing after commas)
  • [50,40,10,30,-20,50] (or with spacing after commas)
  • 50 40 10 30 -20 50 (or with \n(newlines) instead of spaces)
  • {50,40,10,30,-20,50} (or with spaces instead of commas)

Examples

Input => Output

50,40,10 => 50,40,10,30,-20,50,-70,120,-190,310
-100,-90,7 => -100,-90,-10,-80,70,-150,220
250,10,8 => 250,10,240,-230,470,-700,1170,-1870

Rules

  • You are guaranteed that p is higher than 1
  • You should provide a way to test your program, if possible
  • Take note that this loopholes are forbidden and code insertion is disallowed, as mentioned above

Scoring & Leaderboard

Your code must be as short as possible, since this is . No answer will be accepted, because this challenge is meant to find the shortest answer by language, avoiding an unfair advantage to golfing languages.

var QUESTION_ID=113051,OVERRIDE_USER=59487;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>

Related Question by ETHproductions: Monday Mini-Golf #1: Reverse Fibonacci Solver

Mr. Xcoder

Posted 2017-03-16T15:19:14.780

Reputation: 39 774

Related, possible duplicate. It's basically the same challenge as this one, but outputting in reverse order from a specific spot in the sequence. – ETHproductions – 2017-03-16T15:24:35.430

@ETHproductions might be considered a dupe, but this is a bit different, trying to see the shortest solution in each language – Mr. Xcoder – 2017-03-16T15:27:09.070

Yeah, there wasn't as much worry about language inequality back then ;-) I don't think it makes a big difference though. The main difference here is that you can pretty much leave out the first step of the algorithm you would have used to solve that challenge (working backwards to find the starting point) – ETHproductions – 2017-03-16T15:29:07.237

@ETHproductions indeed there are small differences. If you wish this challenge to be removed, I'll totally do it. – Mr. Xcoder – 2017-03-16T15:30:25.273

I personally think it's fine. Aside, are we allowed to have a trailing separator? – ETHproductions – 2017-03-16T15:37:33.927

@ETHproductions yes, trailing separators are allowed – Mr. Xcoder – 2017-03-16T15:38:26.807

Would p, [m,n] be an okay input format? – Emigna – 2017-03-16T16:00:46.633

Yes @Emigna, it would. – Mr. Xcoder – 2017-03-16T16:04:29.923

Do we have to handle p=1? – Greg Martin – 2017-03-16T16:49:25.967

No, p=1 or 0 is excluded – Mr. Xcoder – 2017-03-16T16:50:16.003

Answers

9

Haskell, 29 bytes

a#b=a:b#(a-b)
(.(#)).(.).take

Length p is the first parameter. Usage example: ( (.(#)).(.).take ) 10 50 40 -> [50,40,10,30,-20,50,-70,120,-190,310]. Try it online!.

Shortening the list to p elements takes more bytes than producing it.

nimi

Posted 2017-03-16T15:19:14.780

Reputation: 34 639

6

Python 2, 39 bytes

-2 bytes thanks to ETHproductions

-1 byte thanks to Dennis

f=lambda m,n,p:p*[0]and[m]+f(n,m-n,p-1)

Try it Online!

math junkie

Posted 2017-03-16T15:19:14.780

Reputation: 2 490

6

Jelly, 6 bytes

_@С+Ṗ

Try it online!

How it works

_@С+Ṗ  Main link. Left argument: m. Right argument: n. Third argument: p

    +   Yield (m + n), the term that comes before m.
  С    Execute the link to the left p times, starting with left argument m and
        right argument (m + n). After each execution, replace the right argument
        with the left one and the left argument with the previous return value.
        Yield all intermediate values of the left argument, starting with m.
_@          Subtract the left argument from the right one.
        This yields the first (p + 1) terms of the sequence, starting with m.
    Ṗ   Pop; discard the last term.

Dennis

Posted 2017-03-16T15:19:14.780

Reputation: 196 637

5

JavaScript (ES6), 33 bytes

f=(m,n,p)=>p?m+[,f(n,m-n,p-1)]:[]

Returns a string of the format 1,2,3, — without using strings!

Test snippet

f=(m,n,p)=>p?m+[,f(n,m-n,p-1)]:[]

console.log(f(50,40,10))
console.log(f(-100,-90,7))
console.log(f(250,10,8))

ETHproductions

Posted 2017-03-16T15:19:14.780

Reputation: 47 880

5

CJam, 15 bytes

q~2-{1$1$-}*]S*

1 extra byte because CJam doesn't naturally use one of the allowed output formats >_<

Try it online!

Explanation

q~               e# Read and eval the input
  2-             e# Subtract 2 from p (to account for m and n being in the list)
    {            e# Run this block p-2 times:
     1$1$-       e#   Copy the top values and subtract
          }*     e# (end of block)
            ]    e# Wrap the stack in an array
             S*  e# Join with spaces

Business Cat

Posted 2017-03-16T15:19:14.780

Reputation: 8 927

5

Perl 6, 25 bytes

{($^m,$^n,*-*...*)[^$^p]}

Try it

Expanded:

{  # bare block lambda with placeholder parameters 「$m」 「$n」 「$p」
  (
    $^m, $^n,  # declare first two params, and use them

    * - *      # WhateverCode lambda which subtracts two values

    ...        # keep using that to generate values

    *          # never stop (instance of type Whatever)

  )[ ^ $^p ]   # declare last param, and use it to grab the wanted values
               # 「^ $^p」 is short form of range op
               # 「0 ..^ $^p」 which excludes the 「$p」
}

Brad Gilbert b2gills

Posted 2017-03-16T15:19:14.780

Reputation: 12 713

4

05AB1E, 9 7 bytes

ÍFÂ2£¥«

Try it online!

Explanation

ÍF          # p-2 times do
  Â         # create a reversed copy of the current list
   2£       # take the first 2 elements of the list
     ¥      # calculate delta
      «     # append to the list

Emigna

Posted 2017-03-16T15:19:14.780

Reputation: 50 798

3

Röda, 38 bytes

f i,a,b{seq 1,i|{|_|[a];b=a-b;a=a-b}_}

Try it online!

Explained:

f i,a,b{seq 1,i|{|_|[a];b=a-b;a=a-b}_}
f i,a,b{                             } /* Function declaration */
        seq 1,i                        /* Push numbers 1..i to the stream */
               |{|_|               }_  /* For each number in the stream: */
                    [a];               /*   Push the current value of a */
                        b=a-b;         /*   Set b = the next number */
                              a=a-b    /*   Set a = the previous value of b */

fergusq

Posted 2017-03-16T15:19:14.780

Reputation: 4 867

3

Haskell, 33 bytes

(m!n)0=[]
(m!n)p=m:(n!(m-n))(p-1)

Call using (m!n)p. Works by defining ! as an infix function that takes in m and n and returns a function that takes p and returns the desired result.

Julian Wolf

Posted 2017-03-16T15:19:14.780

Reputation: 1 139

Nice! I didn't think of making the function infix, so my best try with haskell was 34. BTW you can replace the newline with ; to make it single-line, so it looks a little more codegolfy. – AlexJ136 – 2017-03-16T20:46:15.023

2

PHP, 76 Bytes

[,$a,$b,$c]=$argv;for($r=[$a,$b];$c---2;)$r[]=-end($r)+prev($r);print_r($r);

PHP, 84 Bytes

[,$a,$b,$c]=$argv;for($r=[$a,$b];$c>$d=count($r);)$r[]=$r[$d-2]-end($r);print_r($r);

Jörg Hülsermann

Posted 2017-03-16T15:19:14.780

Reputation: 13 026

2

Ruby, 31 bytes

->m,n,p{p.times{m,n=n,(p m)-n}}

The straightforward solution

G B

Posted 2017-03-16T15:19:14.780

Reputation: 11 099

2

Pyth, 18 bytes

JEKEVEJ=N-JK=JK=KN

Try it online!

Input and output are both delimited by newlines.

How it works:

JEKE                Read two lines of input to J and K
    VE              Read another line and loop that many times:
      J               Print J
       =N-JK          Set N to J - K (Pyth uses prefix notation)
            =JK       Set J to K
               =KN    Set K to N

draziwfozo

Posted 2017-03-16T15:19:14.780

Reputation: 21

1

Mathematica, 26 bytes

{-1,1}~LinearRecurrence~##

Lovin' the builtin. Takes input in the form {{m, n}, p}. LinearRecurrence wants the know the coefficients of the linear combination of previous elements to use to generate new elements, which in this case is {-1,1}.

Greg Martin

Posted 2017-03-16T15:19:14.780

Reputation: 13 940

1

QBIC, 35 33 bytes

:::?'a;b;`[c-2|e=a-b?e';`┘a=b┘b=e

Saved 2 bytes by placing the first PRINT into one code literal.

Explanation (35 byte version):

:::         Get parameters a, b, c from the cmd-line
  ';`       This suppresses a newline when printing
?a   b';`   PRINT a and b
[c-2|       FOR x=1; x<=(c-2); x++
  e=a-b       calculate the next term of the sequence
  ?e';`       Print it, suppressing newline
  ┘a=b        ┘ denotes a syntactic linebreak; shove the numbers one over
  ┘b=e        dito
            FOR-loop is auto-closed

steenbergh

Posted 2017-03-16T15:19:14.780

Reputation: 7 772

Have any idea of an online interpreter to test this? – Mr. Xcoder – 2017-03-16T17:54:21.163

@Mr.Xcoder no online interpreter yet, sorry. I've added a link to the interpreter, which is a DOSBOX project running QBasic, running QBIC. – steenbergh – 2017-03-16T18:10:02.940

1The explanation is worth more than the interpreter @steenbergh, thanks for responding! – Mr. Xcoder – 2017-03-16T18:11:01.830

1

C, 128 bytes

m,n,p,z;main(c,v)char**v;{m=atoi(v[1]);n=atoi(v[2]);p=atoi(v[3])-2;printf("%d,%d",m,n);while(p--)z=m,m=n,n=z-m,printf(",%d",n);}

This program parses the three arguments m, n and p from the command-line, and prints the output as specified.

Modern C compilers allow you to omit basic imports, and thus we can use printf and atoi without the #includes.

Global variables are int by default when declared without a type - this saves a lot of space.

AlexJ136

Posted 2017-03-16T15:19:14.780

Reputation: 251

1

Java, 66 bytes

For once, lambdas are the inefficient approach to golfing due to the very roundabout way of applying recursion to them that requires a lot of extra bytes.

Golfed:

String f(int m,int n,int p){return""+m+(p>1?","+f(n,m-n,p-1):"");}

Ungolfed:

public class CounterFibonacciSequences {

  private static final int[][] INPUTS = new int[][] { //
      { 50, 40, 10 }, //
      { -100, -90, 7 }, //
      { 250, 10, 8 } };

  private static final String[] OUTPUTS = new String[] { //
      "50,40,10,30,-20,50,-70,120,-190,310", //
      "-100,-90,-10,-80,70,-150,220", //
      "250,10,240,-230,470,-700,1170,-1870" };

  public static void main(String[] args) {
    for (int i = 0; i < INPUTS.length; ++i) {
      final int m = INPUTS[i][0];
      final int n = INPUTS[i][1];
      final int p = INPUTS[i][2];
      System.out.println("M: " + m);
      System.out.println("N: " + n);
      System.out.println("P: " + p);
      System.out.println("Expected: " + OUTPUTS[i]);
      System.out.println("Actual:   " + new CounterFibonacciSequences().f(m, n, p));
      System.out.println();
    }
  }

  String f(int m, int n, int p) {
    return "" + m + (p > 1 ? "," + f(n, m - n, p - 1) : "");
  }
}

user18932

Posted 2017-03-16T15:19:14.780

Reputation:

1

AHK, 68 bytes

m=%1%
n=%2%
3-=2
Send %m%`n%n%`n
Loop,%3%
{
n:=m-n
m-=n
Send %n%`n
}

Getting' really tired of not knowing how / being able to use passed arguments (%1%, %2%, ...) directly in any math functions

Engineer Toast

Posted 2017-03-16T15:19:14.780

Reputation: 5 769

1

Python 2, 93 90 bytes

u,t=int,input;m,n,p=u(t()),u(t()),u(t());l=[m,n]
for i in range(p-2):l.append(l[-2]-l[-1])

Try it online!

Saved 3 bytes thanks to @Mr.Xcoder

It works by taking the numbers as input and formatting them correctly, then using a for loop to generate a list based on the inputted numbers.

Comrade SparklePony

Posted 2017-03-16T15:19:14.780

Reputation: 5 784

You can remove the space after comma in that range to save 1 byte – Mr. Xcoder – 2017-03-18T06:04:18.663

And it may be shorter if you map your input with ints and input.split – Mr. Xcoder – 2017-03-18T06:05:17.883

@Mr.Xcoder I tried the split, but it ended up being longer. – Comrade SparklePony – 2017-03-18T14:39:35.577

Ok, I couldn't test it. It's good anyway. – Mr. Xcoder – 2017-03-18T14:40:51.533

And the range does not need the first argument – Mr. Xcoder – 2017-03-18T14:48:09.083

0

Swift - 85 bytes

func y(x:Int,y:Int,z:Int){var m=x,n=y,p=z,c=0;for _ in 1...p{print(m);c=m;m=n;n=c-n}}

Usage: y(x:50,y:40,x:6)

Swift - 84 bytes

func z(l:[Int]){var m=l[0],n=l[1],p=l[2],c=0;for _ in 1...p{print(m);c=m;m=n;n=c-n}}

Usage: z(l: [50,40,6])


Output:

50
40
10
30
-20
50

Mr. Xcoder

Posted 2017-03-16T15:19:14.780

Reputation: 39 774

0

Python - 55 bytes

def s(m,n,p):
 for i in range(p):print(m);c=m;m=n;n=c-n

Try it online! & Usage: s(50,40,6)

Note: Solution without lambda

Mr. Xcoder

Posted 2017-03-16T15:19:14.780

Reputation: 39 774