# Introduction

• Note that I learned it from a Numberphile Video, where Neil Sloane explains it better. I recommend you to watch his Video. But for a quick Introduction:

The Levine Sequence is made from the Levine's Triangle, which is made as follows:
First you have $$\0\$$ ones, and $$\1\$$ twos.
Then you read the list backwards (right to left) and you have the same number of ones, as the $$\0\$$$$\th\$$ element of the list.
Then you have the same number of twos, as the $$\1\$$$$\th\$$ element of the list. That goes on and on, till the list ends. These are the first few rows:

ln: 2
ln: 11
ln: 12
ln: 112
ln: 1123
ln: 1112234
ln: 11112223344567


Really, I don't think I've explained it good, so check out Neil's Video to learn more about it.

So, now, the Levine's Sequence. The $$\n\$$$$\th\$$ Term of the sequence (starting at $$\0\$$), is just the sum of the $$\n\$$$$\th\$$ row of the Levine's Triangle. These are the first few terms: 2, 2, 3, 4, 7, 14.
Then it just blows up.

Disclaimer: In the Numberphile video, also when you follow the steps I told, the $$\0\$$$$\th\$$ term is $$\2\$$. But in OEIS the first term is $$\1\$$. So I will accept both sequences.

# Rules

• The output must be printed to the program's output.
• The output must be in base 10 (outputting them in any other base is not allowed).
• Your program must can take input, the nth term.
• Outputting the integers with trailing / leading spaces is allowed.
• This is , so the shortest (original) code in each language wins!

I'm a bit free about this, so you can output just the $$\n\$$$$\th\$$ term, up to the $$\n\$$$$\th\$$ term, or even the whole sequence!

I liked the leaderboard thingy, so here it is again: This uses uses @manatwork's layout.

/* Configuration */

var QUESTION_ID = 222856; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 96037; // This should be the user ID of the challenge author.

/* App */

return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(a) {
});
comment_page = 1;
}
});
}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
});
else process();
}
});
}

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

function getAuthorName(a) {
return a.owner.display_name;
}

function process() {
var valid = [];

var body = a.body;
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,
language: match,
});

});

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;

.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)

var lang = a.language;
if (! /<a/.test(lang)) lang = '<i>' + lang + '</i>';
lang = jQuery(lang).text().toLowerCase();

languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang};
});

var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);

langs.sort(function (a, b) {
if (a.uniq > b.uniq) return 1;
if (a.uniq < b.uniq) 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)
language = jQuery(language);
jQuery("#languages").append(language);
}

}
body { text-align: left !important}

width: 290px;
float: left;
}

#language-list {
width: 290px;
float: left;
}

font-weight: bold;
}

