A "Giza number", also colloquially known as a Timmy Number is any number where the digits represent a pyramid (A134810). For example, "12321" is a giza number because it can be visualized like this:

 2 2
1   1

However, something like "123321" is not a Giza number because there are two digits at the top of the pyramid

 2  2
1    1

In other words, a number is a Giza number if all of the following conditions are met:

  • It has an odd number of digits, and the center digit is the largest

  • It's palindromic (the same read forwards or backwards), and

  • The first half of the digits are strictly increasing by one. (Since it must be palindromic, this means the second half of the digits must be strictly decreasing by one)

You must write a full program or a function that takes a positive integer as input, and determine if it is a Giza number or not. You may take the input as a string or as a number. If it is a Giza number, output a truthy value. Otherwise, a falsy value.

There are a total of 45 Giza numbers, so any one of these inputs should result in a truthy value:


Any other input should give a falsy value. Of course, you do not have to handle invalid inputs, such as non-positive numbers, non-integers, or non-numbers.

As usual, this is , so standard loopholes are banned, and the shortest answer in bytes wins!

  • \$\begingroup\$ what about 0? is that a thruthy? \$\endgroup\$ – tuskiomi Nov 16 '16 at 16:48
  • \$\begingroup\$ @tuskiomi Technically, no, but it's irrelevant because you do not have to handle non-positive numbers. \$\endgroup\$ – DJMcMayhem Nov 16 '16 at 16:49
  • 1
    \$\begingroup\$ The reason I ask is because if it is a giza number, then numbers like 1210, 123210, etc would also be truthy. \$\endgroup\$ – tuskiomi Nov 16 '16 at 16:50
  • 5
    \$\begingroup\$ @tuskiomi Neither of those are palindromic or have an odd number of digits. Unless you're counting a leading 0 but that makes everything way more complicated. \$\endgroup\$ – DJMcMayhem Nov 16 '16 at 16:56
  • 1
    \$\begingroup\$ @nedla2004 I think leading 0's makes input formats more complicated. To keep everything nice and simple, we'll say you can assume that inputs will not contain leading 0's. \$\endgroup\$ – DJMcMayhem Nov 17 '16 at 20:44

33 Answers 33


Python 2, 48 47 46 bytes

lambda s:s[~len(s)/2:]in'987654321'>s==s[::-1]

Test it on Ideone.

How it works

