(Challenge taken from a multiplayer game (clash of code) at codingame.com)

The challenge

Find the n-th term of the following sequence: 1, 1, 2, 1, 2, 3, 1, 2, 3, 4... or to make it more appearing {1}, {1,2}, {1,2,3}, {1,2,3,4}...

The sequence is made up from concatenated ranges from 1 to x, starting from 1, all the way up to infinity.

Rules / IO

Input and output can be in any format, as long as it's distinguishable. Input can be taken from any appropriate source -> STDIN, file, etc...

The input can be 0- or 1 indexed, and the selected indexing must be mentioned in the post.

This is code-golf so the shortest byte count wins!

Test cases (0-based indexing)

0 -> 1
1 -> 1
5 -> 3
10 -> 1
59 -> 5
100 -> 10
1001 -> 12
share|improve this question
8  
OEIS – Gurupad Mamadapur 16 hours ago
2  
You should probably add a few more larger test cases (59, 100, etc) – FlipTack 15 hours ago
    
@FlipTack Added a few. – TuukkaX 13 hours ago

27 Answers 27

Haskell, 27 bytes

(concat[[1..k]|k<-[1..]]!!)

Try it online!

This is an anonymous function, creating the infinite sequence an just returning the n-th element thereof: [[1..k]| k<-[1..]] produces an infinite list of list: [[1],[1,2],[1,2,3],[1,2,3,4],...]. The concat just joins all those lists to [1,1,2,1,2,3,1,2,3,4,...] and finally (...!!) accepts the input n (pointless notation) and returns the n-th term (0-based).

share|improve this answer
    
Replacing concat with more comprehension only saves 1 byte: ([z|k<-[1..],z<-[1..k]]!!). – Dan D. 3 hours ago

Octave, 39 bytes

@(z)z-(n=ceil((8*z+1)^.5/2-.5))*(n-1)/2

1- based index

Explanation:

Consider this sequence:

1   1   2   1   2   3   1   2   3   4   1   2   3   4   5

if we count number of element of subsequences we have

1   2        3          4               5         

so using Gauss formula for triangular number we can form a formula for z:

z=n*(n+1)/2

that is a quadratic equation if we solve it for n we have

n=(sqrt(8*z+1)-1)/2

Try It Online!

share|improve this answer

Octave, 39 bytes

