Is this a staircase number?

15

0

Challenge :

Check if the given number forms a number staircase or not


Input :

A integer (greater than 0 and not decimal). NOTE : You can take input as string , array of digits.


Output :

a truthy / falsy value depending on whether the number forms a staircase or not


Number staircase :

A number staircase is an integer that , when read from left to right :

  • Starts with 1
  • which may be followed by 2
  • which may be followed by 3
  • and so on till n
  • then the number descends starting at n - 1
  • then n - 2
  • then n - 3
  • and so on till it reaches 1

Note :

The may be part is used to indicate that if length > is greater than 1. If it is the order must be followed as is. i.e : 12321


Example :

12321                          ---> true
12345654321                    ---> true
9                              ---> false
1                              ---> true
2                              ---> false
123421                         ---> false
112312318901323                ---> false
123456789101110987654321       ---> true

Note :

The input given will always be an integer greater than 0 and will not be a decimal. Your output must be a truthy or falsy value depending on the input


Restrictions :

This is so shortest code in bytes (for each programming language ) wins.


Muhammad Salman

Posted 2018-04-30T15:27:07.007

Reputation: 2 361

2Can we take input as a list of digits? Like [1,2,3,4,5,6,7,8,9,1,0,1,1,1,0,9,8,7,6,5,4,3,2,1] for 123456789101110987654321? – Mr. Xcoder – 2018-04-30T15:50:23.963

@Mr.Xcoder : I would rather prefer if you didn't but I guess you can – Muhammad Salman – 2018-04-30T16:06:37.113

Is there an upper limit on the input? – mypetlion – 2018-04-30T16:23:30.413

@mypetlion : Not really , it is as high as your code can support (excluding hardcoded and purposedly low ones.) Normally the highest your language can support (but not in this case) – Muhammad Salman – 2018-04-30T16:26:42.860

May we take a string of characters as input to a function? (or is this only acceptable input for a full-program?) – Jonathan Allan – 2018-04-30T16:54:20.923

@JonathanAllan : You may take that as a function. – Muhammad Salman – 2018-05-01T00:44:47.860

@JoKing : normally yes , but in this case I do since this . Although it is different sadly the name is same so

– Muhammad Salman – 2018-05-01T03:58:03.247

@JoKing : Why not! – Muhammad Salman – 2018-05-01T04:16:34.367

"and so on till it reaches 0" - should be "and so on till it reaches 1". – djhurio – 2018-05-01T05:09:11.613

@djhurio : nice catch. Thanks. – Muhammad Salman – 2018-05-01T05:10:52.593

Very closely related, nearly a dupe. It's slightly different, since this one allows the string to go above 9, but other than that they're the same. – James – 2018-05-01T16:34:43.270

Answers

5

R, 97 bytes

function(n)"if"(n>1,{while({T=T+1;x=paste(c(1:T,T:2-1),collapse="");nchar(x)<nchar(n)})0;x==n},T)

Try it online!

Takes n as a character or an integer; using character will give correct results for integers that can't be held precisely as a 64-bit double.

Generates staircase numbers until it finds one at least as long as n is, then tests for equality.

Equivalent to:

function(n)
    if(n > 1){
        T <- T + 1
        x <- paste(c(1:T,T:2-1),collapse="")
        while(nchar(x) < nchar(n)){
            T <- T + 1
            x <- paste(c(1:T,T:2-1),collapse="")
        }
        return(x == n)
    } else
        return(TRUE)

Giuseppe

Posted 2018-04-30T15:27:07.007

Reputation: 21 077

Wouldn't replacing function(n) with n=scan(); be shorter? (for integers of course) – pajonk – 2018-05-01T07:47:44.597

@pajonk I suppose so. But I'll say I'm taking it as a string so this answer is correct for larger inputs. – Giuseppe – 2018-05-01T12:59:47.887

3

Jelly, 5 bytes

ŒḄ€Vċ

Try it online!

