17
\$\begingroup\$

Goal

Write a program that outputs this list: 0, 1, 1, 0, 2, 2, 2, 0, 3, 2, 4, 1, 1, 0, 4, 4, 4, 1, 4, 0, 5, 5, 4, 1, 6, 2, 1, 0, 6, 7, 5, 1, 6, 3, 3, 1, 0, 7, 9, 5, 3, 6, 4, 4, 2, 0, 8, 9, 6, 4, 9, 4, 5, 2, 1, 3, 0, 9, 10, 7, 5, 10, 6, 6, 3, 1, 4, 2, 0, 10, 11, 8, 6, 11, 6, 9, 3, 2, 5, 3, 2, 0, 11, 11, 10, 8, 11, 7, 9, 4, 3, 6, 4, 5, 0, 12, 11, 10, 9, 13, 8, 10, 4, 4, 7, 6, 6, 1, 1, 0, 13, 13, 10, 9, 15, 8, 12, 5, 5, 8, 7, 6, 2, 3, 0, 14, 13, 11, 10, 15, 10, 13, 6, 6, 8, 9, 7, 2, 5, 1, 2, 0, 15, 14, 13, 10, 15, 11, 15, 7, 7, 9, 10, 8, 2, 6, 2, 5, 0, 16, 14, 15, 10, 15, 12, 16, 9, 8, 11, 12, 9, 4, 6, 3, 7, 2, 0, 17, 14, 16, 11, 16, 12, 17, 10, 9, 13, 13, 10, 5, 8, 4, 7, 4, 2, 0, 18, 14, 17, 11, 18, 13, 17, 11, 10, 13, 15, 12, 6, 10, 5, 8, 4, 4, 2, 0, 19, 14, 18, 11, 20, 14, 18, 11, 11, 13, 16, 15, 6, 11, 7, 9, 5, 4, 4, 1, 1, 0, 20, 16, 18, 11, 22, 15, 19, 12, 11, 14, 16, 18 ...

This is the inventory sequence (OEIS A342585).

Description

The inventory sequence is generated by:

  1. Setting the index to 0
  2. Print how many times a value equal to the current index was already printed.
  3. If the last printed number was 0, go back to 1.
  4. If the last printed number was not 0, increment the index and go back to 2.

Example Code

Ungolfed Python

#!/usr/bin/env python3

index=0
alreadyPrinted=[] #List of all numbers we already printed. One element per print

while True:
  nextNumber = alreadyPrinted.count(index) #How many times did we print a value equal to index?
  print(nextNumber,end=' ') 
  alreadyPrinted.append(nextNumber)        #Keep track of all printed numbers
  if nextNumber==0:
    index=0
    print() #Just to add a newline for a nicer looking output, not required
  else:
    index = index+1
    

Rules

  1. Shortest code wins.
  2. Print at least 250 correct numbers of the sequence, in the correct order from the start of the sequence (obviously).
  3. Printing more (numbers) after that is allowed, they don't have to be correct.
  4. If you want it, you can expect a number input for the amount of numbers you have to print. But then the output has to stop at the correct time and you have to support an input of up to 65'000 (all have to be correct).
\$\endgroup\$
6
  • 8
    \$\begingroup\$ Re "Print at least 250 correct numbers of the sequenece, in the correct order from the start of the sequence" - we have some default sequence rules - see here, they are probably favourable to your listed rules and most will probably assume they are all acceptable (since there is no reason to override them for this challenge). \$\endgroup\$ Commented Jun 4 at 16:28
  • \$\begingroup\$ @JonathanAllan I don't see a Start at the beginning requirement in the link. \$\endgroup\$ Commented Jun 4 at 17:21
  • 2
    \$\begingroup\$ "all entries up to" implies "from the beginning". The default rules also allow us to take the number of terms required as an input, or just to implement something that outputs a requested term. \$\endgroup\$ Commented Jun 4 at 17:25
  • 3
    \$\begingroup\$ For situations where no index is given, it does emphasize _all_ entries, which obviously implies "from the beginning". \$\endgroup\$
    – Arnauld
    Commented Jun 4 at 17:59
  • 4
    \$\begingroup\$ This is very similar to code.golf/inventory-sequence, they might not want public answers to it \$\endgroup\$
    – xnor
    Commented Jun 4 at 21:00

18 Answers 18

