g | x | w | all
Bytes Lang Time Link
062AWK250826T130856Zxrs
034Uiua version 0.0.7231001T113708ZRay Bern
013Thunno 2230729T115455ZThe Thon
065JavaScript230208T105522ZShaggy
046Haskell220627T130245ZWheat Wi
109C#220701T111619ZAcer
008Vyxal220412T220436ZnaffetS
008Vyxal220701T020140Zemanresu
083PostScript220516T151628Zbartysla
060R211105T224401ZDominic
072krrp190918T225421ZJonathan
094C gcc190918T224207ZJonathan
024K ngn/k190828T172123Zscrawl
012Japt181126T094737ZShaggy
068R190207T214944ZRobert S
130C# .NET Core190208T203146ZDestroig
046Pari/GP181127T063503Zalephalp
041Ruby181126T093801ZG B
010MathGolf181126T093714Zmaxb
047Haskell160130T075408Zxnor
018Japt181126T010332ZKamil Dr
036Tidy181126T010053ZConor O&
059Mathematica171003T080309Znumberma
031J171003T063754ZJonah
009Husk171003T030726ZLeo
067Jq 1.5171002T231903Zjq170727
122BrainFlak170909T134631ZH.PWiz
078PHP170612T130131ZJör
360C++11160130T125945Zhetepepe
nanJava160213T022618Zhyperneu
132C160203T212503ZCole Cam
nanJavascript ES6/ES2015160129T230414Zgabrielp
038Perl 6160131T221234ZBrad Gil
006Boolfuck160130T125350ZStack Ex
059Python 3160129T215346ZMorgan T
022MATL160129T231924ZLuis Men
055Python 2160130T042016Zxnor
012Jelly160130T010923ZDennis
4767Perl 6160129T233214ZAndreas
066ES6160130T003433ZNeil
078Julia160129T230442ZAlex A.
013Pyth160129T214944ZFryAmThe
021APL160129T220918Zmarinus
079Python 2160129T220635ZLambda
056Haskell160129T220546Znimi

AWK, 62 bytes

n=$1{x=$2;for($0=X;j++<x;)for(i=0;i++<n;)j>n?$j+=$(j-i):$j=1}1

Attempt This Online!

n=$1{x=$2;           # get input
for($0=X;            # to highjack output
j++<x;)              # number of nums
for(i=0;i++<n;)      # range of previous nums
j>n?$j+=$(j-i):$j=1  # sum and set output
}1                   # output

Uiua (version 0.0.7), 34 bytes

→(;;)⍥(⊂∶/+↙∶→,⇌.)∶→(-,,)[⍥.-1∶1].

Thunno 2, 13 bytes

{1}¹{K°ɱS}K¹ɱ

Attempt This Online!

Explanation

{1}¹{K°ɱS}K¹ɱ  # Implicit input
{1}            # Push 1 to the stack n times
   ¹{    }     # Repeat x times:
     K°ɱ       #  Take the top n items of the stack
        S      #  And sum this list
          K¹ɱ  # Take the top x items of the stack
               # Implicit output

JavaScript, 65 bytes

The eval & slice are annoying me!

x=>g=(n,...a)=>n?g(n-1,...a,a[x-1]?eval(a.slice(-x).join`+`):1):a

Try it online!

Haskell, 46 bytes

g _ 0=[]
g(h:t)n=h:g(t++[sum$h:t])(n-1)
g.g[1]

Attempt This Online!

This is based on xnor's answer but it employs 1 clever trick.

The \$n\$-bonacci sequence always start with \$n\$ 1s. A more general version of this might start with just any \$n\$ values. And this more general version is what we implement with g. g takes a list of \$n\$ integers and a value \$m\$ and gives us a list of the first \$m\$ terms of this generalized \$n\$-bonacci sequence.

The trick is then that g[1] is a cheap way to generate \$n\$ 1s. Since the sequence starting with [1] is just an endless stream of 1s. So we use g in two ways, and even though g might be slightly longer because it implements something a little more general, it saves bytes because it serves two purposes.

C#, 109 bytes

(n,x)=>{int i,j,k;var y=new int[x];for(i=-1;++i<x;y[i]=i<n?1:k){k=0;for(j=i-n;j>-1&j<i;)k+=y[j++];}return y;}

Try it online!


(n, x) => { 
    int i, j, total; 
    var result = new int[x];
    for (i = -1; ++i < x; ) { //calculate each term one at a time
        total = 0; //value of the current term
        for (j = i - n; j > -1 & j < i;) //sum the last n terms
        {
            total += result[j++]; 
        }
        result[i] = i < n ? 1 : total; //first n terms are always 1 so ignore the total if i < n
    } 
    return result; 
}