@(n){v=1:n,A=triu(v'+0*v),A(A>0)(n)}{3}

Try it online!

This uses an alternative approach.

For e.g. n=1 this A=triu(v'+0*v) creates the matrix

1   1   1   1
0   2   2   2
0   0   3   3
0   0   0   4

When removing all the zero elements and appending the columns by A(A>0) we get the sequence:

1   1  2  1  2  3  1  2  3  4

Then it is just a matter of exctracting the n-th term of that sequence.

share|improve this answer

JavaScript, 29 28 bytes

-1 byte thanks to Arnauld!

f=(n,m)=>n++<m?n:f(n+~m,-~m)

Uses the 0-indexed recursive formula found on OEIS.

When called with 1 argument as expected, the default value of the second, m, will be undefined. However, -~undefined, returns 1, which allows us to get the recursion rolling without an explicit m = 1 in the argument list (thanks @Arnauld!)

Test snippet:

f=(n,m)=>n++<m?n:f(n+~m,-~m)

let examples = [0, 1, 5, 10, 15, 1000];

examples.forEach(function log(x) {
    console.log(x, " => ", f(x))
});

share|improve this answer

Haskell, 25 24 bytes

(!!)$[1..]>>= \x->[1..x]

Usage example: ((!!)$[1..]>>= \x->[1..x]) 10 -> 1.

Maps the anonymous make-a-list-from-1-to-x function \x->[1..x] (the built-in enumFromTo 1 is one byte longer) to the infinite list [1..] and concatenates the resulting lists into a single list. !! picks the nth element.

Thanks to @flawr for one byte.

share|improve this answer
    
I think you could shorten it by using (!!)$[1..]>>= \x->[1..x]. Sometimes I really wish there was a shorter pointless way of writing \x->[1..x] :) – flawr 14 hours ago
    
PS: Why don't you add a Try it online! link? – flawr 14 hours ago
    
@flawr: Well spotted, thanks! Try it online uses an old version of ghc (or Prelude) and most of answers use <$> which isn't in scope. Do you know any online Haskell compiler/interpreter that uses the newest version? haskell.org only allows expressions and you cannot create links to code you've entered. – nimi 14 hours ago
1  
Ah, let me tell @Dennis to update it, he is the creator of TIO :) – flawr 14 hours ago

Python, 39 36 bytes

-3 bytes thanks to Dennis!

A recursive lambda which uses 1-based indexing.

f=lambda n,m=1:n*(n<=m)or f(n-m,m+1)

Try it online!

We keep track of the current "rise" size using m. If n is smaller than or equal to m, it fits within the current "rise", and so we return it. However, if it's larger than m, we take m away from it, than add 1 to m and call the function recursively (moving on to the next rise).

share|improve this answer

Pyke, 6 bytes

OmSsQ@

Try it here!

O      -    input+2
 mS    -   map(range(1,i+1), range(^))
   s   -  sum(^)
    Q@ - ^[input]

0-indexed.

share|improve this answer

Jelly, 5 bytes, 1-indexed

RRF³ị

Try it online!

Explanation (assume input is 4)

R      Generate a list of 1 to N      [1, 2, 3, 4]
 R     Generate a new list for each item on the previous list, with that item as N
                                      [[1], [1,2], ...]
  F    Flatten that list              [1, 1, 2, 1, 2, 3 ...]
   ³ị  Get the input number (³) and return the item at that index of the list. 
       This is one-based:             [1, 1, 2, 1, 2, 3 ...] 
                                                ^
share|improve this answer

Pyth, 6 5 bytes

1 byte saved thanks to @TheBikingviking!

@s._S

This uses 0-based indexing.

Try it online!

Explanation

@          Index with implicit input into
   ._      all prefixes of
     S     1-based range of implicit input
 s         concatenated into an un-nested list
share|improve this answer
    
Nice! You can replace .n with s. – TheBikingViking 12 hours ago
    
@TheBikingViking Thanks! – Luis Mendo 12 hours ago

R, 43 41 bytes

Edit: Found a shorter recursive approach by using A002262 + 1 (0 indexed):

f=function(n,m=1)`if`(n<m,n+1,f(n-m,m+1))

Old version:

n=scan();n-choose(floor((1+sqrt(8*n))/2),2)

1-indexed formula from OEIS.

share|improve this answer
    
Try It Online! It seems to work just fine. :) – R. Kap 6 hours ago

Perl 6, 21 bytes

{map(|^*,^∞)[$_]+1}

0-indexed. Try it online!

How it works:

{                 }  # A lambda.
         ^∞          # Range from 0 to Inf-1. (Same byte count as 0..*, but cooler.)
 map( ^*,  )         # Map each number n to the range 0..(n-1),
     |               # And slip each range into the outer list.
            [$_]     # Index the sequence with the lambda argument.
                +1   # Add 1.

Perl 6, 21 bytes

{[\,](1..*).flat[$_]}

0-indexed. Try it online!

How it works:

{                   }  # A lambda.
      1..*             # Range from 1 to infinity.
 [ ,](    )            # Fold it with the comma operator,
  \                    # and return all intermediate results, e.g. (1), (1,2), (1,2,3)...
           .flat       # Flatten the sequence.
                [$_]   # Index it with the lambda argument.
share|improve this answer

Mathematica, 27 24 bytes

Thanks @MartinEnder for 3 bytes!