6
\$\begingroup\$

Jelly, 10 bytes

Ṛi0’ċ@ṭµ¡Ḋ

Try it online!

A monadic Link accepting the number of terms, N, to produce and yielding a list of the first N terms.

How?

Ṛi0’ċ@ṭµ¡Ḋ - Link: non-negative integer, N
        ¡  - repeat this N times (do it N+1 times):
       µ   -   monadic chain - f(A=current list or the initial integer, N):
Ṛ          -     reverse A (N becomes [N])
 i0        -     first 1-indexed index of zero in that; 0 if not found
   ’       -     decrement that
    ċ@     -     count occurrences in A
      ṭ    -     tack that to A (ready for the next iteration)
         Ḋ - dequeue (remove the leading N)

Note that leading \$N\$ is guaranteed to never be counted due to it simply being too large (we only have that number of terms on the final iteration however, the list at that point starts N, 0 so the only edge case to check is \$N=1\$).

\$\endgroup\$
5
\$\begingroup\$

><> (Fish), 24 bytes

5:1g:n::1g1+$1p0):@*+ao!

Hover over any symbol to see what it does

Unformatted:

5:1g:n::1g1+$1p0):@*+ao!

Try it

\$\endgroup\$
4
\$\begingroup\$

JavaScript (V8), 47 bytes

A full program that prints the sequence indefinitely.

for(o=[v=0];;o[v]=-~o[v])print(v=~~o[n=v&&n+1])

Try it online!

Commented

for(            // loop:
  o = [         //   o = object to count how many times
                //       each value was printed
    v = 0       //   v = last printed value
  ];            //
  ;             //   no stop condition (loop forever)
  o[v] = -~o[v] //   increment o[v] after each iteration
)               //
  print(        //   print:
    v = ~~o[    //     the new value v = o[n]
      n = v &&  //     where n is set to 0 if v = 0
          n + 1 //     or incremented otherwise
    ]           //
  )             //
\$\endgroup\$
4
\$\begingroup\$

Google Sheets, 90 bytes

=LET(R,LAMBDA(R,l,v,i,LET(c,COUNTIF(l,v),IF(i=250,l,R(R,{l;c},(c>0)*(v+1),i+1)))),R(R,,,))

Commented

=LET(
   R,LAMBDA(R,l,v,i,        // define a recursive function R(R,l,v,i) where `l` is the list, `v` is the current value and `i` is the current iteration
     LET(c,COUNTIF(l,v),    // assign to `c` the count of the current value `v` in the list of values `l`
        IF(i=250,           // base case: if we reached 250 iterations... 
           l,               // ...return the list
           R(R,             // recursive case: execute the function R(R,l,v,i)... 
            {l;c},          // ...where the new list is `c` appended to `l`, 
            (c>0)*(v+1),    // the new value is 0 if the count is 0 or incremented by 1 otherwise, 
            i+1)))),        // the new iteration is the current iteration + 1
   R(R,,,))                 // execute the function
\$\endgroup\$
4
\$\begingroup\$

Ruby, 44 38 bytes

$*<<B while$_=0<(B=p$*.count$_)?$_+1:0

Try it online!

  • thanks to @Dingus for saving 6 Bytes
\$\endgroup\$
0
4
\$\begingroup\$

05AB1E, 11 7 bytes

0λλÂ0k¢

-4 bytes porting @JonathanAllan's Jelly approach, so make sure to upvote that answer as well!

Outputs the infinite sequence.

Try it online.

Original 11 bytes approach:

0λλ¾¢¼D_i.µ

Outputs the infinite sequence.

Try it online.

Explanation:

 λ          # Start a recursive environment,
            # to calculate the infinite sequence
0           # Starting with a(0)=0
            # Where every following a(n) is calculated as:
  λ         #  Push all terms thus far: [a(0),a(1),...,a(n-1)]
   Â        #  Bifurcate it; short for Duplicate & Reverse copy
    0k      #  Pop and get the first 0-based index of item 0 in this reversed copy
      ¢     #  Count how many times this index occurs in the terms thus far
   
 λ          # Start a recursive environment,
            # to calculate the infinite sequence
