n-th term of the rise & reset sequence
Haskell, 27 26 bytes
([z|k<-[1..],z<-[1..k]]!!)
Try it online!
Thanks @DanD. for -1 byte!
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],...]
. To concatenate these we can write [z|k<-[1..],z<-[1..k]]
which results in [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).
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))
});
Alternatively, for the same byte count, we can have a curried function like so:
f=n=>m=>n++<m?n:f(n+~m)(-~m)
You can call this with f(5)()
- it returns a function, which when called, returns the result, as described in this meta post.
Jelly, 5 bytes, 1-indexed
RRF³ị
Try it online!
Explanation:
(Assume N = 4 for the examples)
R Generate a list of 1 to N [1, 2, 3, 4]
R Generate new lists 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 ...]
³ị Use the input number (³) as index (ị) on the list.
This is one-based: [1, 1, 2, 1, 2, 3 ...]
^