Warning: Very slow (fast for 1 and 121)! Prepend DL to make it faster.

Erik the Outgolfer

Posted 2018-04-30T15:27:07.007

Reputation: 38 134

3

JavaScript (ES6), 62 57 bytes

Saved 2 bytes thanks to @l4m2

Returns a boolean.

f=(s,k=1)=>(m=s.match(`^${k}(.*)${k}$`))?f(m[1],k+1):s==k

Try it online!

How?

Starting with k = 1, we look for k at the beginning and at the end of the string, and recursively iterate the process on the remaining middle sub-string with k + 1. The recursion stops as soon as there's no match anymore. The input is a staircase number if the last sub-string is equal to k.

Example for s = "1234321":

 k | s         | match     | s == k 
---+-----------+-----------+--------
 1 | "1234321" | 1(23432)1 | no     
 2 | "2343"    | 2(343)2   | no     
 3 | "343"     | 3(4)3     | no     
 4 | "4"       | null      | yes    

Arnauld

Posted 2018-04-30T15:27:07.007

Reputation: 111 334

55 bytes. Assume 0 as truthy and null as falsy (he didn't exactly specify did he) – None – 2018-04-30T16:13:04.180

Hum I didn't see that guess that's invalid. Sorry – None – 2018-04-30T16:20:18.120

@I'mnoone No worries! Interestingly, removing m[0]==s& instead would make it pass all test cases (but still fail on other ones such as "123217"). – Arnauld – 2018-04-30T16:40:40.163

f=(s,k=1)=>(m=s.match(`^${k}(.*)${k}$`))?f(m[1],k+1):s==k ? – l4m2 – 2018-05-01T04:19:50.500

2

Pyth, 13 12 bytes

/mjk+Sd_Stdl

Saved a byte thanks to RK.
Try it here

Explanation

/mjk+Sd_Stdl
 m         lQ   For each d up to the length of the (implicit) input...
    +Sd_Std     ... get the list [1, 2, ..., d, d-1, ..., 1]...
  jk            ... concatenated.
/               Count how many times the input appears.

If you really want the input as an integer, you can use }Qmsjk+Sd_Std instead, but this is horrifyingly slow.

user48543

Posted 2018-04-30T15:27:07.007

Reputation:

you can use / instead of }Q so it autocompletes Q at the end – RK. – 2018-04-30T23:52:02.853

2

Haskell, 55 54 bytes

-1 byte thanks to Laikoni!

f x=elem x[read$[1..z]++[z-1,z-2..1]>>=show|z<-[1..x]]

Try it online!

ბიმო

Posted 2018-04-30T15:27:07.007

Reputation: 15 345

2

Python 2, 69 bytes

f=lambda s,n=1,t='1',u='':t+':'>s>t<s*f(s,n+1,t+`n+1`,`n`+u)or s==t+u

Try it online!

Dennis

Posted 2018-04-30T15:27:07.007

Reputation: 196 637

2

C# (Visual C# Interactive Compiler), 138 107 102 bytes

bool t(List<int>s)=>s.Select((j,i)=>s[0]==1&&s.Last()==1&&(i==0||j+1==s[i-1]||j-1==s[i-1])).All(x=>x);

Try it online!

Explanation:

bool t(List<int>s)=>
    s.Select((j,i) =>         //iterate over each item and store the return value
        s[0]==1&&s.Last()==1  //does the sequence start and end with 1?
        &&                    //AND
        (i==0                 //is it the first item?
        ||                    //OR
        j+1==s[i-1]           //is the item 1 greater than the previous?
        ||                    //OR
        j-1==s[i-1])          //is the item 1 smaller than the previous?
    ).All(x=>x);              //did all pass the criteria?

Kahzaar

Posted 2018-04-30T15:27:07.007

Reputation: 21

Actually, the Zip...Skip method in my previous comment fails on [1,1], which should return true if I understand the spec. I've deleted it. – benj2240 – 2018-05-01T19:56:43.637