In Python, a chained comparison returns True if and only if all individual comparison do the same. In this specific case, our lambda returns True if and only if all of the following conditions are met.

  • s[~len(s)/2:]in'987654321'

    For a string s of length 2n + 1, ~len(s)/2 returns ~(2n + 1) / 2 = -(2n + 2) / 2 = -(n + 1), so s[~len(s)/2:] yields the rightmost n + 1 characters of s.

    Similarly, for a string s of length 2n, ~len(s)/2 returns ~(2n) / 2 = -(2n + 1) / 2 = -(n + 1) (integer division always round towards -∞, so s[~len(s)/2:] once more yields the rightmost n + 1 characters of s

    The comparison returns True if and only if the rightmost n + 1 characters form a substring of 987654321.

    Note that if they do and s has 2n characters, s cannot be a palindrome; the nth and (n+1)th characters from the right will be distinct, and the latter is the nth character from the left.

  • '987654321'>s

    This compares the strings lexicographically. Since 9 is the only Giza number that starts with 9, all Giza numbers satisfy this comparison.

    Note that comparing these strings does not form part of our decision problem; >s is simply three characters shorter than and s.

  • s==s[::-1]

    This returns True if and only if s is a palindrome.

  • 8
    \$\begingroup\$ This answer is insane wizardry. I understand how bits and pieces of it work, but can't even begin to comprehend how you came up with it. And for a moment there, I was proud of my 64. +1 \$\endgroup\$ – DJMcMayhem Nov 16 '16 at 20:26
  • 2
    \$\begingroup\$ i love the guaranteed comparison to save those 3 bytes \$\endgroup\$ – greyShift Nov 17 '16 at 22:12

Perl, 39 37 42 39 + 1 = 40 bytes

Using a new method, I managed to cut down a huge number of bytes. Run with the -n flag. Accepts input repeatedly at runtime, printing 0 or 1 accordingly.

I had to add 5 bytes because I realized without it, the code worked for inputs such as 1234567900987654321, which is not a Giza number. Since Giza numbers never contain the digit 0 (and all false positives by necessity would contain the digit 0), these 5 bytes account for that.

say!/0/*($_- s/..?/1/gr**2)=~/^(.)\1*$/


say!/0/*($_- s/..?/1/gr**2)=~/^(.)\1*$/  #$_ contains input by default.
   !/0/                                  #Ensure that the initial text doesn't contain the number 0
       *                                 #Since both halves of this line return either 0 or 1, multiplying them together only yields 1 if both are true (which we want).
             s/   / /gr                  #Perform a substitution regex on $_ (see below)
                                         #/g means keep replacing, /r means don't modify original string; return the result instead
               ..?                       #Replace 1 or 2 characters (2, if possible)...
                   1                     #...with the number 1
                       **2               #Square this number...
        ($_-              )              #...and subtract it from the input
                           =~            #Do a regex match on the result
                             /^      $/  #Make sure the regex matches the WHOLE string
                               (.)       #Match any character...
                                  \1*    #...followed by itself 0 or more times
say                                      #Finally, output the result of the whole line of code.

The purpose of the substitution regex is to construct a string of 1s whose length is half the length of the input, rounded up. Thus, an input of 12321 will produce the string 111, which then gets squared (explanation below). Even-length inputs will produce strings that are too small to ensure the final regex is successful.

The reason this code works is because of the following:

        1         =         1**2
       121        =        11**2
      12321       =       111**2
     1234321      =      1111**2
    123454321     =     11111**2
   12345654321    =    111111**2
  1234567654321   =   1111111**2
 123456787654321  =  11111111**2
12345678987654321 = 111111111**2

We can clearly see that the number of 1's in RHS is equal to 1/2 more than half the size of LHS. (1 more if we truncate). Additionally:

567898765 - 123454321 = 444444444, which is just 4 repeating. So when we subtract our square from our number, if we get a repdigit, our original number is a Giza number.

Old code and old method (58 + 1 = 59 bytes)

Saved 1 byte thanks to @Dada

Run with the -n flag, pipe text in using echo


Calculates the unique giza number determined by the length and the leading integer, and sees if it matches the input.

Run as echo -n "123454321" | perl -M5.010 -n giza.pl Returns 1 if it's a Giza number, null otherwise.

  • 2
    \$\begingroup\$ That's a beautiful observation for the second method. \$\endgroup\$ – trichoplax Nov 17 '16 at 23:20

Jelly, 10 7 6 bytes


Generates all 45 Giza numbers numbers, then tests for membership.

Try it online! or see the generated numbers.

How it works

9ẆŒBḌċ  Main link. Argument: n

9       Set the return value to 9.
 Ẇ      Windows; yield all "substrings" of [1, ..., 9].
  ŒB    Bounce; map each [a, ..., b] to [a, ..., b, ..., a].
    Ḍ   Undecimal; convert the digit arrays to integers.
     ċ  Count the number of occurrences of n.

JavaScript (ES6), 46 45 42 41 bytes


Takes input as a string and returns a single-digit string for truthy, 0 for falsy.

The basic idea is to check for a few things:

  • If the string is one char long, OR
  • the first char is the same as the last char, and
  • the middle section is also a Giza number, and
  • the second char is one more than the first char here.
  • \$\begingroup\$ Sorry, I misread the question. \$\endgroup\$ – Neil Nov 16 '16 at 20:31

Java 7, 128 119 105 bytes

boolean t(long n){long a=1,b=1,c=0;for(;a<n/10;b=b*b<=n/10?b*10+1:b,c^=1)a=a*10+1;return(n-b*b)%a<1&c<1;}

No more strings! So, now I start by generating a 111... number of the same length as input (a), and one shorter to square (b). Then you can subtract b*b from the input and check divisibility by a. c is just there to check odd/even, pay it no mind >_>


boolean t(long n){
    long a=1,b=1,c=0;

Old Method, 119 bytes

boolean g(char[]a){int i=1,l=a.length,b=1,d;for(;i<l;b*=i++>l/2?d==-1?1:0:d==1?1:0)d=a[i]-a[i-1];return b>0?l%2>0:0>1;}

Walks through the array, checking for a difference of 1 (or -1, depending on which half) between each digit. Then just checks to see the length is odd.


boolean g(char[]a){
    int i=1,l=a.length,b=1,d;
    return b>0?l%2>0:0>1;
  • \$\begingroup\$ Why do you need to check to see if the first is the same as the last? \$\endgroup\$ – Nathan Merrill Nov 16 '16 at 16:50
  • 3
    \$\begingroup\$ I have no idea what you mean >_> \$\endgroup\$ – Geobits Nov 16 '16 at 17:04
  • \$\begingroup\$ Is this a valid answer considering the problem specifies that the function must take a positive integer? Of course a char array can represent a positive integer, but I think it's an important distinction. \$\endgroup\$ – Hypino Nov 16 '16 at 17:32
  • 1
    \$\begingroup\$ @Hypino The problem says input can be taken as a string or integer, and char[] counts as a string here, so I'd say it's valid. \$\endgroup\$ – Geobits Nov 16 '16 at 17:37
  • \$\begingroup\$ @Geobits Ah I did miss the part where it said it could be taken as a String. \$\endgroup\$ – Hypino Nov 16 '16 at 17:42

05AB1E, 9 8 bytes

Truthy is 1, falsy is 0.


Uses the CP-1252 encoding. Try it online!

  • \$\begingroup\$ I think that 2ä¬û¹Q would work as well and saves two bytes. \$\endgroup\$ – Osable Nov 17 '16 at 9:57
  • \$\begingroup\$ @Osable 12521 isn't a giza number, this fails for the middle element. \$\endgroup\$ – Magic Octopus Urn Nov 17 '16 at 14:36
  • \$\begingroup\$ I realize now that i skipped the third point (consecutive digits). Nevermind! \$\endgroup\$ – Osable Nov 17 '16 at 14:41
  • \$\begingroup\$ Ahhhh... I was using prefixes, I'll keep substrings in mind for future efforts, neat little hack. \$\endgroup\$ – Magic Octopus Urn Nov 17 '16 at 14:43

Python 2, 77, 76, 64, 63 bytes

f=lambda s:2>len(s)or(s[0]==s[-1]==`int(s[1])-1`and f(s[1:-1]))

A simple recursive solution. Checks to see if the first and last digits equal each other and the second digit minus one. Then checks if the middle is also a Giza number. Returns true once it gets down to a single digit.

One byte saved thanks to @Rod, a ton of bytes saved thanks to DLosc and ETHProductions!

  • \$\begingroup\$ you can swap len(s)==1 with 1==len(s) to save 1 byte on the space, also, the ands could be replaced with * to save 3 bytes \$\endgroup\$ – Rod Nov 16 '16 at 17:48
  • \$\begingroup\$ Just to add to Rod's comment: 1or works too. (As long as it's not a 0 preceding the o--then Python thinks it's an octal number.) \$\endgroup\$ – DLosc Nov 16 '16 at 17:49
  • 1
    \$\begingroup\$ You generally can't replace and with * when short-circuiting behavior is required, as it is in a recursive function. The first and should be replaceable, but it needs two sets of parentheses, which negates any savings. (cc: @Rod) \$\endgroup\$ – DLosc Nov 16 '16 at 17:53
  • 1
    \$\begingroup\$ I don't know much Python, but could you 1) remove the int() around s[0] or 2) use s[0]==`int(s[1])-1` ? \$\endgroup\$ – ETHproductions Nov 16 '16 at 17:55
  • 1
    \$\begingroup\$ Building on @ETHproductions suggestion: s[-1]==s[0]==`int(s[1])-1` (requires Python 2 specifically). \$\endgroup\$ – DLosc Nov 16 '16 at 17:57

PowerShell v3+, 147 108 67 bytes


Radically changed approach. Generates all possible Giza numbers, and then checks whether the input $args[0] is -in that collection. Below is how the collection of Giza numbers is formed:

      1..8|%{                                       }  # Loop from 1 up to 8
             $i=$_;                                    # Set $i to the current number
                   ++$_..9|%{                      }   # Loop from one higher up to 9
                                   $i..$_+--$_..$i     # Build two ranges and concatenate
                                                       # E.g., 2..5 + 4..2
                             -join(               )    # Join into a single string
1..9+(                                               ) # Array concatenate with 1 to 9

Example runs:

PS C:\Tools\Scripts\golfing> 12321,5678765,121,4,123321,1232,5678,13631|%{"$_ --> "+(.\giza-numbers.ps1 "$_")}
12321 --> True
5678765 --> True
121 --> True
4 --> True
123321 --> False
1232 --> False
5678 --> False
13631 --> False
  • \$\begingroup\$ 108 -> 67... looks like you win this time (and probably most of the time) :P \$\endgroup\$ – Yodle Nov 17 '16 at 14:51

Python 3, 65 bytes

lambda x:len(x)<18and x[:len(x)//2+1]in'0123456789'and x[::-1]==x

I'm not entirely sure, but I think this works.

  • 1
    \$\begingroup\$ There are no Giza numbers that start with 0, you can remove that :) There also won't be any numbers longer than 17 that satisfy that condition so you don't need that either. It's essentially the same solution Dennis has :) \$\endgroup\$ – Kade Nov 17 '16 at 19:23
  • \$\begingroup\$ @Shebang but this one was posted first... \$\endgroup\$ – Rod Nov 18 '16 at 18:06
  • \$\begingroup\$ @Rod I wasn't claiming he copied or anything :) \$\endgroup\$ – Kade Nov 18 '16 at 18:24
  • \$\begingroup\$ @Shebang Neither am I c: \$\endgroup\$ – Rod Nov 18 '16 at 18:31

Python 2, 68 73 66 bytes

lambda n:n==`int('1'+len(n)/2%9*'1')**2+int(len(n)*`int(n[0])-1`)`

abusing the fact that 11^2=121, 111^2=12321 and so on, I calculate this and add 1111.. enough times as offset.

  • \$\begingroup\$ Since you are not calling f, you don't need to actually name it. You can save two bytes by removing f= \$\endgroup\$ – DJMcMayhem Nov 16 '16 at 17:34
  • \$\begingroup\$ You should set a cap on this. Input 1234567900987654321 returns true, when it should be false. \$\endgroup\$ – Geobits Nov 16 '16 at 17:44
  • \$\begingroup\$ @Geobits ooops, fixed (I guess?) \$\endgroup\$ – Rod Nov 16 '16 at 18:03

Perl, 41 bytes

40 bytes of code + -p flags.


Outputs 1 if the input is a Giza number, nothing otherwise. Supply the input without final newline to run it :

echo -n '123456787654321' | perl -pe 's/(.)(?=(.))/$1-$2/ge;$_=/^(-1(?1)1|).$/'

Explanations : first, s/(.)(?=(.))/$1-$2/ge replace each digit $1 (followed by $2) by $1-$2. If it's a Giza number, then each digits being one less than the next in the beginning, and one more in the end, then the string should contain only -1 in the first part, and 1 in the second (except the last that is left unchanged). That's what the second part /^(-1(?1)1|).$/ checks : looks for a -1 followed by recursion followed by a 1.

-1 byte thanks to Martin Ender.

My previous version 15 bytes longer (quite different so I'll let it here) :

echo -n '123456787654321' | perl -F -pe '$\=$_ eq reverse;$\&=$F[$_-1]+1==$F[$_]for 1..@F/2}{'
  • \$\begingroup\$ The only part of this I don't understand is the purpose of the | in the second regex. \$\endgroup\$ – Gabriel Benamy Nov 16 '16 at 19:19
  • \$\begingroup\$ @GabrielBenamy That's the base case of the recursive block (ie. it matches nothing and stops the recursion). \$\endgroup\$ – Dada Nov 16 '16 at 19:47

><> FISH 57 52 49 48 bytes

{:<11 ^?:=@:$+=

Edit 1: = returns 0 or 1 if true so removed a check and used this value to increment, then it checks equality after anyway. (saved 6 bytes, lost 1 for new line).

Edit 2: 3 directional markers removed and 11 placed into gap to offset the stack to an even length to force false ( 3 bytes saved).,

Edit 3: Duplicate the length of the stack for checking MOD by 2 and len(1), this was done by putting the length on twice before but this now filled an empty space on line 2 ( 1 byte saved).


C#, 120 86 108 102 92 bytes

x=I=>{var Z=I.Length;return Z<2?1>0:I[0]==I[Z-1]&I[1]-0==I[0]+1?x(I.Substring(1,Z-2)):0>1;};

Full program with some test cases:

class a
    static void Main()
        Func<string, bool> x = null;

        x = I=>
            var Z=I.Length;
            return Z==1?                           // length == 1?
                     1>0:                          // return true (middle of #)
                     I[0]==I[Z-1]&I[1]-0==I[0]+1?  // else start == end and the next number is 1 above the current?
                       x(I.Substring(1,Z-2)):      // recursive call on middle
                       0>1;                        // else false

        Console.WriteLine("1 -> " + (x("1") == true));
        Console.WriteLine("9 -> " + (x("9") == true));
        Console.WriteLine("121 -> " + (x("121") == true));
        Console.WriteLine("12321 -> " + (x("12321") == true));
        Console.WriteLine("4567654 -> " + (x("4567654") == true));
        Console.WriteLine("12345678987654321 -> " + (x("12345678987654321") == true));
        Console.WriteLine("12 -> " + (x("12") == false));
        Console.WriteLine("1221 -> " + (x("1221") == false));
        Console.WriteLine("16436346 -> " + (x("16436346") == false));
        Console.WriteLine("123321 -> " + (x("123321") == false));
        Console.WriteLine("3454321 -> " + (x("3454321") == false));
        Console.WriteLine("13631 -> " + (x("13631") == false));
        Console.WriteLine("191 -> " + (x("13631") == false));
        Console.Read(); // For Visual Studio

Hooray for single line conditionals, now beating the Java answer :)! Also got to write my first explaining comments, though it's probably self explanatory. Thanks to @Dada for finding a problem with my algorithm (was true for numbers that were mirrored like 13631). Now sub 100 since apparently checking for length%2 is redundant.

  • 1
    \$\begingroup\$ Wouldn't this return true for numbers like 13631 ? Also since you make a recursive call to x, I think you need to include x= in your byte count. \$\endgroup\$ – Dada Nov 16 '16 at 20:00
  • \$\begingroup\$ @Dada Heh good point, knew I was missing something... And alright, I'll add those to the count. \$\endgroup\$ – Yodle Nov 16 '16 at 20:01
  • \$\begingroup\$ Wait, you're beating what now? ;) \$\endgroup\$ – Geobits Nov 17 '16 at 2:14
  • \$\begingroup\$ @Geobits Dangit! I'll see what I can do tomorrow :P \$\endgroup\$ – Yodle Nov 17 '16 at 2:43

Bash, 111 bytes


Note that input number normalization can probably be skipped completely, if you just add the first digit back to your generated GIZA number, like that:

01210 + 6 => 67876

and then just compare it with the input directly.

Disclaimer: this one is not really optimized, so it is more a proof of concept than a real contender


G() { I=`sed "s/./\0-${1::1}\n/g"<<<$1|bc`;Z=`seq 0 $((${#1}/2))`;A=`rev <<<$Z`;cmp -s <(echo $I) <<<$Z${A:1}


Any GIZA number can be normalized to its canonical form, by substracting its first digit from the rest:

67876 - 6 => 01210
78987 - 7 => 01210

and there is only one canonical GIZA number of a particular length.

Knowing this we can easily generate a canonical GIZA number based on the input number length:

 Z=`seq 0 $((${#1}/2))`;A=`rev <<<$Z` => $Z${A:1}

then normalize the input number:

 I=`sed "s/./\0-${1::1}\n/g"<<<$1|bc`

and compare

 cmp -s <(echo $I) <<<$Z${A:1};


for i in `seq 0 1000`; do G $i && echo $i; done



G 12345678987654321 && echo "OK" || echo FALSE     

G 123456789987654321 && echo "OK" || echo FALSE
  • \$\begingroup\$ I hope you don't mind, I implemented a part of this algorithm in my answer :) \$\endgroup\$ – FlipTack Nov 18 '16 at 10:42

Actually, 22 bytes


Try it online!

Takes input as a quoted string (e.g. "12321"). Output is a positive integer for true, and 0 for false.


9uR;∙                   cartesian product of [1,2,3,4,5,6,7,8,9,10] with itself
     `xR;RdX+εj`M       for each pair:
      x                   construct the half-open (end-exclusive) range ([1, 5] -> [1, 2, 3, 4])
       R                  reverse
        ;RdX+             duplicate, reverse, remove first element, prepend ([1, 2, 3, 4] -> [1, 2, 3, 4, 3, 2, 1])
             εj           concatenate into a string
                 ;░     filter out empty strings
                   #íu  test for membership

Haskell, 62 bytes

(`elem`[[j..pred i]++[i,pred i..j]|i<-['1'..'9'],j<-['1'..i]])

The input is taken as a string.

Creates a list of all Giza numbers an checks if the number is in it. The list is created by looping i through '1'..'9' and then j through '1'..i and creating the elements j .. i-1 , i , i-1 .. j.


><>, 62 bytes

i:0(   ?v

Try it online!

Outputs 1 for a Giza number; 0 otherwise. Works by pushing the input into a dequeue (ok, technically a reversible stack) and repeatedly testing both ends for equality, as well as making sure they are exactly one larger than the previous value.


CJam, 20 19 bytes


Test suite.


The basic idea is to find the minimum and maximum digit, then create a Giza number from those and then check that it's equivalent to the input.

l       e# Read input.
_$      e# Get a sorted copy of the input.
_W=     e# Get its last character, i.e. the maximum digit M.
),      e# Get a string with all characters from the null byte up to M.
\c      e# Get the first character of the sorted string, i.e. the minimum
        e# character m.
i>      e# Convert to its character code and discard that many leading
        e# characters from the string we generated before. Now we've got
        e# a string with all digits from m to M, inclusive.
_W<W%+  e# Palindromise it, by appending a reversed copy without M.
=       e# Check that it's equal to the input.

Instead of the minimum character, we can also use the first character, for the same byte count:


Mathematica, 62 61 60 bytes

Saved 2 bytes due to @MartinEnder.


Composition of functions. Takes a number as input and returns True or False as output.


Retina, 55 54 36 bytes

Byte count assumes ISO 8859-1 encoding.


Try it online

Convert each digit to unary, separated by colons. Loop, removing matching outer digits if the next digit is one more. Match a single remaining digit.


PHP, 71 bytes


fetches the largest digit from input and counts down, adding the new digit to a comparison string until input and comparison string are equal - or $i is 0.

prints the lowest digit for a Timmy Number, 0 else.


Pushy, 30 15 bytes

I woke up this morning and realise I could half the length of my answer...


(non-competing as the language postdates challenge)

Input is given on the command line: $ pushy gizas.pshy 3456543. Outputs 1 for truthy and 0 for falsy. Here's the breakdown:

s                  % Split the number into its individual digits
 &K-               % Subtract all digits by the last 
    kL2/  h        % Get the halved length of the stack (+1)
        Ov X       % In stack 2, generate range (0, halved length)
            w      % Mirror the range 
             x#    % Check stack equality and output

The algorithm was inspired by the bash answer: first, normalize the number, (45654 -> 01210), then generate the normalized giza number of the same length (there is only one), and compare.

Old Solution


Racket 292 bytes

(let*((s(number->string n))(sn string->number)(st string)(lr list-ref)(sl(string->list s))(g(λ(i)(-(sn(st(lr sl(add1 i))))
(sn(st(lr sl i)))))))(cond[(even?(string-length s))#f][(not(equal? s(list->string(reverse sl))))#f][(andmap identity
(for/list((i(floor(/(length sl)2))))(= 1(g i))))]))


(define(f n)
  (let* ((s (number->string n))
         (sn string->number)
         (st string)
         (lr list-ref)
         (sl (string->list s))
         (g (λ (i) (- (sn(st(lr sl (add1 i))))
                      (sn(st(lr sl i)))))))
      [(even? (string-length s))
      [(not(equal? s (list->string (reverse sl))))
       (andmap identity
               (for/list ((i (floor(/(length sl)2))))
                 (= 1 (g i))))]


(f 12321) 
(f 123321)  ; only this should be false; 

(f 9)
(f 787)
(f 67876)
(f 4567654)
(f 123454321)
(f 12345654321)
(f 1234567654321)
(f 123456787654321)
(f 12345678987654321)



Java 8, 162 + 19 bytes

19 for import java.util.*;

s->{List f=new ArrayList();for(int i=0;i<9;){String l=String.valueOf(++i);for(int j=i;j>0;){f.add(l);String k=String.valueOf(--j);l=k+l+k;}}return f.contains(s);}

Different approach to the other Java answer, I wanted to try and use the method of creating all the possible Timmy numbers and checking to see if our string was contained in them.


Octave, 56 bytes


Check out all test cases here.

This would be two less bytes in MATLAB, since diff(n) works for strings. In Octave, you need diff(+n).


@(n)                  % Anonymous function taking a string `n` as argument
    nnz(n)<2          % True if there is only one element in n
            ||        % Short circuit or operator. Expression will be true if this is true
~(abs(diff(+n))-1)    % Takes the absolute value of the difference between adjacent numbers
                      % which should always be 1. Subtracts 1, to get 0
                      % and negates it to get 1 (true)
diff(+n(1:1+end/2))==1   % Checks if the difference between the first half of the numbers
                         % is 1.
                      % If either the first, or both the second and third argument is true
                      % then the function will return 1, otherwise 0. 

Mathematica, 56 bytes

This is a little shorter:


Java 7, 129 119 109 bytes

boolean e(char[]a){int l=a[0]-1,f=0,b=a.length-1;for(;f<b&&a[f]==++l&a[f++]==a[b--];);return f==b&l==a[b]-1;}

Old Recursive Method, 119

boolean b(char[]a){int b=a.length;return b>1&&a[0]==a[b-1]&a[0]+1==a[1]?b(java.util.Arrays.copyOfRange(a,1,b-1)):b==1;}

-10 bytes thanks to Geobits. We are were tied...

Try it online!

  • \$\begingroup\$ I think you could save 1 byte with bitwise and, I think you used it once but didn't the other time? Or I'm reading it wrong. \$\endgroup\$ – Yodle Nov 16 '16 at 20:58
  • \$\begingroup\$ @Yodle I only used it once because I need to short circuit for the first condition. \$\endgroup\$ – Poke Nov 16 '16 at 21:00
  • 1
    \$\begingroup\$ It looks like you're only using the import once, so you should be able to shorten this by using java.util.Arrays.copyOfRange(...) to skip the import line. \$\endgroup\$ – Geobits Nov 17 '16 at 2:23
  • \$\begingroup\$ @Geobits good catch... I derp \$\endgroup\$ – Poke Nov 17 '16 at 14:13

Perl 6, 43 34 bytes

Thanks to Jo King for -9 bytes.

{!/0/==set comb $_- S:g/..?/1/²:}

Port of Gabriel Benamy's Perl solution.

Try it online!


Cjam, 35 bytes

Probably very suboptimal... I'm a little out of practice!


Try it online!


Python 2, 50 82 81 80 bytes

def f(a):b=len(a)/2+1;print(1,0)[a[:b-1]!=a[b:][::-1]or a[:b]not in'123456789']

Simple approach. Just splits the string in half (missing out the middle character or one after the middle character if it is of even length), reverses the second half then compares the two and compares the first half with a string of 1 to 9.


Reposted after constructive feedback from fellow golfers and realising and correcting my mistakes.

-1 for losing a (waste of) space

-1 for reading the question again and realising that we don't need to take 0 into account. Really must stop golfing after a long day at work.

  • 1
    \$\begingroup\$ This doesn't check if numbers are strictly increasing by one. For example, 13531, and 6543456 both incorrectly return True. \$\endgroup\$ – DJMcMayhem Nov 16 '16 at 20:03
  • 1
    \$\begingroup\$ Also, the strings '0' and '1' are both truthy. \$\endgroup\$ – Dennis Nov 16 '16 at 20:03
  • \$\begingroup\$ Absolutely right. It's been a long day. Will delete as invalid. \$\endgroup\$ – ElPedro Nov 16 '16 at 20:07
  • 4
    \$\begingroup\$ Thanks for the comments and not just downvoting. \$\endgroup\$ – ElPedro Nov 16 '16 at 20:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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