0           # Starting with a(0)=0
            # Where every following a(n) is calculated as:
  λ         #  Push all terms thus far: [a(0),a(1),...,a(n-1)]
   ¾¢       #  Count how many times the counter variable `¾` occurs in it
            #  (`¾` starts at 0 by default)
     ¼      #  Increase the counter variable `¾` by 1 for the next iteration
     D      #  Duplicate this count
      _i    #  Pop the copy, and if it's 0:
        .µ  #   Reset counter variable `¾` back to 0 for the next iteration
\$\endgroup\$
1
  • 1
    \$\begingroup\$ 0-indexing FTW! \$\endgroup\$
    – Neil
    Commented Jun 6 at 6:59
4
\$\begingroup\$

R (lower than version 4.1), 50 bytes

p={}
repeat F="if"(p<-c(print(sum(p==F)),p),F+1,0)

Try it online!

Prints indefinitely (or until R runs out of memory). p would contain the printed values in reverse, since if defaults to take the first element as its condition (with a warning), in versions 4.1 and lower.

R, 67 bytes

function(n,p={})for(i in 1:n)F="if"(p<-c(print(sum(p==F)),p),F+1,0)

Try it online!

Function version that prints out the first \$n\$ terms.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ I swear I haven't seen your solution! \$\endgroup\$ Commented Jun 4 at 19:48
  • 1
    \$\begingroup\$ Note that this works only in older versions of R (up to 4.1) - newer version error on condition with length > 1. \$\endgroup\$
    – pajonk
    Commented Jun 5 at 18:33
  • \$\begingroup\$ @pajonk oh yeaaah I knew that but forgot. I'll make a note! \$\endgroup\$
    – Giuseppe
    Commented Jun 5 at 18:38
4
\$\begingroup\$

Brainfuck, 135 Byte

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

Some Notes:

  • It uses negative addresses. Not all interpreter and compilers accept that. If that is not acceptable, add >>>>> (not sure how many you exaclty need) at the beginning.
  • With 8 bit cells only the first 285 are correct. With larger cells, more values will be correct. With infinite large cells and a infinite amount of cells, it should print infinite correct values.
  • It outputs it as raw integers. Don't expect any ASCII values.

Explanation

The cells are combined to blocks or structs of 5 Cells. Similar to a C array of struct with 5 members per struct. Each struct has this Members.

  • Member 0, moveData: Used to move data from one struct to struct 0 and to move M struct's forward (where M is the number we last printed). So we increase the counter in the correct struct
  • Member 1, temp: Used to temporarely copy data to. To be able to copy data from one cell to a other and then restoring the source.
  • Member 2, counter: How many times we printed N (Where N is struct index we are currently on).
  • Member 3, structPrinted: Is set when we start printing the number of the current struct. Cleared after we printed 0.
  • Member 4, useThisStruct: Set in all used struct's. Used to find struct 0. This value is incrementd multiple time but never decremented (to reduce code), with a limited cell size, this means that this will overflow and generate wrong values (reason for the 285 limit with 8 bit cells).

Note, we start with Member 4, useThisStruct. This means we use negative offests and the cell index doesn't align with the struct's.

+  Set useThisStruct since we use struct 0

[ "Infinite" loop; useThisStruct of struct 0 should be non 0

    <+ Set structPrinted since we are about to print the value
    <[ Loop we run till the next value we should print is 0
        .   Print counter of the current struct
        
        [-<+<+>>]<[->+<] Copy counter to moveData while using temp to restore counter after copying

        <<[>[-<<<<<+>>>>>]<<<<<<] Move the value of moveData of the current struct to moveData of struct at Index 0

        >[[->>>>>+<<<<<]>>>>>>>>>+<<<<-] Move to struct at index moveData
        >>+ Increase the counter in this block

        <<<[<<<<<] Move back to struct 0
        >>>>[>>>>>] Move to the next struct we should print
        + Set structPrinted since we are about to print the value
    <] Loop till counter is 0


    .  Print counter which is 0
    <<<[>>>>-<<<<<<<<<]>>>+ Go back to struct 0 and reset structPrinted in every struct
    >-> Set counter in struct 0 to 1

]

Previous versions

137 Byte

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

144 Byte version

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

180 Byte version

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

202 Byte version

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

211 Byte Version