table td {
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>

</tbody>
</table>
</div>
<div id="language-list">
<h2>Winners by Language</h2>
<table class="language-list">
<tr><td>Language</td><td>User</td><td>Score</td></tr>
<tbody id="languages">

</tbody>
</table>
</div>
<table style="display: none">
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
</tbody>
</table>

• "The output must be in base 10 (outputting them in any other base)" - it seems you forgot to finish the sentence, though really I think restrictive rules (and requiring input to STDOUT) like this are not the best idea and I'd strongly recommend just using the I/O defaults. Also, "Your program must not take input" is inconsistent with the actual challenge to print the nth term - where does n come from if not as input? Standard sequence rules would allow you to print either the nth term, up to the nth, or print infinitely - is that allowed? Apr 4, 2021 at 11:43
• Sorry, I forgot it. Apr 4, 2021 at 11:44
• In future please post your challenges in the Sandbox before using the main site so you can iron out problems like this early on Apr 4, 2021 at 11:44
• @pxeger Ok, I will do it next time. Apr 4, 2021 at 11:46
• "So, now, the Levine's Sequence. The nth Term of the sequence (starting at 0), is just the nth row of the Levine's Triangle." - Shouldn't it be the sum of the row? Apr 4, 2021 at 13:23

# J, 17 15 bytes

1#.0&(]|.##\)&2


Try it online!

-2 thanks to FrownyFrog!

On TIO, handles up to the 11th term 6837625106787 (where term 1 is 2).

## how

J's "Copy" verb # is tailor made for this challenge:

   1 2 3 # 'abc'
abbccc


The rest is just mechanics needed to reverse and iterate:

• 0&(...)&2 Iterate ... as many times as the input. This occurs as a result of a special rule J has for the bond & conjunction. The &2 on the right hand side also sets the starting value of the iteration.
• ]... Ignores the left argument of 0 (resulting from 0&), and returns the result of ..., which is processed as a single argument verb, because this entire phrase is a dyadic hook.
• |.##\ Reverse current list |., and use it as a mask to duplicate # the numbers 1...<length of current list>.
• 1#. Sum the result of that iteration.
• 1#.(]|.##\)^:[&2 or 1#.[0&(]|.##\)2: for 16 Apr 4, 2021 at 13:53
• 1#.0&(]|.##\)&2 for 15 Apr 4, 2021 at 13:54
• @FrownyFrog Very clever. I had tried using Bond to shorten it but totally missed this approach, so thank you! Apr 4, 2021 at 16:11

# Python 3, 9187 85 bytes

f=lambda n,l=:n and f(n-1,[n+1for n,e in enumerate(l[::-1])for _ in*e])or l[-1]


Try it online!

Inputs $$\1\$$-based index $$\n\$$ and returns the $$\n^{\text{th}}\$$ element of the Levine Sequence starting at $$\1\$$.

### Explanation

Starts at  and successively computes the next row in Levine's Triangle. The last element in the $$\(n+2)^{\text{th}}\$$ row is equal to the sum of the $$\n^{\text{th}}\$$ row or the $$\n^{\text{th}}\$$ term of the Levine Sequence starting at $$\2\$$. By using a $$\1\$$-based index and starting the sequence at $$\1\$$ we simply return the last element in the $$\(n+1)^{\text{th}}\$$ row.

# R, 49 48 bytes

Edit: -1 byte thanks to Giuseppe

i=1:0;repeat{i=rep(seq(!i),rev(i));show(sum(i))}


Try it online!

Prints the infinite sequence (well, until it fails to allocate vector of size 25472.1 Gb at the 12th iteration...)

• seq(!i) is a byte shorter. Apr 4, 2021 at 14:45
• @Giuseppe - Thanks! I stared & stared at that horrible seq(a=i) but somehow couldn't think of a better way. That's much nicer now. Apr 4, 2021 at 14:47

# Python 2, 62 bytes

-3 bytes thanks to @xnor

Outputs the Levine sequence indefinitely, starting at 1.

a=
while 1:i=len(a);print i;exec'a+=a.pop(i-1)*[i];i-=1;'*i


Try it online!

• Ah, yes, infinite printing is allowed >.< Apr 4, 2021 at 18:30
• It's really nice how you're appending to the end of the list while popping the original elements to avoid needing to allocate a new list.
– xnor
Apr 4, 2021 at 23:15
• Since the sum of each list is the length of the list at the next step, it looks like you can shift by a loop to avoid the sum.
– xnor
Apr 4, 2021 at 23:25
• @xnor Very nice, and obvious in hindsight! And with the rules stating that starting with 1 is allowed, that's two more bytes saved. Apr 5, 2021 at 1:30

# Scratch, 734 715 Bytes

-19 thanks to Lyxal!
Try it online!

Previously discussed, there doesn't seem to be a consensus on how to score Scratch code. I converted the code to scratchblocks4 and counted the characters:

