15
\$\begingroup\$

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.


\$\endgroup\$
11
  • 2
    \$\begingroup\$ Can 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? \$\endgroup\$
    – Mr. Xcoder
    Commented Apr 30, 2018 at 15:50
  • \$\begingroup\$ @Mr.Xcoder : I would rather prefer if you didn't but I guess you can \$\endgroup\$ Commented Apr 30, 2018 at 16:06
  • \$\begingroup\$ Is there an upper limit on the input? \$\endgroup\$
    – mypetlion
    Commented Apr 30, 2018 at 16:23
  • \$\begingroup\$ @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) \$\endgroup\$ Commented Apr 30, 2018 at 16:26
  • \$\begingroup\$ May we take a string of characters as input to a function? (or is this only acceptable input for a full-program?) \$\endgroup\$ Commented Apr 30, 2018 at 16:54

21 Answers 21

5
\$\begingroup\$

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)

\$\endgroup\$
2
  • \$\begingroup\$ Wouldn't replacing function(n) with n=scan(); be shorter? (for integers of course) \$\endgroup\$
    – pajonk
    Commented May 1, 2018 at 7:47
  • \$\begingroup\$ @pajonk I suppose so. But I'll say I'm taking it as a string so this answer is correct for larger inputs. \$\endgroup\$
    – Giuseppe
    Commented May 1, 2018 at 12:59
3
\$\begingroup\$

Jelly, 5 bytes

ŒḄ€Vċ

Try it online!

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

\$\endgroup\$
3
\$\begingroup\$

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    
\$\endgroup\$
4
  • \$\begingroup\$ 55 bytes. Assume 0 as truthy and null as falsy (he didn't exactly specify did he) \$\endgroup\$
    – user79855
    Commented Apr 30, 2018 at 16:13
  • \$\begingroup\$ Hum I didn't see that guess that's invalid. Sorry \$\endgroup\$
    – user79855
    Commented Apr 30, 2018 at 16:20
  • \$\begingroup\$ @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"). \$\endgroup\$
    – Arnauld
    Commented Apr 30, 2018 at 16:40
  • \$\begingroup\$ f=(s,k=1)=>(m=s.match(`^${k}(.*)${k}$`))?f(m[1],k+1):s==k ? \$\endgroup\$
    – l4m2
    Commented May 1, 2018 at 4:19
2
\$\begingroup\$

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!

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

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.

\$\endgroup\$
1
  • \$\begingroup\$ you can use / instead of }Q so it autocompletes Q at the end \$\endgroup\$
    – RK.
    Commented Apr 30, 2018 at 23:52
2
\$\begingroup\$

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!

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

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?
\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$
    – benj2240
    Commented May 1, 2018 at 19:56
  • \$\begingroup\$ Thanks anyway! I've never utilized Zip before, but I see now how it can be useful. \$\endgroup\$
    – Kahzaar
    Commented May 1, 2018 at 20:03
1
\$\begingroup\$

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!

\$\endgroup\$
5
  • \$\begingroup\$ Palindromize ? What does this do? Because as you may know the stairs with 10+ are no palindromes \$\endgroup\$ Commented Apr 30, 2018 at 20:32
  • \$\begingroup\$ @YassinHajaj It palindromises the array, not the string \$\endgroup\$
    – Okx
    Commented Apr 30, 2018 at 20:48
  • \$\begingroup\$ Alright thanks for the info \$\endgroup\$ Commented Apr 30, 2018 at 21:18
  • \$\begingroup\$ @YassinHajaj gLη€ûJså is another, where you can see the vectorization of the palindromization using €û palindromize each. \$\endgroup\$ Commented Apr 30, 2018 at 23:35
  • \$\begingroup\$ @okx gLη€ûJså for an 8-byte that doesn't blow up TIO. \$\endgroup\$ Commented Apr 30, 2018 at 23:35
1
\$\begingroup\$

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!

\$\endgroup\$
1
  • \$\begingroup\$ 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! \$\endgroup\$ Commented Apr 30, 2018 at 17:04
1
\$\begingroup\$

Stax, 14 bytes

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

Run and debug it

Very slow for bigger numbers.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ 9 bytes \$\endgroup\$
    – wastl
    Commented May 1, 2018 at 7:41
  • \$\begingroup\$ Slight change for 7 bytes \$\endgroup\$
    – recursive
    Commented May 5, 2018 at 2:51
  • \$\begingroup\$ And a fast one at 8 bytes \$\endgroup\$
    – recursive
    Commented May 5, 2018 at 2:57
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

J, 40 bytes

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

Try it online!

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

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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]
\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
4
  • \$\begingroup\$ Theoretically works for 12345678910987654321, if you are able to construct a list with that many elements. \$\endgroup\$ Commented Apr 30, 2018 at 17:27
  • \$\begingroup\$ @BMO I knew there had to be a way to do that. Thanks \$\endgroup\$ Commented Apr 30, 2018 at 17:42
  • \$\begingroup\$ @BMO Your golf is really obvious in hindsight... \$\endgroup\$ Commented May 1, 2018 at 5:24
  • \$\begingroup\$ 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). \$\endgroup\$ Commented May 1, 2018 at 10:25
0
\$\begingroup\$

Perl 5 -lp, 49 bytes

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

Try it online!

0 = truthy, anything else = falsy

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

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
\$\endgroup\$
0
\$\begingroup\$

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

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

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.

\$\endgroup\$
1
  • \$\begingroup\$ I think your \ds can become . and save you two bytes \$\endgroup\$
    – Leo
    Commented May 1, 2018 at 5:41
0
\$\begingroup\$

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.

\$\endgroup\$
0
-1
\$\begingroup\$

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!

\$\endgroup\$
8
  • \$\begingroup\$ The output doesn't have to be the strings true and false but truthy and falsey values. 1 and 0 would work for example \$\endgroup\$
    – dylnan
    Commented Apr 30, 2018 at 15:43
  • \$\begingroup\$ @dylnan : I just read that , thanks. Still golfing (a lot to go) \$\endgroup\$
    – user79855
    Commented Apr 30, 2018 at 15:45
  • \$\begingroup\$ 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'. \$\endgroup\$ Commented Apr 30, 2018 at 17:40
  • \$\begingroup\$ @NoOneIsHere : good idea. apparently coding while sleeping is not such a good idea thanks \$\endgroup\$
    – user79855
    Commented May 1, 2018 at 1:54
  • 1
    \$\begingroup\$ Your 138 byte solution always returns False, since g is never 1. You should probably test these solutions before posting them... \$\endgroup\$
    – Jo King
    Commented May 1, 2018 at 5:09

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.