Vyxal, 8 bytes

1ẋ{:∑pṫ,

Try it Online!

-2 bytes thanks to emanresu A

Vyxal , 8 bytes

1ẋ?‡W∑*Ḟ

Try it Online!

1ẋ       # [1] * input
   ‡W∑   # Function summing its inputs
  ?   *  # Set the arity to the input
       Ḟ # Generate an infinite list from the function and the vector of 1s.

PostScript, 83 bytes

/f{/x exch def/n exch def[1 1 x{n le{1}{n copy n 1 sub{add}repeat}ifelse}for]==}def

e.g., 5 11 f prints [1 1 1 1 1 5 9 17 33 65 129].

Try it online!

R, 60 bytes

function(n,m){for(i in 1:m)T[i]=`if`(i>n,sum(T[i-1:n]),1);T}

Try it online!

krrp, 72 bytes

^nx:\L[take]x,^nl:?nL#!fl@-n1#!r[append]lL[sum]lEl.x[map]^_:1.[range]0n.

Try it online!


Explanation

^nx:              ~ lambda expression in two parameters
 \L               ~  import list module
 [take]x          ~  the first x elements of
  ,^nl:           ~   extend the initial list of n ones
    ?n            ~    if n is non-zero
     L #!fl       ~     keep the first element
      @-n1        ~     recur
       #!r        ~     separate the first element
        [append]l ~      append an additional element,
         L[sum]lE ~      namely the sum of the previous elements
     l            ~    if n is zero, yield l
   . x            ~ extend x elements, yielding in a list of n+x elements
   [map]^_:1.     ~   map a constant function
   [range]0n.     ~   onto a list of n elements

Try it online!

C (gcc), 94 bytes

a(c,C,i){for(int Q[C+c],*q=Q;C--;printf("%d ",*q++))for(*q=Q-q>(i=-c);Q-q<=i&i<0;)*q+=q[i++];}

Try it online!

K (ngn/k), 26 24 bytes

{(y-x){y,+/x#y}[-x]/x#1}

Try it online!

Japt, 16 12 bytes

@ZÔ¯V x}hVÆ1

Try it

@ZÔ¯V x}hVÆ1     :Implicit input of integers U=X & V=N
         VÆ1     :Map the range [0,V) returning 1 for each element
        h        :Push the result of the following to the array and repeat until its length equals U
@                :  Pass the array through the following function as Z
 ZÔ              :    Reverse Z
   ¯V            :    Slice to the Vth element
      x          :    Reduce by addition
       }         :  End function

R, 68 bytes

function(n,x){a=1+!1:n;for(i in n+1:x){a[i]=sum(a[(i-n:1)])};a[1:x]}

Try it online!

C# (.NET Core), 130 bytes

(n,x)=>{int j=0,k=0,l=0;var b=new int[x];for(;j<(x<n?x:n);)b[j++]=1;for(j=n;j<x;l=0){for(k=n;k>0;)l+=b[j-k--];b[j++]=l;}return b;}

Try it online!

Pari/GP, 46 bytes

The generating function of the sequence is:

$$\frac{(n-1)x^n}{x^{n+1}-2x+1}-\frac{1}{x-1}$$

(n,m)->Vec(n--/(x-(2-1/x)/x^n)-1/(x-1)+O(x^m))

Try it online!

Ruby, 41 bytes

->a,b{r=[1]*a;b.times{z,*r=r<<r.sum;p z}}

Try it online!

MathGolf, 10 bytes

ª*kÆ_Σ▐├p;

Try it online!

Explanation

ª            push [1]
 *           pop a, b : push(a*b)
  k          read integer from input
   Æ         start block of length 5
    _        duplicate TOS
     Σ       sum(list), digit sum(int)
      ▐      append to end of list
       ├     pop from left of string/array
        p    print with newline
         ;   discard TOS

Haskell, 47 bytes

q(h:t)=h:q(t++[h+sum t])
n?x=take x$q$1<$[1..n]

Try it online!

<$ might have been introduced into Prelude after this challenge was posted.


Haskell, 53 bytes

n%i|i>n=sum$map(n%)[i-n..i-1]|0<1=1
n?x=map(n%)[1..x]

Try it online!

Defines the binary function ?, used like 3?8 == [1,1,1,3,5,9,17,31].