((r=Range)@r@#<>1)[[#]]&

1-indexed. This throws errors that are safe to ignore.

Explanation

((r=Range)@r@#<>1)[[#]]&
  r=Range                 (* Store Range function in r *)
           r@#            (* Create list {1..n} *)
 (r      )@               (* For each element, generate {1..n} *)
              <>1         (* Join the lists and append a 1; throws errors *)
(                )[[#]]&  (* Take the nth element *)
share|improve this answer
1  
Join@@ is way too expensive ;) ((r=Range)@r@#<>1)[[#]]& – Martin Ender 14 hours ago
    
@MartinEnder Woah, abusing the fact that StringJoin is not evaluated... I like it – JungHwan Min 12 hours ago

Brain-Flak, 46 bytes

Zero indexed

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

Try it online!

Stack Clean, 48 bytes

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

Try it online!

Explanation

This is a modified version of the modulo function. Instead of using a constant number as the divisor it increments the divisor for each time the divisor is subtracted from it (once per outside loop iteration).

Annotated Code

(<>())       # Switch to the opposite stack and push 1 (the initial divisor)
{            # (outside loop) While top of stack is not 0...
  (          # Push...
    ({}())   # Push the divisor plus 1
  [()])      # ...minus one (ie push a copy of the original divisor
  {          # (inner loop) While the top of stack does not equal zero
    ({}[()]) # Decrement the top of the active stack
    <>       # Switch stacks
  }{}        # (inside loop) End loop and pop zero off the top of stack)
}            # (outside loop) End loop
<>           # Switch stacks (to the one with the divisor)
([{}()]{})   # Calculate the result
share|improve this answer

05AB1E, 5 bytes

The program is 0-indexed, code:

ÌLL¹è

Explanation:

Ì       # Double increment the input
 LL     # List of list on the input
   ¹è   # Get nth element

Uses the CP-1252 encoding. Try it online!

share|improve this answer

Perl, 30 bytes

29 bytes of code + -p flag.

map{$\-=$c++if$c<++$\}0..$_}{

Try it online!

share|improve this answer

MATL, 8 bytes

:"@:]vG)

This solution uses 1-based indexing

Try it at MATL Online

Explanation

        Implicitly grab input (N)
:       Create an array from [1...N]
"       For each element (A) in this array...
  @:    Create an array from [1....A]
]       End for loop
v       Vertically concatenate everything on the stack
G       Explicitly grab the input again
)       And use it to index into the vertically concatenated array
        Implicitly display the result
share|improve this answer
    
Not that it matters a lot, but the code is much faster if you move v after ] – Luis Mendo 12 hours ago
    
@LuisMendo Ah good point! I like short and fast! – Suever 12 hours ago
    
But that's a short-circuited and, of course! :-) – Luis Mendo 12 hours ago

APL, 9 bytes

{⍵⊃∊⍳¨⍳⍵}

Explanation:

⍵⊃           ⍝ ⍵'th element of
  ∊          ⍝ concatenated elements of
   ⍳         ⍝ each list from 1 to N 
    ¨        ⍝ for each N in 
     ⍳⍵      ⍝ list from 1 to ⍵
share|improve this answer

C, 81 bytes

void main(n){int m=1,c=1;for(scanf("%d",&n);n--;c=c^m?c+1:!!++m);printf("%d",c);}

straight iterative method, 0 indexed

share|improve this answer
    
Try It Online! It works. :) – R. Kap 6 hours ago

Batch, 55 bytes

@set/am=%2+1,n=%1-m
@if %n% gtr 0 %0 %n% %m%
@echo %1

1-indexed. Like some of the other recursive answers, this keeps track of which range it's in using a second argument that defaults to the empty string. This means that m equals 1 on the first pass. The loop ends when n falls below 1 in which case the previous value of n is the answer.

share|improve this answer

PHP, 41 bytes

seems like there´s nothing shorter in PHP. Damn the dollars.

for($s=$argv[1];$s>0;$s-=++$i);echo$i+$s;

1-indexed. Run with -r.

share|improve this answer
    
Try It Online! In Bash, as it was more convenient and I could not figure out how to use flags on the actual PHP page, but at least it proves that the code works. :) – R. Kap 6 hours ago

Scala, 45 bytes

(n:Int)=>Stream.from(1)flatMap(1 to _)apply n

0-indexed.

share|improve this answer

QBIC, 21 bytes, 1-indexed

