16
\$\begingroup\$

Task

The prepend,append-Sequence is defined recursively, like this

  • a(1) = 1
  • a(n) = a(n-1).n , if n is even
  • a(n) = n.a(n-1) , if n is odd

where the . represents an integer concatenation.

So the first few terms are: 1,12,312,3124,53124,531246,7531246,... This is A053064.

Your task is, given an integer a> 0 to return n, such that the nth element in the prepend,append-Sequence is equal to a and if no such n exists return 0, a negative number or error out etc.

Rules

  • Input can be taken as an integer, string, list of characters/digits etc.
  • Output can be printed to STDOUT or returned (integer, string etc. is fine)
  • On invalid input & in the case no such n exists your program may do anything but return a positive integer (eg. loop forever, return 0 etc.)
  • You may choose to use 0-indexing, but then the output in case no n exists cannot be 0

Test cases

1 -> 1
12 -> 2
21 -> 0
123 -> 0
312 -> 3
213 -> 0
211917151311975312468101214161820 -> 21
2119171513119753102468101214161820 -> 0
333129272523211917151311975312468101214161820222426283031 -> 0
999795939189878583817977757371696765636159575553514947454341393735333129272523211917151311975312468101214161820222426283032343638404244464850525456586062646668707274767880828486889092949698100 -> 100
Erik the Outgolfer
40.7k5 gold badges46 silver badges125 bronze badges
asked Aug 7, 2017 at 16:11
\$\endgroup\$
7
  • \$\begingroup\$ More formal: a(n-1)*(int(log(n))+1)+n and n*(int(log(n))+1)+a(n-1)? \$\endgroup\$ Commented Aug 7, 2017 at 16:19
  • 1
    \$\begingroup\$ @Mr.Xcoder I would call that less formal :P \$\endgroup\$ Commented Aug 7, 2017 at 16:20
  • \$\begingroup\$ @JonathanAllan That is already in the question for ~10 minutes. \$\endgroup\$ Commented Aug 7, 2017 at 16:27
  • 2
    \$\begingroup\$ I suggest allowing errors for invalid inputs. \$\endgroup\$ Commented Aug 7, 2017 at 16:46
  • \$\begingroup\$ I suggest allowing undefined behaviour for invalid inputs. \$\endgroup\$ Commented Aug 7, 2017 at 16:46

15 Answers 15

6
\$\begingroup\$

JavaScript (ES6), 40 bytes

Takes input as a string. Throws a recursion error if no index is found.

f=(n,s=k='1')=>n==s?k:f(n,++k&1?k+s:s+k)

Demo

f=(n,s=k='1')=>n==s?k:f(n,++k&1?k+s:s+k)
console.log(f('1')) // 1
console.log(f('12')) // 2
console.log(f('312')) // 3
console.log(f('211917151311975312468101214161820')) // 21
console.log(f('999795939189878583817977757371696765636159575553514947454341393735333129272523211917151311975312468101214161820222426283032343638404244464850525456586062646668707274767880828486889092949698100')) // 100

answered Aug 7, 2017 at 17:47
\$\endgroup\$
3
  • \$\begingroup\$ I think you can save a byte with this: f=(n,s=k='1')=>n-s?f(n,++k&1?k+s:s+k):k \$\endgroup\$ Commented Aug 7, 2017 at 21:56
  • \$\begingroup\$ @RickHitchcock Unfortunately, that would force Number comparisons and introduce false positives on large inputs caused by the loss of precision. \$\endgroup\$ Commented Aug 7, 2017 at 22:11
  • \$\begingroup\$ Gotcha. It works on the test cases but was unsure how it would handle other situations. \$\endgroup\$ Commented Aug 7, 2017 at 22:12
6
\$\begingroup\$

C# (.NET Core), (削除) 83, 80, 60 (削除ここまで) 59 bytes

n=>{int i=0;for(var t="";t!=n;)t=++i%2<1?t+i:i+t;return i;}

Try it online!

Takes the input as a string into a lambda function. 1-indexed. Returns the index of the value for truthy, or infitnitely loops for a "falsey"

answered Aug 7, 2017 at 16:42
\$\endgroup\$
6
\$\begingroup\$

Python 2, 63 bytes

-1 byte thanks to @EriktheOutgolfer.

f=lambda x,i='1',j=2:i!=`x`and f(x,[i+`j`,`j`+i][j%2],j+1)or~-j

Try it online!

Python 2, 64 bytes

-18 bytes thanks to @officialaimm, because I didn't notice erroring out was allowed!

x,i,j=input(),'1',1
while i!=x:j+=1;i=[i+`j`,`j`+i][j%2]
print j

Try it online!

Python 2, 82 bytes (does not loop forever)

This one returns 0 for invalid inputs.

def f(n,t="",i=1):
 while len(t)<len(n):t=[t+`i`,`i`+t][i%2];i+=1
 print(n==t)*~-i

Try it online!