Thanks anyway! I've never utilized Zip before, but I see now how it can be useful. – Kahzaar – 2018-05-01T20:03:26.750

1

05AB1E, 9 8 bytes

L€L€ûJså

Warning: EXTREMELY SLOW! Add g to the start to speed it up.

Try it online!

Explanation:

L           1..input
 €L         for each element, map to 1..element 
   €û       palindromize each element
     J      join each element from a list to a string
      så    is the input in that list?

Old Explanation:

F           For [0 .. input] map over
 NL          Push 1..i
   û         Palindromize
    J        Join
     ¹       First input
      Q      Equal?
       }   end loop
        O  Sum.

Try it online!

Okx

Posted 2018-04-30T15:27:07.007

Reputation: 15 025

Palindromize ? What does this do? Because as you may know the stairs with 10+ are no palindromes – Yassin Hajaj – 2018-04-30T20:32:01.543

@YassinHajaj It palindromises the array, not the string – Okx – 2018-04-30T20:48:28.653

Alright thanks for the info – Yassin Hajaj – 2018-04-30T21:18:43.930

@YassinHajaj gLη€ûJså is another, where you can see the vectorization of the palindromization using €û palindromize each. – Magic Octopus Urn – 2018-04-30T23:35:24.833

@okx gLη€ûJså for an 8-byte that doesn't blow up TIO. – Magic Octopus Urn – 2018-04-30T23:35:51.130

1

Python 2, 77 bytes

lambda s,r=range:s in[''.join(map(str,r(1,k+2)+r(k,0,-1)))for k in r(len(s))]

Try it online!

Lynn

Posted 2018-04-30T15:27:07.007

Reputation: 55 648

Save four by accepting an integer if we may error once we hit longs: TIO. We'd need quite some time and memory by that point anyway!

– Jonathan Allan – 2018-04-30T17:04:56.913

1

Attache, 57 55 46 bytes