+<+[>>>>+<[.>>[-]<<[-<+>>>+<<]<[->+<]<<<<<<[>>>>[-]>>>>>[-<<<<<+>>>>>]<<<<<<<<<<<<<<]>>>>>>>>>[>>>>>[-]<<<<<[->>>>>+<<<<<]>+>>>>-]<<+<<<<<<<[<<<<<]>>>>>>>>[>>>>>]+<].<<<<<<<[>>>>>>>>-<<<<<<<<<<<<<]>>>>>>>>-<+<<<]
\$\endgroup\$
3
\$\begingroup\$

Python 3.8 (pre-release), 54 bytes

i,*a=0,
while[print(x:=a.count(i))]:i,*a=x and-~i,*a,x

Try it online!

Full program that prints indefinitely


Python 3.8 (pre-release), 52 bytes

a=[i:=0]*99
while[print(x:=a[i])]:i=x and-~i;a[x]+=1

Try it online!

Full program that prints the first 2974 entries and then halts

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Just came to post the 52 (except I was going to use 23 to print only 265). \$\endgroup\$ Commented Jun 5 at 23:21
3
\$\begingroup\$

Perl 5, 45 bytes

{{$a[$_=$a[$i++]|0]++;say;$_&&redo}$i=0;redo}

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ This is a great approach, I can't come up with a better alternative! But, with a big of juggling you can drop the second redo and the inner {...}s: Try it online! If you add -n0513 you can drop the other {...} too but that might be a stretch for -2! Great solution though! \$\endgroup\$ Commented Jun 7 at 15:39
  • \$\begingroup\$ Alternatively, one more byte using -n0513 to have while$ at the end, but again might be too much flag abuse! Try it online! and still not as short as redo: Try it online! \$\endgroup\$ Commented Jun 7 at 15:46
3
\$\begingroup\$

R, 56 52 bytes

N={};repeat{show(x<-sum(F==N));N=c(N,x);F=(F+1)*!!x}

Attempt This Online!

R, 60 56 52 bytes

  • -4 bytes thanks to the pajonk's suggestion
`?`=\(F,N){show(x<-sum(F==N));(F+1)*!!x?c(N,x)};0?{}

Attempt This Online!

Edit: -4 bytes were removed in both cases by teplacing an if with an arithmetical expression. The old code is still available and linked to the respective byte count.

Here are two full programs: the first one runs a forever loop (repeat conveniently requires no arguments for that) and another one is based on a recursive function without an exit condition.

  • For the sequence elements the constant F is used, which has been set to FALSE (==0) by default

  • The number of occurences is calculated inside of the show as a sum of booleans

  • In the last statement F becomes 0 or adds 1.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ funny that print is shorter than show here; it usually isn't, but the invisible return from print is pretty handy. \$\endgroup\$
    – Giuseppe
    Commented Jun 4 at 20:13
  • \$\begingroup\$ I think in the first solution you should include the function call in the byte-count (ATO), because only after calling the function with specific parameters it answers the problem, but I will be happy to be convinced otherwise. \$\endgroup\$
    – pajonk
    Commented Jun 5 at 18:29
  • \$\begingroup\$ Anyway, renaming f to ? should save one byte. \$\endgroup\$
    – pajonk
    Commented Jun 5 at 19:40
  • \$\begingroup\$ @pajonk thanks for the ? - turned out that the full program has the same length as the function ('?'=\(F=0,N={}){show(x<-sum(F==N));(F+1)*!!x?c(N,x)}) \$\endgroup\$ Commented Jun 6 at 7:33
3
\$\begingroup\$

Bash, 53 bytes

-21 bytes by @12431234123412341234123 and myself:

By removing the loop condition (and run infinitely, which I had feelings about), I also get to use for instead of while, which means i get to use {} instead of do...done.
I also get to remove the i=0 assignment.
Separately, i get to remove :>a (which creates the file) by using tee to create the file.
The remaining byte save is simple golfing like avoiding assigning a variable and instead using tthe output of grep directly.

-7 bytes by @12431234123412341234123 by using grep -w instead of grep ^$i$, and by using recursive functions instead of a for loop

-1 byte by me by using <1 instead of ==0

0()(((`grep -wc $i a|tee -a a`<1))&&i=0||let i++
0);0

Attempt This Online!

Previous Version

Previous Previous Version

explanation:

0()(                                                 #declare a function named "0"
       grep -wc $i a                                 #find and count all instances of our index in file "a"
                    |tee -a a                        #copy standard output and append it to file "a"
    ((`                      `<1))                   #test if standard output of previous is ==0 (since we never have negative numbers, <1 is equivalent to ==0).
                                   &&i=0||let i++    #if so, i=0, increment otherwise
0                                                    #call function "0", looping infinitely
 );0                                                 #end function declaration, then call 0 the first time.

use as a function body or script, runs infinitely. outputs to a file named "a" in the current directory.

I've verified the first 85 elements (this is what OEIS stores) are correct, but I don't see why it wouldn't keep being correct.

\$\endgroup\$
4
  • \$\begingroup\$ >a;i=0;while :;do c=`grep -wc $i a|tee -a a`;(($c==0))&&i=0||let i++;done? \$\endgroup\$ Commented Jun 5 at 15:30
  • \$\begingroup\$ yes, that crossed my mind. I had feelings about having no stop condition, but actually the benefits far outweigh my feelings. \$\endgroup\$ Commented Jun 5 at 15:35
  • \$\begingroup\$ >a;0(){ i=0;while :;do c=`grep -wc $i a|tee -a a`;$c||let i++;done;};0 \$\endgroup\$ Commented Jun 5 at 15:52
  • \$\begingroup\$ was in the middle of it, sorry. nice catch on grep -w though! \$\endgroup\$ Commented Jun 5 at 16:06
2
\$\begingroup\$

PowerShell Core, 44 bytes

for($s=@{}){($l=+$s.($i=++$i*!!$l))
$s.$l++}

Try it online!

Outputs the sequence indefinitely

for($s=@{}){   # Main loop, initialises the inventory `$s` to an empty object
($l=+$s.+$i)   # Get the state of the inventory at the current index `$i`, print and store in `$l`
$s.$l++        # Increment the inventory for the last printed value
$i=++$i*!!$l}  # if the last printed number `$l` was 0, reset the index to 0, increment it otherwise
\$\endgroup\$
2
\$\begingroup\$

Charcoal, 12 bytes

FN⊞υ№υ⌕⮌υ⁰Iυ

Try it online! Link is to verbose version of code. Outputs the first N terms. Explanation: Port of @JonathanAllan's Jelly answer. Explanation:

FN

Repeat N times.

⊞υ№υ⌕⮌υ⁰

Find the position of 0 in the reversed list so far, and push the count of that position in the list to the list.

Iυ

Output the final list.

\$\endgroup\$
2
\$\begingroup\$

Uiua, 42 37 chars, 72 59 bytes

◌:∧(⊂:⟜(:⟨-.:|+1:⟩±)/+=,,°□◌)⇡250□[]0

Try it

I've literally never written program in Uiua before so it's probably nowhere near efficient.

\$\endgroup\$
2
\$\begingroup\$

Haskell, 60 bytes

g[]0
g a i|let c=sum[1|x<-a,x==i]=c:g(c:a)(last$0:[i+1|c>0])

Prints the sequence indefinitely.

Attempt This Online!

\$\endgroup\$
2
\$\begingroup\$

Retina 0.8.2, 65 bytes

.+
$*_
smr{1`(^0((¶)|.)*?¶)?_
$1$#3¶_
(((^\4$)|.)*)(\d+)¶_
$1$#3¶

Try it online! Outputs the first N terms. Explanation:

.+
$*_

Convert the input to unary, but using _ instead of the default 1, which would otherwise be confusing.

smr`

Process the rest of the script in single-line (. matches newlines), multiline (^$ match on each line) and right-to-left (regex starts matching at the end of the output buffer and works backwards) modes.

{`

Repeat until N is reduced to zero.

1`(^0((¶)|.)*?¶)?_
$1$#3¶_

Append the offset of the last appearance of 0 on its own line. (A $ isn't needed here because 0 is the only non-negative integer that begins with 0.) The extra 1`(...¶)? seems to be the golfiest way to deal with the edge case of the first pass through the loop.

(((^\4$)|.)*)(\d+)¶_
$1$#3¶

Count the number of times that the offset has already appeared in the sequence, replace the offset with that count, and decrement N.

\$\endgroup\$
0
\$\begingroup\$

Python 3, 59 bytes

i=0;a=[0]*99
while 1:print(n:=a[i]);a[n]+=1;i=[i+1,0][n==0]

This is a mostly straightforward golfing of OP's program, with i = index, n = nextNumber, and a[i] being the number of times i has already been printed.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.