when gf clicked
delete all of[B v
delete all of[E v
delete all of[T v
set[D v]to(1
set[C v]to(0
A
repeat((item(length of [T v])of[T v])-(1
A
if<not<(R)=(item((length of[B v])-(1))of[B v])>>then
change[C v]by(()-(length of(D
change[D v]by(-1
delete(length of[B v])of[B v
A
end
end
set[D v]to(length of[B v
set[S v]to(
set[V v]to(1
set[t v]to(0
repeat(length of[B v
repeat(item(1)of[B v
set[S v]to(join(S)(V
end
change[V v]by(1
change[t v]by(item(1)of[B v
delete(1)of[B v
end
define A
set[R v]to(
repeat(length of(D
set[l v]to(item(length of[E v])of[E v
set[R v]to(join(letter((length of(l))-(C))of(l))(R
change[C v]by(1
end


Alternatively, the program is 73 blocks: Obviously, Scratch isn't the first choice for any serious program, but I enjoyed making this! Lyxal substituted (item(length of[E v])of(E v for a variable, saving 19 bytes.

• Welcome to Code Golf! This is a really cool answer! Apr 9, 2021 at 4:14
• Very nice scratch answer - I'm glad to see someone else is joining the scratch side of golfing. Here's a way to turn it into 715 bytes. Apr 9, 2021 at 4:17

# Jelly, 7 bytes

2JxṚƊ¡S


Try it online!

Outputs the $$\n\$$th term.

## Explanation

2JxṚƊ¡S   Main monadic link
¡    Repeat n times
Ɗ     (
J          Indices (range [1..length])
x         Repeat each item a number of times given by the corresponding item in
Ṛ          The list reversed
Ɗ     )
S   Sum


# Wolfram Language (Mathematica), 71 bytes

prints the nth 0-indexed term

Tr@Nest[Join@@MapThread[Table,{Range@Length[a=#],Reverse@a}]&,{1,0},#]&


Try it online!

# Husk, 10 bytes

mΣ¡oṘN↔;2


Try it online!

Prints the infinite sequence. If you let it time out, you can see upto 11 terms.

## Explanation

mΣ¡oṘN↔;2
¡o       create the next iteration by
↔   reversing it
Ṙ     and replicating each element(flipped arg)
N    times each element in the natural numbers
mΣ         map each list to its sum


# JavaScript (Node.js), 110 bytes

n=6;a=;for(;n-->0;a=a.reverse().reduce((v,e,i)=>v.concat(Array(e*1).fill(i+1)),[]));console.log(a.join(""))


Try it online!

Set n at the start to change which element of the sequence is calculated.

Unfortunately, this is a rather long answer, due to JavaScript's wordy array operator functions.

• Nice! You could include the tio link. Apr 4, 2021 at 12:13
• @math done, thanks for this problem :) Apr 4, 2021 at 12:16
• @jumpbot Just as a recommendation, you could learn Japt if you want. (And if you don't know it yet) Apr 4, 2021 at 12:20
• @math call me a traditionalist, but golfing languages feel a bit like cheating to me (: Apr 4, 2021 at 12:22
• @jumpbot Yeah, I just want to learn them because they see hard to do so. Apr 4, 2021 at 12:24

# Python 2, 82 bytes

x=
exec'x=sum([v*[i]for i,v in enumerate(x[::-1],1)],[]);'*input()
print sum(x)


Prints the nth, 0-indexed, term.

Try it online!

Others at 82:

x=
exec'i=1;x=x[::-1];exec"x+=x.pop(0)*[i];i+=1;"*len(x);'*input()
print sum(x)

x=
exec'i=1;exec"x=x.pop()*[i]+x;i+=1;"*len(x);x=x[::-1];'*input()
print sum(x)

x=2,
exec'x=sum([v*(i,)for i,v in enumerate(x[::-1],1)],());'*input()
print sum(x)


# JavaScript (ES6), 81 bytes

Returns the $$\n\$$-th term, 0-indexed.

f=(n,a=)=>a.map(k=>A=n?[...Array(k).fill(++i),...A]:+A+k,i=A=[])&&n?f(n-1,A):A


Try it online!

### Commented

f = (               // f is a recursive function taking:
n,                //   n = input
a =            //   a[] = Levine sequence
) =>                //
a.map(k =>          // for each value k in a[]:
A =               //   compute A, which is either the updated Levine sequence
//   or the sum of the terms of the last sequence if this is
//   the last iteration:
n ?             //     if n is not equal to 0:
[ ...Array(k) //       build an array consisting of k entries
.fill(++i), //       equal to i (which is first incremented)
...A        //       followed by the existing entries in A[]
]             //
:               //     else:
+A + k,       //       coerce A to a number and add k
i = A = []        //   start with i = A = []
)                   // end of map()
&& n ?              // if n is not equal to 0:
f(n - 1, A)       //   do a recursive call with n - 1 and a[] = A[]
:                   // else:
A                 //   we're done: return A

• +1 Nice footer too! But can't vote anymore. (mainly because I wanted the badge) :P Apr 4, 2021 at 17:34

• -2 bytes thanks to kops.
sum<$>iterate(!1) (x:y)!n=y!(n+1)++(n<$[1..x])
e!_=e


Try it online!

The whole Levine sequence.

• Sorry, can't upvote anymore ;-). Apr 4, 2021 at 15:56
• -2 bytes by avoiding length and using an auxiliary variable instead. Here the generated lists are reversed but that doesn't matter once we take sums.
– kops
Apr 4, 2021 at 20:36

# APL (Dyalog Unicode), 2̶3̶ 2̶2̶ 21 bytes

-1 thanks to @Razetime
-1 thanks to @User

+/{×⍵:/∘⍳∘⍴⍨⌽∇⍵-1⋄,2}
+/ ⍝ summation
×⍵: ⍝ conditional
/∘⍳∘⍴⍨ ⍝ expand range 0 to length of L(n-1) inclusive
⌽∇⍵-1 ⍝ reverse L(n-1)
⋄ ⍝ statement separator (effectively an else clause)
,2 ⍝ return value


Try it online!

• /∘(⍳⍴)/∘⍳∘⍴ Apr 6, 2021 at 6:46
• Thanks, I'm still struggling with the rules of function composition and trains. 👍 Apr 6, 2021 at 14:54
• You can save a byte by using ×⍵ and switching the guard bodies.
– user
Apr 9, 2021 at 20:44
• @user Oh, wow. I didn't know about ×⍵. Thanks! Apr 9, 2021 at 22:11

# 05AB1E, 15 bytes

1‚¸λRεN>yи}˜}εθ


Try it online!

prints the whole sequence forever

1     pushes 1 to the stack
‚     because there is no input, pairs 1 with itself, pushing [1, 1]
¸     listify, pushing [[1,1]]
λ     recursive environment, with [1, 1] as the base case
R    reverse the implicit last value
ε    and map each element to
N>  index + 1
y   that element
и   repeated, pushes index + 1 repeated the element
}
˜    flatten, to a flat list
}
ε     and for each such list
θ     take the last element


# Factor, 68 bytes

[ { 2 } swap [ reverse [ 1 + <array> ] map-index concat ] times Σ ]


Try it online!

## Explanation:

It's a quotation (anonymous function) that takes an integer from the data stack as input and puts an integer (the nth term of the Levine sequence) on the data stack as output. Assuming 4 is on top of the stack when this quotation is called...

• { 2 } Push a sequence to the stack containing one element, 2.

Stack: 4 { 2 }

• swap Swap two objects (because times needs access to the 4 later).

Stack: { 2 } 4

• [ reverse [ 1 + <array> ] map-index concat ] Push a quotation for times to use later. This is a quotation that produces the next row of the Levine's Triangle from the previous one.

Stack: { 2 } 4 [ reverse [ 1 + <array> ] map-index concat ]

• times Call a quotation a certain number of times. Inside the quotation now for the first iteration...

Stack: { 2 }

• reverse Reverse a sequence.

Stack: { 2 }

• [ 1 + <array> ] Push a quotation for map-index to use later.

Stack: { 2 } [ 1 + <array> ]

• map-index Take a sequence and a quotation and apply the quotation to each element of the sequence, collecting the results into a new sequence of the same length. However, it also places the index of the element on top of the stack. Inside the quotation now for the first iteration...

Stack: 2 0

• 1 Push 1.

Stack: 2 0 1

• + Add.

Stack: 2 1

• <array> Create an array from a count and an element.

Stack: { 1 1 }

• Now map-index has exhausted its elements. Since we are mapping numbers to arrays, the result will be an array of arrays.

Stack: { { 1 1 } }

• concat Concatenate a sequence of sequences together into one sequence.

Stack: { 1 1 }

• Now we have produced the second row of Levine's Triangle. times will run the quotation three more times...

Stack: { 1 1 2 3 }

• Σ Sum a sequence.

Stack: 7

# Python 3, 316 bytes

print(*[11,12,112,1123],sep="\n");n="11|2|3";x=2;t="";j=0
while 1:
for y,z in enumerate(''.join([str(w)[::-1] for w in n.split("|")[1:][::-1]])):
t+=str(y+1)*int(z)
if j==0:t+="|"
j+=1;k=y+2
n=t+''.join(map(lambda z:'|'+str(z),list(range(k,k+(len(n)-len(n.lstrip('1')))))))
print(n.replace("|",""));t="";j=0


Try it online!

In one word, horrible

• No, 4 words: horrible but good work. ;) Apr 4, 2021 at 14:09
• It's meant to print the sum. That was, unfortunately, missing from the description when you wrote this. Apr 4, 2021 at 15:39

# Charcoal, 29 bytes

⊞υ²ＦＮ«≔⟦⟧θＦＬυＦ§⮌υκ⊞θ⊕κ≔θυ»ＩΣυ


Try it online! Link is to verbose version of code. 0-indexed, I think? Explanation:

⊞υ²


Start with .

ＦＮ«


Repeat n times.

≔⟦⟧θ


Start a new list.

ＦＬυ


Iterate up to the length of the previous list.

Ｆ§⮌υκ


Repeat according to the value in the reversed list.

⊞θ⊕κ


Push the next integer to the list.

≔θυ


Copy the new list to the previous list.

»ＩΣυ


Print the final sum.

# JavaScript (Node.js), 76 bytes

function that take n and output A[n]

f=(n,a=,q=a.length)=>n?f(n-1,a.flatMap(n=>Array(a[--q]).fill(++i),i=0)):q


Try it online!

# JavaScript (Node.js), 77 bytes

output all A[i]

for(a=;;a=a.flatMap(n=>Array(a[--q]).fill(i++)))i=!console.log(q=a.length)


Try it online!

# Pyth, 28 bytes

J[2)W1K_JsK=JYFklK=+J*@Kk[hk


Try it online!

Prints the infinite sequence.

# Explanation

J[2)      # Initialize J to 
W1        # While 1...
K_J       # Initialize K to reverse of J
sK        # Print the sum of elements of K
=JY       # Y is an empty list by default. Set J to it.
FklK      # For loop from 0 till length of K, with iterator as k
@Kk       # k'th element of K
[hK       # A list containing only k+1
*         # Repeats the sequence specified number of times.
=+J       # Append that to J.


# Scala 3, 84 bytes

Seq.iterate(Seq(2),_){s=>s.reverse.zip(1 to s.sum)flatMap(Seq.fill(_)(_))}map(_.sum)


Try it in Scastie!

Outputs the first n items.

## Infinite list + nth element, 85 bytes

Stream.iterate(Seq(2)){s=>s.reverse.zip(1 to s.sum)flatMap(Seq.fill(_)(_))}map(_.sum)
`

Try it in Scastie!

Here is an infinite Stream that also acts as a function giving the nth element, but it's a byte longer.