:[a|[b|~q=a|_Xc\q=q+1

Explanation:

:      Get 'a' from the cmd line
[a|    FOR (b = 1; b <= a; b++) This creates an outer loop from 1 to N
[b|    FOR (c = 1; c <= b; c++) This creates an iteration, yielding the 1, 12, 123 pattern
       'q' stores how many terms we've seen. It starts at 1 b default.
~q=a   if we are at the desired term (q == a)
|_Xc   Then quit, and print 'c' (the current number in the sequence)
\q=q+1 Else, increase 'q' and run again.

Slightly more interesting approach, but 10 bytes longer:

:{~b+q>=a|_xa-b|\b=b+q┘q=q+1

This program continuously calculates the total number of numbers in this bracket and all previous ones (1 at loop 1, 3 at loop 2, 6 at loop 3 ...). When that counter exceeds the sought-after index N, then return X from the current bracket, where X is N minus the previous amount of the counter.

share|improve this answer

Neither of these solutions is as short as JungHawn Min's, but they're alternate approaches, which is something I guess. Both are unnamed functions taking a (1-indexed) positive integer input and returning a positive integer.

Mathematica, 30 bytes

-#^2-#&@⌈√(2#)-3/2⌉/2+#&

An actual mathematical formula for this function! Made more readable (in part by translating the 3-byte characters , , and ):

# - ((#^2 + #) / 2 &)[Ceiling[Sqrt[2 * #] - 3/2]] &

Ceiling[Sqrt[2 * #] - 1/2] tells us which sublist the input refers to, from which we subtract one to tell us which sublist ends before we get to the input; then ((#^2 + #) / 2 &) computes how many elements occur in all the sublists before the one we care about, which we subtract from the input # to get our answer. (Some will notice the familiar formula (#^2 + #) / 2 for the #th triangular number; Ceiling[Sqrt[2 * #] - 1/2] is essentially the inverse function.)

Mathematica, 32 bytes

If[#2<=#,#2,#0[#+1,#2-#]]&[1,#]&

Recursive solution, basically the same as in Billywob's answer and others.

share|improve this answer

dc, 47 bytes, 0 indexed

?0sb1se[0sble1+se]sf[lb1+dsble=f1-d0!>c]dscxlbp

Try It Online!

Explanation

This explanation assumes that the input is 100.

?                                               # Ask for inout and store it on top of the main stack. 
                                                # Main = [100].
 0sb1se                                         # Store 0 on top of register "b" and 1 on top of register "e" to be referenced later. 
                                                # b = [0], e = [1], Main = [100].
       [0sble1+se]sf                            # Store the macro "0sble1+se" on top of register "f". 
                                                # f = [0sble1+se], b = [0], e = [1], Main = [100].
                    [lb1+dsble=f1-d0!>c]dscx    # Store the macro "lb1+dsble=f1-d0!>c" on top of Main stack, duplicate it, and then store one copy on top of register "c" and then immediately executing the other copy as a dc program. 
                                                # c = [lb1+dsble=f1-d0!>c], f = [0sble1+se], b = [0], e = [1], Main = [100]

================================================================================================================================================================================================================================================

Upon invocation of the macro `lb1+dsble=f1-d0!>c`:

    lb1+dsble            # Load (not pop) the value off of the top of register "b" on top of the main stack, add 1 to it, duplicate the sum, and then push one copy to the top of register "b". 
                         # Then, load the value off of the top of "e" onto the main stack.
                         # b = [0,1], e = [1], Main = [100,1,1].
             le=f        # Now, pop the top 2 values (1 and 1), compare them, and invoke the macro on top of register "f" if both are equal. In this case, it is invoked, since 1==1.
                         # b = [0,1], e = [1], Main = [100].

    ======================================================================================================================================================================================

     If the macro on top of "f" (`0sble1+se`) is invoked:

         0sble1+se # Push 0 to the top of the Main stack. Then, push it to the top of register "b", resetting the sequence, after which the value on top of "e" is loaded onto the main stack.
                   # Then, this value is incremented by 1. This new value os finally pushed to the top of register "e".
                   # b = [0,1,0], e = [1, 2], Main = [100]

    ======================================================================================================================================================================================

                 1-d0!>c # Finally, decrement the value on top of the Main stack (the input) by 1, duplicate this, pop and compare this value with 0, and as long as the `input-1`>=0, keep on executing this macro.
                         # b = [0,1,0], e = [1, 2], Main = [100,99]

================================================================================================================================================================================================================================================

                                            lbp # Finally, once all the iterations of the macros have taken place, load the n'th value of the sequence off of the top of register "b", and then output it.
                                                # At the end, b = [0,1,0,1,2,0,1,2,3,0,1,2,3,4,...] and Main=[100,99,...,0,-1].             
share|improve this answer

Bash + Unix utilities, 29 bytes, 1-based indexing

seq $1|xargs -n1 seq|sed $1!d

Try it online!

share|improve this answer

dc, 21 bytes, 0-based indexing

?d8*1+v1-2/d1+*2/-1+p

Try it online!

share|improve this answer

Bash + Unix utilities, 28 bytes, 0-based indexing

dc -e"?d8*1+v1-2/d1+*2/-1+p"

Try it online!

This is 1 byte shorter than my earlier bash answer, which used a completely different algorithm.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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