{GenerateFirst[N@Join@Bounce@1&`:,`>=:`#&_]=_}

Try it online! Ah, that's much more elegant.

With Generate (49 bytes):

{g@Generate[{g@_>=#_2}&_]=_}g:=N@Join@Bounce@1&`:

Explanation

{GenerateFirst[N@Join@Bounce@1&`:,`>=:`#&_]=_}
{                                            }   anonymous lambda, argument: _
 GenerateFirst[                  ,        ]      find the first element satisfying...
               N@Join@Bounce@1&`:                    this generation function
                                  `>=:`#&_           and this condition
                                           =_    is it equal to the input?

The generation function simply creates the Nth staircase number. Then, this search terminates once `>=:`#&_ is satisfied. Expanded, this is:

 `>=:`#&_
 (`>= : `#) & _      NB. remember _ is the input
                     NB. also, f:g is f[...Map[g, args]]
 { #_1 >= #_2 } & _
 { Size[_1] >= Size[_2] } & _
 { Size[_1] >= Size[the original input] }
 [n] -> { Size[n] >= Size[input] }

So, this terminates once the length of the generation function's output is at least that of the inputs. Thus, this generates the smallest staircase number at least as long as the input number. Thus, if the input is a staircase number, the result will be the same staircase number, and otherwise the next longest staircase number. As such, a simple check with equality to the original input is sufficient for determining whether or not it was a staircase number.

Attache, 55 bytes

0&{If[#_2>#g[_],$[_+1,_2],_2=g!_]}g:=N@Join@Bounce@1&`:

Try it online! With plan ol' recursion.

Conor O'Brien

Posted 2018-04-30T15:27:07.007

Reputation: 36 228

1

Stax, 14 bytes

Ç╗☻W╧ΩÆΘαφ←≤─♣

Run and debug it

Very slow for bigger numbers.

Multi

Posted 2018-04-30T15:27:07.007

Reputation: 425

19 bytes – wastl – 2018-05-01T07:41:02.550

Slight change for 7 bytes

– recursive – 2018-05-05T02:51:09.300

And a fast one at 8 bytes

– recursive – 2018-05-05T02:57:04.173

1

J, 40 bytes

1#.[:(<-:"_1<@([:;>:<@":@-|@i:)@<:@#\)":

Try it online!

I'm not quite happy with this soluiton - a lot of @ and boxing < .

Galen Ivanov

Posted 2018-04-30T15:27:07.007

Reputation: 13 815

1

SNOBOL4 (CSNOBOL4), 109 bytes

	N =INPUT
	X =L ='1'
C	R =LT(SIZE(L R),SIZE(N)) X R	:F(O)
	X =X + 1
	L =L X	:(C)
O	OUTPUT =IDENT(L R,N) 1
END

Try it online!

Curiously, replacing '1' in the second line with 1 causes the program to fail on the input of 1.

Giuseppe

Posted 2018-04-30T15:27:07.007

Reputation: 21 077

1

K, 36 bytes

{|/($x)~/:{,/$(1+!x),1+1_|!x}'1+!#x}

Takes a string such as "12321" as a parameter.

This function is written as a long chain of function applications, as in f g h x, so read the commented versions from the bottom, going up. {x+1} is lambda x: x+1, x is a default param name. Check out https://pastebin.com/cRwXJn7Z or the interpreter's help for operator meanings.

We generate the staircase number with n in the middle by {,/$(1+!x),1+1_|!x}:

{,/                      / join all the chars
   $                     / tostring each number
     (1+!x)              / take the range [0..x-1]; add 1 to each
            ,            / concat
             (1+1_|!x)}  / take the range [0..x-1]; reverse it; drop 1; add 1 to each

The whole function {|/($x)~/:{,/$(1+!x),1+1_|!x}'1+!#x}:

{|/                                   / any_is_true
   ($x)~/:                            / match the string with each of the generated staircases
          {,/$(1+!x),1+1_|!x}'        / make staircase number of each of the numbers
                                      / (note: the x in the inner lambda shadows the outer x)
                              1+!#x}  / take the range [1..length of the string, inclusive]

uryga

Posted 2018-04-30T15:27:07.007

Reputation: 71

0

Japt, 11 bytes

Takes input as a string.

Êõõ mê m¬øU

Try it


Explanation

                :Implicit input of string U
Ê               :Length of U
 õ              :Range [1,Ê]
  õ             :Range [1,el] for each element
    mê          :Map & palidromise
       m¬       :Map & join
         øU     :Contains U?

Alternative, 10 9 bytes

This solution, which can take input as a string or an integer, will return an array of numbers for truthy or, eventually, throw an error for falsey, if it doesn't cripple your browser before that. Use with caution.

@¥Xê q}aõ

Try it

Shaggy

Posted 2018-04-30T15:27:07.007

Reputation: 24 623

0

Haskell, 64 60 58 bytes

-6 thanks to @BMO!

elem.show<*>(`take`[[1..n]++[n-1,n-2..1]>>=show|n<-[1..]])

Try it online!

Esolanging Fruit

Posted 2018-04-30T15:27:07.007

Reputation: 13 542

Theoretically works for 12345678910987654321, if you are able to construct a list with that many elements. – Esolanging Fruit – 2018-04-30T17:27:18.700

@BMO I knew there had to be a way to do that. Thanks – Esolanging Fruit – 2018-04-30T17:42:07.363

@BMO Your golf is really obvious in hindsight...

– Esolanging Fruit – 2018-05-01T05:24:07.880

It's also very close, I would have suggested it as an improvement if I didn't already post it (I didn't see yours until I posted mine). – ბიმო – 2018-05-01T10:25:02.237

0

Perl 5 -lp, 49 bytes

$i++while s/^$i//;$i-=2;$i--while s/^$i//;$_||=$i

Try it online!

0 = truthy, anything else = falsy

Xcali

Posted 2018-04-30T15:27:07.007

Reputation: 7 671

0

Retina, 45 43 bytes

$
;1
+`^(.+)(.*)\1;\1$
$2;$.(_$1*
^(.+);\1$

Try it online! Link includes test cases. Edit: Saved 2 bytes thanks to @Leo. Explanation:

$
;1

Initialise n to 1.

+`^(.+)(.*)\1;\1$

While s begins and ends with n:

$2;$.(_$1*

Delete n from the ends of s and increment n.

^(.+);\1$

Test whether n is left.

Neil

Posted 2018-04-30T15:27:07.007

Reputation: 95 035

I think your \ds can become . and save you two bytes – Leo – 2018-05-01T05:41:06.360

0

Java 10, 142 bytes

s->{int n=1,l,f=1;try{for(;;s=s.substring(l=(n+++"").length(),s.length()-l))if(!s.matches(n+".*"+n)&!s.equals(n+""))f=0;}finally{return f>0;}}

Try it online.

Explanation:

s->{                 // Method with String parameter and boolean return-type
  int n=1,           //  Stair integer, starting at 1
      l,             //  Length integer to reduce bytes
      f=1;           //  Result-flag, starting at 1
  try{for(;;         //  Loop until an error occurs
          s=s.substring(l=(n+++"").length(),s.length()-l))
                     //    After every iteration: remove `n` from the sides of the String
        if(!s.matches(n+".*"+n)
                     //   If the current String with the current `n` isn't a stair
           &!s.equals(n+""))
                     //   And they are also not equal (for the middle)
          f=0;       //    Set the flag to 0
   }finally{         //  After the error (StringOutOfBoundsException) occurred:
      return f>0;}}  //   Return whether the flag is still 1

Kevin Cruijssen

Posted 2018-04-30T15:27:07.007

Reputation: 67 575

0

Regex (PCRE), 92 bytes

^(1|\d(?=1|9)|[2-79](?=8)|[2-68](?=7)|[2-57](?=6)|[2346](?=5)|[235](?=4)|[24](?=3)|3(?=2))+$

Try it online!

I'm open to any suggestions to improve this.

Neil

Posted 2018-04-30T15:27:07.007

Reputation: 2 417

-1

Thanks to following users:

@Nooneishere
@LyricLy
@JoKing

Python 2, 147 bytes

g=s=input()
f=1
o='1'==s[0]
while`f`==s[0]:s=s[len(`f`):];f+=1
f-=2
o&=`f`==s[0]
while s and`f`==s[0]:s=s[len(`f`):];f-=1
o&=f==0
o|=g=='1'
print o

Try it online!

user79855

Posted 2018-04-30T15:27:07.007

Reputation:

The output doesn't have to be the strings true and false but truthy and falsey values. 1 and 0 would work for example – dylnan – 2018-04-30T15:43:24.750

@dylnan : I just read that , thanks. Still golfing (a lot to go) – None – 2018-04-30T15:45:08.547

Couldn't you just use s[0] instead of startswith? Errors are allowed, and you can say 'outputs 1 for staircase, anything else (including nothing) [since stderrr is ignored] for non-staircase'. – NoOneIsHere – 2018-04-30T17:40:35.107

@NoOneIsHere : good idea. apparently coding while sleeping is not such a good idea thanks – None – 2018-05-01T01:54:10.677

You can save bytes by replacing the if x:o=0 statements with o*=x. – LyricLy – 2018-05-01T03:30:38.087

This doesn't work without a trailing character for truthy inputs – Jo King – 2018-05-01T03:52:14.473

This fixes most of your issues, but still doesn't support staircase numbers above n=9 – Jo King – 2018-05-01T04:27:55.320

@Joking : thanks – None – 2018-05-01T04:58:51.960

1Your 138 byte solution always returns False, since g is never 1. You should probably test these solutions before posting them... – Jo King – 2018-05-01T05:09:11.757