answered Aug 7, 2017 at 16:57
\$\endgroup\$
7
  • 2
    \$\begingroup\$ Ninja'd :D 65 bytes \$\endgroup\$ Commented Aug 7, 2017 at 17:02
  • \$\begingroup\$ @officialaimm Thanks a lot! I didn't notice erroring out / loop forever was allowed. \$\endgroup\$ Commented Aug 7, 2017 at 17:05
  • \$\begingroup\$ Save a byte with a lambda: f=lambda x,i='1',j=2:i!=`x`and f(x,[i+`j`,`j`+i][j%2],j+1)or~-j \$\endgroup\$ Commented Aug 7, 2017 at 18:17
  • \$\begingroup\$ @EriktheOutgolfer Wait, it throws recursion error for everything, although I set sys.setrecursionlimit(). Can you provide a tio? \$\endgroup\$ Commented Aug 7, 2017 at 18:20
  • \$\begingroup\$ @Mr.Xcoder Does it throw an error for x=1? Or x=12? I thought it only threw such an error for at least x=151311975312468101214 or something. \$\endgroup\$ Commented Aug 7, 2017 at 18:24
3
\$\begingroup\$

Jelly, 12 bytes

Rs2ZU1¦ẎVμ€i

Try it online!

Explanation:

Rs2ZU1¦ẎVμ€i
 μ€ Eval this link for each (automatic [1..n] range)
R Range
 s2 Split in pieces of: 2
 Z Zip
 U1¦ Only keep index: 1 of: Vectorized reverse
 Ẏ Flatten 1-deep
 V Concatenate string versions and eval
 i Find index of y in x (y = implicit input)
answered Aug 7, 2017 at 16:21
\$\endgroup\$
0
3
\$\begingroup\$

05AB1E, 14 bytes

$vDNÌNFs}«})Ik

Try it online! or as a Test suite

Explanation

0-indexed.
Returns -1 if the input is not in the sequence.

$ # push 1 and input
 v # for each y,N (element, index) in input do:
 D # duplicate top of stack
 NÌ # push N+2
 NF } # N times do:
 s # swap the top 2 elements on the stack
 « # concatenate the top 2 elements on the stack
 }) # end loop and wrap in a list
 Ik # get the index of the input in this list
answered Aug 7, 2017 at 17:22
\$\endgroup\$
2
  • \$\begingroup\$ Haha, this is basically my solution with the g removed and the append/prepend thing shortened. I'll delete my answer \$\endgroup\$ Commented Aug 7, 2017 at 17:26
  • \$\begingroup\$ @Okx: Oh yeah, I see you golfed yours down to almost exactly this only minutes after my post. Great minds ;) \$\endgroup\$ Commented Aug 7, 2017 at 17:34
2
\$\begingroup\$

R, 73 bytes

p=paste0;n=scan(,'');l='';while(l!=n){F=F+1;l="if"(F%%2,p(F,l),p(l,F))};F

Reads from stdin and returns the value of the index (implicitly printed). Infinite loops when the value isn't in the sequence. F is by default FALSE which is cast to 0 when used in arithmetic.

Try it online!

answered Aug 7, 2017 at 17:13
\$\endgroup\$
2
\$\begingroup\$

Haskell, (削除) 75 (削除ここまで) (削除) 71 (削除ここまで) 57 bytes

f n=[i|i<-[1..],(show=<<reverse[1,3..i]++[2,4..i])==n]!!0

Takes n as a string.

Try it online!

answered Aug 7, 2017 at 19:18
\$\endgroup\$
2
\$\begingroup\$

Husk, (削除) 17 (削除ここまで) 15 bytes

£moiṁsṁṠehGJC2N

Try it online!

1-indexed. Returns 0 if not in the sequence.

-2 bytes from Leo, GJ!

answered Mar 16, 2021 at 6:13
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Nice, particularly the z*İ_ trick to reverse alternate elements. 15 bytes by using string input... \$\endgroup\$ Commented Mar 16, 2021 at 11:35
  • \$\begingroup\$ String input doesn't really work because values are not lexicographically ordered: Try it online! \$\endgroup\$ Commented Mar 17, 2021 at 0:42
  • \$\begingroup\$ There is a shorter way by scanning with J, though: Try it online! \$\endgroup\$ Commented Mar 17, 2021 at 4:05
2
\$\begingroup\$

Vyxal, 12 bytes

ɾɖ≬wJṘyRYvṅḟ

Try it Online! Uses 0-indexing, outputs -1 for invalid.

 ḟ # Find index of input in...
 ɖ # Scan
ɾ # range(1, input)
 ≬--- # by
 wJ # Concatenate
 Ṙ # Reverse
 yRY # Reverse every other element
 vṅ # Concatenate each list into a number
answered Dec 29, 2023 at 13:13
\$\endgroup\$
1
\$\begingroup\$

Mathematica, 135 bytes