The auxiliary function % recursively finds the ith element of the n-bonacci sequence by summing the previous n values. Then, the function ? tabulates the first x values of %.

Japt, 18 bytes

@ZsVn)x}gK=Vì1;K¯U

Try it online!

Explanation:

         K=Vì1        :Start with n 1s in an array K
@      }gK            :Extend K to at least x elements by setting each new element to:
      x               : The sum of
 ZsVn                 : The previous n elements
              ;       :Then
               K¯U    :Return the first n elements of K

Tidy, 36 bytes

{x,n:n^recur(*tile(x,c(1)),sum@c,x)}

Try it online!

Explanation

{x,n:n^recur(*tile(x,c(1)),sum@c,x)}
{x,n:                              }   lambda taking parameters `x` and `n`
     n^                                take the first `n` terms of...
       recur(                     )        a recursive function
             *tile(x,c(1)),                whose seed is `x` `1`s
                           sum@c,          taking the sum of each window
                                 x         with a window size of `x`

Mathematica, 59 bytes

((f@#=1)&/@Range@#;f@n_:=Tr[f[n-#]&/@Range@#];f/@Range@#2)&

You'll probably want to Clear@f between function calls. Arguments are n,x, just like the test cases.

J, 31 bytes

]{.(],[:+/[{.])^:(-@[`]`(1#~[))

Ungolfed:

] {. (] , [: +/ [ {. ])^:(-@[`]`(1 #~ [))

explanation

Fun times with the power verb in its gerund form:

(-@[`]`(1 #~ [)) NB. gerund pre-processing

Breakdown in detail:

Try it online!

Husk, 9 bytes

↑§¡ȯΣ↑_B1

Try it online!

Starts from the Base-1 representation of N (simply a list of N ones) and ¡teratively sums (Σ) the last (↑_) N elements and appends the result to the list. Finally, takes () the first X numbers in this list and returns them.

Jq 1.5, 67 bytes

def C:if length>X then.[:X]else.+=[.[-N:]|add]|C end;[range(N)|1]|C

Assumes input provided by N and X e.g.

def N: 5;
def X: 11;

Expanded

def C:                        # . is current array
    if length>X               # stop when array is as long as X
    then .[:X]                # return first X elements
    else .+=[.[-N:]|add] | C  # recursively add sum of last N elements to array
    end
;
  [range(N)|1]                # initial state
| C

Try it online!

Brain-Flak, 144 124 122 bytes

-20 bytes thanks to Nitroden

This is my first Brain-Flak answer, and I'm sure it can be improved. Any help is appreciated.

(([{}]<>)<{({}(()))}{}>)<>{({}[()]<<>({<({}<({}<>)<>>())>[()]}{})({}<><({({}<>)<>}<>)>)<>>)}{}<>{({}<{}>())}{}{({}<>)<>}<>

Try it online!

PHP, 78 bytes

for(list(,$n,$x)=$argv;$i<$x;print${$i++}." ")$s+=$$i=$i<$n?1:$$d+$s-=${$d++};

Try it online!

-4 Bytes using PHP>=7.1 [,$n,$x] instead of list(,$n,$x)

C++11, 360 bytes

Hi I just like this question. I know c++ is a very hard language to win this competition. But I'll thrown a dime any way.

#include<vector>
#include<numeric>
#include<iostream>
using namespace std;typedef vector<int>v;void p(v& i) {for(auto&v:i)cout<<v<<" ";cout<<endl;}v b(int s,int n){v r(n<s?n:s,1);r.reserve(n);for(auto i=r.begin();r.size()<n;i++){r.push_back(accumulate(i,i+s,0));}return r;}int main(int c, char** a){if(c<3)return 1;v s=b(atoi(a[1]),atoi(a[2]));p(s);return 0;}

I'll leave this as the readable explanation of the code above.

#include <vector>
#include <numeric>
#include <iostream>

using namespace std;
typedef vector<int> vi;

void p(const vi& in) {
    for (auto& v : in )
        cout << v << " ";
    cout << endl;
}

vi bonacci(int se, int n) {
    vi s(n < se? n : se, 1);
    s.reserve(n);
    for (auto it = s.begin(); s.size() < n; it++){
        s.push_back(accumulate(it, it + se, 0));
    }
    return s;
}

int main (int c, char** v) {
    if (c < 3) return 1;
    vi s = bonacci(atoi(v[1]), atoi(v[2]));
    p(s);
    return 0;
}

Java, 82 + 58 = 140 bytes

Function to find the ith n-bonacci number (82 bytes):

int f(int i,int n){if(i<=n)return 1;int s=0,q=0;while(q++<n)s+=f(i-q,n);return s;}

Function to print first k n-bonacci number (58 bytes):

(k,n)->{for(int i=0;i<k;i++){System.out.println(f(i,n));}}

C, 132 bytes

The recursive approach is shorter by a couple of bytes.

k,n;f(i,s,j){for(j=s=0;j<i&j++<n;)s+=f(i-j);return i<n?1:s;}main(_,v)int**v;{for(n=atoi(v[1]);k++<atoi(v[2]);)printf("%d ",f(k-1));}

Ungolfed

k,n; /* loop index, n */

f(i,s,j) /* recursive function */
{
    for(j=s=0;j<i && j++<n;) /* sum previous n n-bonacci values */
        s+=f(i-j);
    return i<n?1:s; /* return either sum or n, depending on what index we're at */
}

main(_,v) int **v;
{
    for(n=atoi(v[1]);k++<atoi(v[2]);) /* print out n-bonacci numbers */
        printf("%d ", f(k-1));
}

Javascript ES6/ES2015, 107 97 85 80 Bytes

Thanks to @user81655, @Neil and @ETHproductions for save some bytes


(i,n)=>eval("for(l=Array(i).fill(1);n-->i;)l.push(eval(l.slice(-i).join`+`));l")

try it online


Test cases:

console.log(f(3,  8))// 1, 1, 1, 3, 5, 9, 17, 31
console.log(f(7,  13))// 1, 1, 1, 1, 1, 1, 1, 7, 13, 25, 49, 97, 193
console.log(f(5,  11))// 1, 1, 1, 1, 1, 5, 9, 17, 33, 65, 129

Perl 6, 38 bytes

->\N,\X{({@_[*-N..*].sum||1}...*)[^X]} # 38 bytes
-> \N, \X {
  (

    {

      @_[
        *-N .. * # previous N values
      ].sum      # added together

      ||     # if that produces 0 or an error
      1      # return 1

    } ... *  # produce an infinite list of such values

  )[^X]      # return the first X values produced
}

Usage:

# give it a lexical name
my &n-bonacci = >\N,\X{…}

for ( (3,8), (7,13), (1,20), (30,4), (5,11), ) {
  say n-bonacci |@_
}
(1 1 1 3 5 9 17 31)
(1 1 1 1 1 1 1 7 13 25 49 97 193)
(1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1)
(1 1 1 1)
(1 1 1 1 1 5 9 17 33 65 129)

Boolfuck, 6 bytes

,,[;+]

You can safely assume no N-Bonacci numbers will exceed the default number type in your language.

The default number type in Boolfuck is a bit. Assuming this also extends to the input numbers N and X, and given that N>0, there are only two possible inputs - 10 (which outputs nothing) and 11 (which outputs 1).

, reads a bit into the current memory location. N is ignored as it must be 1. If X is 0, the loop body (surrounded by []) is skipped. If X is 1, it is output and then flipped to 0 so the loop does not repeat.

Python 3, 59

Saved 20 bytes thanks to FryAmTheEggman.

Not a great solution, but it'll work for now.

def r(n,x):f=[1]*n;exec('f+=[sum(f[-n:])];'*x);return f[:x]

Also, here are test cases:

assert r(3, 8) == [1, 1, 1, 3, 5, 9, 17, 31]
assert r(7, 13) == [1, 1, 1, 1, 1, 1, 1, 7, 13, 25, 49, 97, 193]
assert r(30, 4) == [1, 1, 1, 1]

MATL, 22 26 bytes

1tiXIX"i:XK"tPI:)sh]K)

This uses current release (10.2.1) of the language/compiler.

Try it online!

A few extra bytes :-( due to a bug in the G function (paste input; now corrected for next release)

Explanation

1tiXIX"      % input N. Copy to clipboard I. Build row array of N ones
i:XK         % input X. Build row array [1,2,...X]. Copy to clipboard I
"            % for loop: repeat X times. Consumes array [1,2,...X]
  t          % duplicate (initially array of N ones)
  PI:)       % flip array and take first N elements
  sh         % compute sum and append to array
]            % end
K)           % take the first X elements of array. Implicitly display

Python 2, 55 bytes

def f(x,n):l=[1]*n;exec"print l[0];l=l[1:]+[sum(l)];"*x

Tracks a length-n window of the sequence in the list l, updated by appending the sum and removing the first element. Prints the first element each iteration for x iterations.

A different approach of storing all the elements and summing the last n values gave the same length (55).

def f(x,n):l=[1]*n;exec"l+=sum(l[-n:]),;"*x;print l[:x]

Jelly, 12 bytes

ḣ³S;
b1Ç⁴¡Uḣ

Try it online!

How it works

b1Ç⁴¡Uḣ  Main link. Left input: n. Right input: x.

b1       Convert n to base 1.
    ¡    Call...
  Ç        the helper link...
   ⁴       x times.
     U   Reverse the resulting array.
      ḣ  Take its first x elements.


ḣ³S;     Helper link. Argument: A (list)

ḣ³       Take the first n elements of A.
  S      Compute their sum.
   ;     Prepend the sum to A.

Perl 6, 52~72 47~67 bytes

sub a($n,$x){EVAL("1,"x$n~"+*"x$n~"...*")[^$x]}

Requires the module MONKEY-SEE-NO-EVAL, because of the following error:

===SORRY!=== Error while compiling -e
EVAL is a very dangerous function!!! (use MONKEY-SEE-NO-EVAL to override,
but only if you're VERY sure your data contains no injection attacks)
at -e:1

$ perl6 -MMONKEY-SEE-NO-EVAL -e'a(3,8).say;sub a($n,$x){EVAL("1,"x$n~"+*"x$n~"...*")[^$x]}'
(1 1 1 3 5 9 17 31)

ES6, 66 bytes

(i,n)=>[...Array(n)].map((_,j,a)=>a[j]=j<i?1:j-i?s+=s-a[j+~i]:s=i)

Sadly map won't let you access the result array in the callback.

Julia, 78 bytes

f(n,x)=(z=ones(Int,n);while endof(z)<x push!(z,sum(z[end-n+1:end]))end;z[1:x])

This is a function that accepts two integers and returns an integer array. The approach is simple: Generate an array of ones of length n, then grow the array by adding the sum of the previous n elements until the array has length x.

Ungolfed:

function f(n, x)
    z = ones(Int, n)
    while endof(z) < x
        push!(z, sum(z[end-n+1:end]))
    end
    return z[1:x]
end

Pyth, 13

<Qu+Gs>QGEm1Q

Test Suite

Takes input newline separated, with n first.

Explanation:

<Qu+Gs>QGEm1Q  ##  implicit: Q = eval(input)
  u      Em1Q  ##  read a line of input, and reduce that many times starting with
               ##  Q 1s in a list, with a lambda G,H
               ##  where G is the old value and H is the new one
   +G          ##  append to the old value
     s>QG      ##  the sum of the last Q values of the old value
<Q             ##  discard the last Q values of this list

APL, 21

{⍵↑⍺{⍵,+/⍺↑⌽⍵}⍣⍵+⍺/1}

This is a function that takes n as its left argument and x as its right argument.

Explanation:

{⍵↑⍺{⍵,+/⍺↑⌽⍵}⍣⍵+⍺/1}
                   ⍺/1  ⍝ begin state: X ones    
                  +     ⍝ identity function (to separate it from the ⍵)
    ⍺{         }⍣⍵     ⍝ apply this function N times to it with X as left argument
      ⍵,               ⍝ result of the previous iteration, followed by...
        +/              ⍝ the sum of
          ⍺↑            ⍝ the first X of
            ⌽          ⍝ the reverse of
             ⍵         ⍝ the previous iteration
 ⍵↑                    ⍝ take the first X numbers of the result

Test cases:

      ↑⍕¨ {⍵↑⍺{⍵,+/⍺↑⌽⍵}⍣⍵+⍺/1} /¨ (3 8)(7 13)(1 20)(30 4)(5 11)
 1 1 1 3 5 9 17 31                       
 1 1 1 1 1 1 1 7 13 25 49 97 193         
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 
 1 1 1 1                                 
 1 1 1 1 1 5 9 17 33 65 129              

Python 2, 79 bytes

n,x=input()
i,f=0,[]
while i<x:v=[sum(f[i-n:]),1][i<n];f.append(v);print v;i+=1

Try it online

Haskell, 56 bytes

g l=sum l:g(sum l:init l)
n#x|i<-1<$[1..n]=take x$i++g i

Usage example: 3 # 8-> [1,1,1,3,5,9,17,31].

How it works

i<-1<$[1..n]           -- bind i to n copies of 1
take x                 -- take the first x elements of
       i++g i          -- the list starting with i followed by (g i), which is
sum l:                 -- the sum of it's argument followed by
      g(sum l:init l)  -- a recursive call to itself with the the first element
                       -- of the argument list replaced by the sum