s=t={};x=1;While[x<5!,{s~AppendTo~#&,s~PrependTo~#&}[[x~Mod~2+1]]@x;AppendTo[t,FromDigits@Flatten[IntegerDigits/@s]];x++];t~Position~#&
answered Aug 7, 2017 at 16:20
\$\endgroup\$
1
\$\begingroup\$

Jelly, (削除) 19 18 (削除ここまで) 15 bytes

+ḂḶṚm2;RḤ$ṁμ€Vi

A monadic link taking and returning integers.

Try it online! (very slow - takes ~50s on TIO just to confirm that 3124 is at index 4)

For a much faster version use the previous 18 byter (only checks up to the length of the input, which is sufficient).

How?

+ḂḶṚm2;RḤ$ṁμ€Vi - Link: number, v
 μ€ - perform the monadic link to the left for €ach k in [1,2,3,...v]
 - (v can be big, lots of k values makes it slow!)
 Ḃ - modulo k by 2 = 1 if odd 0 if even
+ - add to k = k+isOdd(k)
 Ḷ - lowered range = [0,1,2,...,k+isOdd(k)]
 Ṛ - reverse = [k+isOdd(k),...,2,1,0])
 m2 - modulo slice by 2 = [k+isOdd(k),k+isOdd(k)-2,...,3,1]
 $ - last two links as a monad:
 R - range(k) = [1,2,3,...,k]
 Ḥ - double = [2,4,6,...,2k]
 ; - concatenate = [k+isOdd(k),k+isOdd(k)-2,...,3,1,2,4,6,...,2k]
 ṁ - mould like range(k) = [k+isOdd(k),k+isOdd(k)-2,...,3,1,2,4,6,...,k-isOdd(k)]
 - (this is a list of the integers to be concatenated for index k)
 V - evaluate as Jelly code (yields a list of the concatenated integers)
 i - first index of v in that (or 0 if not found)
answered Aug 7, 2017 at 16:41
\$\endgroup\$
5
  • \$\begingroup\$ How long would it take to compute 211917151311975312468101214161820? \$\endgroup\$ Commented Aug 7, 2017 at 17:01
  • \$\begingroup\$ A long, long time :p \$\endgroup\$ Commented Aug 7, 2017 at 17:21
  • \$\begingroup\$ Yes, but how long? \$\endgroup\$ Commented Aug 7, 2017 at 17:22
  • \$\begingroup\$ Well looks like it's order v squared where v is the input integer. \$\endgroup\$ Commented Aug 7, 2017 at 17:24
  • \$\begingroup\$ @JonathanAllan Technically you call that 8 :p \$\endgroup\$ Commented Aug 7, 2017 at 17:34
1
\$\begingroup\$

Swift 4, 92 bytes

This loops infinitely for invalid cases, so I didn't include them in the testing link.

func f(x:String){var i="1",j=1;while i != x{j+=1;i=[i+String(j),String(j)+i][j%2]};print(j)}

Test Suite.

Amusingly, it is longer with a closure:

var f:(String)->Int={var i="1",j=1;while i != 0ドル{j+=1;i=[i+String(j),String(j)+i][j%2]};return j}

Test Suite.

answered Aug 7, 2017 at 17:21
\$\endgroup\$
1
\$\begingroup\$

Haskell, (削除) 115 (削除ここまで) 85 bytes

s=read.(show=<<)
f 1=1
f x|odd x=s[x,f$x-1]
f x=s[f$x-1,x]
g x=[n|n<-[1..],x==f n]!!0

Try it online!

answered Aug 7, 2017 at 16:19
\$\endgroup\$
1
  • \$\begingroup\$ @BruceForte I actually managed to save 30 thanks to your suggestion. \$\endgroup\$ Commented Aug 7, 2017 at 18:54
1
\$\begingroup\$

Perl 5, 54 + 1 (-n) = 55 bytes

$a=++,ドル%2?,ドル.$a:$a.,ドルwhile length$a<length;say/$a/&&,ドル

Try it online!

Returns nothing if not found.

answered Aug 7, 2017 at 19:17
\$\endgroup\$
1
\$\begingroup\$

Japt, 17 bytes

@P=PiXv n X;\P}a1

Try it online! or check (valid) test cases

Takes input as a string or integer. On invalid input, continues "forever" looking for a solution (thus why I didn't include them in the test cases).

Explanation:

@P=PiXv n X;\P}a1 
 # Implicitly start with P = ""
@ }a1 # Repeat the function for each integer X > 0 until one returns true
 P=Pi X # Insert X into P at index:
 Xv # X is divisible by 2?
 n # Times -1
 ;\P # Return whether P now equals the input
 # Implicitly output the last value of X

The "insert at index" portion might be a bit confusing, so I'll add more detail here. In Japt, NvD is a function which returns 1 if N is divisible by D, and 0 otherwise. If D is not provided, it defaults to 2. Thus Xv here is equal to 1 if X is even, and 0 if X is odd. NnD is a function that returns D - N. If D is not provided it defaults to 0, effectively returning -N. In this program, that results in -1 if X is even, and still 0 if X is odd. Finally, in Japt indexing negative numbers count from the end of a string or array. Thus the segment PiXv n X evaluates to Pi0 X if X is odd, prepending X, but it evaluates to Pi-1 X if X is even, appending it instead.

answered Mar 16, 2021 at 7:00
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.