20
\$\begingroup\$

A hill number is a number that has the same digit in the first & the last, but that's not all. In a hill number the first digits are strictly increasing until the largest digit, and after the largest digit, the last digits are strictly decreasing. The largest digit can be repeated but consecutively only, meaning no gaps by smaller numbers.

Here is an example of a hill number:

12377731 | 1237...             | ...731
^ same ^ | strictly increasing | strictly decreasing 
---------+---------------------+---------------------
12377731
   ^^^ okay because largest digit can be repeated

This is not:

4588774 | ...8774
        |     ^^ not the largest digit
        |        so this has to be strictly decreasing
        |        but it's not, so not a hill number

Challenge

Given a positive integer, write a full program or a function that returns truthy for hill numbers but falsy on other values.

Notes:

  • Input & output can be in any reasonable format.
  • This is so shortest answer in each language wins!

Test Cases

12321 -> Truthy
1233321 -> Truthy
99 -> Truthy
3 -> Truthy
234567992 -> Truthy
5555555 -> Truthy
1232 -> Falsy
778896 -> Falsy
23232 -> Falsy
45566554 -> Falsy
5645 -> Falsy
\$\endgroup\$
13
  • 5
    \$\begingroup\$ What about 222222222? Is it a flat hill number? \$\endgroup\$
    – frarugi87
    Commented Nov 19, 2018 at 14:56
  • 1
    \$\begingroup\$ 222222222 is a hill number, largest digit is 2 and thus can be repeated \$\endgroup\$
    – u-ndefined
    Commented Nov 20, 2018 at 13:02
  • 1
    \$\begingroup\$ Is a string reasonable? \$\endgroup\$
    – Sanchises
    Commented Nov 20, 2018 at 13:11
  • \$\begingroup\$ @frarugi87 See comment above. \$\endgroup\$
    – Dennis
    Commented Nov 20, 2018 at 13:27
  • \$\begingroup\$ Is 1230321 a hill number? \$\endgroup\$ Commented Nov 21, 2018 at 8:50

20 Answers 20

10
\$\begingroup\$

Jelly, 8 bytes

_ƝṠÞ+SƊƑ

Try it online!

How it works

_ƝṠÞ+SƊƑ  Main link. Argument: n (integer)

_Ɲ        Take the differences of neighboring digits.
          This maps n = abcd to [a-b, b-c, c-d].
       Ƒ  Fixed; apply the link to the left and return 1 if the result is equal to
          its argument, 0 if not.
      Ɗ       Drei; combine the three links to the left into a monadic chain.
  ṠÞ              Sort the differences by their signs (negative, zero, positive).
     S            Take the sum of the differences, yielding 0 if and only if the
                  first digit is equal to the last.
    +             Add the sum to each difference.
\$\endgroup\$
6
\$\begingroup\$

JavaScript (ES6), 62 54 bytes

Takes input as a string. Returns a Boolean value.

s=>s[-[...s].some(p=q=n=>q>(q=Math.sign(p-(p=n))))]==p

Try it online!

Commented

s =>                  // s = input string
  s[                  // we will eventually access either s[0] or s[-1]
    -[...s].some(     // depending on the result of this some()
      p = q =         // initialize p and q to non-numeric values
      n =>            // for each digit n:
        q > (         //   compare q with
          q =         //   the new value of q,
          Math.sign(  //   defined as the sign of
          p - (p = n) //   the difference between the current digit and the previous one
        ))            //   yield true if the previous q is greater than the new q
    )                 // s[-1] being undefined, a truhty some() will force the test to fail
  ] == p              // otherwise: test if the 1st digit s[0] is equal to the last digit p

JavaScript (ES6), 65 bytes

A solution using a regular expression. Takes input as a string. Returns \$0\$ or \$1\$.

s=>/N(,-\d+)*(,0)*[^0-]*$/.test([...s].map(p=v=>p-(p=v)))&p==s[0]

Try it online!

How?

We first convert the number to a list of pairwise digit differences in \$[-9,9]\$:

[...s].map(p = v => p - (p = v))

Example:

"234567992" --> [ NaN, -1, -1, -1, -1, -1, -2, 0, 7 ]

This array is coerced to a string, which gives:

"NaN,-1,-1,-1,-1,-1,-2,0,7"

We apply the following regular expression:

 +-----------------------> the second 'N' of 'NaN'
 |    +------------------> a sequence of negative numbers
 |    |     +------------> a sequence of zeros
 |    |     |     +------> a sequence of positive numbers
 |    |     |     |  +---> end of string
 |    |     |     |  |
 |/¨¨¨¨¨¨\/¨¨¨\/¨¨¨¨\|
/N(,-\d+)*(,0)*[^0-]*$/

Finally, we also test if the last digit p is equal to the first digit s[0].

\$\endgroup\$
3
  • \$\begingroup\$ You can save 5 bytes by taking input as an array of digits. \$\endgroup\$
    – Shaggy
    Commented Nov 19, 2018 at 19:11
  • \$\begingroup\$ @Shaggy I wish I could but this is apparently not allowed . \$\endgroup\$
    – Arnauld
    Commented Nov 19, 2018 at 19:25
  • \$\begingroup\$ From the spec, with original emphasis: "Input & output can be in any reasonable format" - we usually consider a digit array a reasonable format for an integer. \$\endgroup\$
    – Shaggy
    Commented Nov 19, 2018 at 19:47
4
\$\begingroup\$

Pyth, 16 bytes

&SI_._MJ.+jQT!sJ

Try the test suite.

          jQT          input in base 10
       J.+             J = differences: [3,1,4,1] -> [-2,3,-3]
    ._M                Signs of each element of J
   _                   Reverse the list
 SI                    and check if it is Invariant under Sorting.
                       If this is true, J consists of some positive numbers,
                         followed by some 0s, followed by some negative numbers,
                         which is what we want.
            !sJ        Now we check the other hill condition by ensuring
                         sum(differences) = 0; i.e. the first and last digit are equal.
&                      We take the logical AND of both conditions.
\$\endgroup\$
4
\$\begingroup\$

Jelly, 11 bytes

DIµṠNṢƑaS¬$

Explanation:

D               Convert to a list of Digits.
 I              Increments; compute differences between successive elements.
  µ             Start new µonadic link.
   Ṡ              Find Ṡign of each increment
    N             then negate;
     ṢƑ           is the result invariant under Ṣorting?
                  If so, the increments consist of some positive numbers,
                     followed by some 0s, followed by some negative numbers,
                     which is what we want.
       a          Logical AND this result with
        S¬$       logical NOT of the Sum of the increments.
                  If the sum of the increments is zero, first and last digits are equal.

Try it online!

\$\endgroup\$
4
\$\begingroup\$

Perl 6, 39 bytes

{.[0]==.tail&&[<=] $_ Z<=>.skip}o*.comb

Try it online!

Explanation

{ ... }o.comb  # Split into digits and feed into block
.[0]==.tail    # First element equals last
&&             # and
     $_ Z<=>.skip  # Pairwise application of three-way comparator
[<=]           # Results never decrease
\$\endgroup\$
1
  • \$\begingroup\$ I was literally seconds away from posting this lol. \$\endgroup\$
    – Jo King
    Commented Nov 19, 2018 at 12:41
3
\$\begingroup\$

Python 2, 114 112 bytes

lambda n:all((n[0]==n[-1])*sorted(set(x))==list(x)[::d]for x,d in zip(n.split(max(n)*n.count(max(n)),1),[1,-1]))

Try it online!

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

R, 65 bytes

Takes strings. Took the idea for checking sort invariance from the Pyth answer.

function(a)!sum(d<-diff(utf8ToInt(a)))&all(sort(k<-sign(d),T)==k)

Try it online!

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

05AB1E, 19 17 13 12 bytes

¥D.±Â{RQsO_*

-5 bytes by creating a port of @lirtosiast's Pyth answer.

Try it online or verify all test cases.

Explanation:

¥           # Push the deltas of the digits of the (implicit) input
            #  i.e. 4588774 → [1,3,0,-1,0,-3]
 D          # Duplicate this list
  .±        # Get the sign of each
            #  [1,3,0,-1,0,-3] → [1,1,0,-1,0,-1]
    Â       # Bifurcate (short for DR: Duplicate and Reverse copy)
            #  i.e. [1,1,0,-1,0,-1] → [-1,0,-1,0,1,1]
     {      # Sort the copy
            #  i.e. [-1,0,-1,0,1,1] → [-1,-1,0,0,1,1]
      R     # Reverse it
            #  i.e. [1,1,0,0,-1,-1]
       Q    # And check if they are equal
            #  i.e. [1,1,0,-1,0,-1] and [1,1,0,0,-1,-1] → 0 (falsey)
s           # Swap to get the list of deltas again
 O          # Take the sum
            #  i.e. [1,3,0,-1,0,-3] → 0
  _         # And check if it's exactly 0
            #  0 → 1 (truthy)
*           # Check if both are truthy (and output implicitly)
            #  i.e. 0 and 1 → 0 (falsey)

Â{RQ can alternatively be (Â{Q for the same byte-count, where ( negates each sign: Try it online.

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

J, 23 bytes

[:((0=+/)**-:*/:*)2-/\]

Idea stolen from the Jelly answers. Just wanted to see how short I could make it in J.

Try it online!

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

Python 2, 53 bytes

def f(s):x=map(cmp,s,s[1:]);s[:sorted(x)==x]!=s[-1]>_

Takes input as a string. Output is via presence or absence of an exception.

Try it online!


Python 2, 62 bytes

lambda s:s[:eval('<='.join(map(str,map(cmp,s,s[1:]))))]==s[-1]

Takes input as a string and returns a Boolean.

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Whoa, I've been hurting my head for hours and I couldn't even come up with something shorter than the combined byte count of your 2 solutions ! Cheers. \$\endgroup\$
    – etene
    Commented Nov 20, 2018 at 17:01
2
\$\begingroup\$

MATL, 12 bytes

dZSd1<AGds~*

Try it online!

Explanation

Input is a string of digits. Output is a 1 or 0. The number 222222 is a hill number according to this program. Saved 2 bytes by copying Dennis' method for checking equality of the first and last digits.

d               % Takes the difference between digits
 ZS             % Calculate the sign. 
   d            % Take the difference again. 
    1<          % A number is a hill number if these differences are < 1.
      A         % Truthy iff above is all true OR if array is empty (necessary for short inputs)
       Gds      % Push the input, and sum all the differences.
          ~     % Negate
           *    % Multiply the two tests (=logical AND).
\$\endgroup\$
0
2
\$\begingroup\$

Ruby, 47 bytes

->n{(r=n.each_cons(2).map{|a,b|a<=>b})==r.sort}

Try it online!

Input as array of digits, output is boolean.

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

Mathematica/Wolfram Language, 69 64 bytes

Pure function. Takes input as an integer, returns True or False.

Sort[x=Sign@-Differences[y=IntegerDigits@#]]==x&&y[[1]]==Last@y&

Explanation:

The first clause checks the "hilliness":

  • IntegerDigits: Get digits from integer. Store in y.
  • -Differences: Take successive differences and flip signs.
  • Sign: Replace each entry with +1 if positive, 0 if zero, and -1 if negative. Store in x.
  • Sort: Sort list of +1, 0, -1 from smallest to largest. Compare to original list in x.

The second clause checks whether the first and last digits are equal.

A tip of the hat to @IanMiller for tips on refining this code.

\$\endgroup\$
2
  • \$\begingroup\$ The fact that IntegerDigits and Differences are rather long function names is a bit annoying. \$\endgroup\$ Commented Nov 19, 2018 at 18:58
  • \$\begingroup\$ Can save 5 bytes with the following changes: Sort[x=Sign@-Differences[y=IntegerDigits@#]]==x&&y[[1]]==Last@y& \$\endgroup\$
    – Ian Miller
    Commented Nov 23, 2018 at 12:54
1
\$\begingroup\$

Japt, 11 bytes

Takes input as a digit array.

ä-
eUñg)«Ux

Try it or run all test cases

             :Implicit input of digit array U
ä-           :Deltas
\n           :Reassign to U
 Uñ          :Sort U
   g         :  By signs
e   )        :Check for equality with U
     «       :Logical AND with the negation of
      Ux     :U reduced by addition
\$\endgroup\$
1
\$\begingroup\$

C# (Visual C# Interactive Compiler), 115 bytes

s=>!s.Where((c,i)=>i<1?c!=s[^1]:i>s.LastIndexOf(s.Max())?c>=s[i-1]:i>s.IndexOf(s.Max())?s.Max()!=c:c<=s[i-1]).Any()

Try it online!

Here is an overview of how this works...

  1. Input is in the form of a string
  2. Find the largest digit
  3. Ensure the first and last digits are the same
  4. Ensure digits after the last occurrence of the largest digit are decreasing
  5. Ensure digits between the first and last occurrence of the largest digit are equal to the largest digit
  6. Ensure digits before the first occurrence of the largest digit are increasing
\$\endgroup\$
1
\$\begingroup\$

Burlesque, 22 bytes

XXJl_-]==j2COqcm^mso&&

Try it online!

XX    # Explode into digits
J     # Duplicate
l_-]  # Head & Tail
==    # Are equal
j     # Reorder stack
2CO   # 2-grams
qcm^m # Compare with UFO operator
so    # If sorted
&&    # If going up then down AND head-tail is equal
\$\endgroup\$
0
\$\begingroup\$

Retina 0.8.2, 52 bytes

.
$*1;$&$*1,
(1+),\1
,
^(1+);(,1+;)*(,;)*(1+,;)*\1,$

Try it online! Link includes test cases. Explanation:

.
$*1;$&$*1,

Convert each digit to unary twice, separated by ;s and terminated by ,s. However, you can then think of the result as the first digit, a ;, then all the pairs of adjacent digits, the digits of each pair separated by , and the pairs separated by ;s, then another ;, then the last digit, then a final ,.

(1+),\1
,

Subtract the pairs of adjacent digits. This leaves ;,; for equal digits and 1s on the greater side for unequal digits. (This could be done as part of the following regex but obviously that wouldn't be so golfy.)

^(1+);(,1+;)*(,;)*(1+,;)*\1,$

Match the first digit, then any number of pairs of ascending digits, then any number of pairs of equal digits, then any number of pairs of descending digits, then match the first digit again at the very end.

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

Red, 181 bytes

func[n][m: last sort copy t: s: form n
parse t[opt[copy a to m(a: sort unique a)]copy b thru any m
opt[copy c to end(c: sort/reverse unique c)]](s = rejoin[a b c])and(s/1 = last s)]

Try it online!

More readable:

f: func[n][
    t: s: form n                                    
    m: last sort copy t                             
    parse t [ opt [ copy a to m (a: sort unique a) ] 
              copy b thru any m
              opt [ copy c to end (c: sort/reverse unique c) ]
            ]
    (s = rejoin [ a b c ]) and (s/1 = last s)
]
\$\endgroup\$
0
\$\begingroup\$

Powershell, 77 bytes

($x=-join("$($args|%{"-$_;$_"})"|iex))-match'^(-\d)+0*\d+$'-and$x[1]-eq$x[-1]

Less golfed test script:

$f = {
                                           # $args = 1,2,3,3,3,2,1
$a=$args|%{"-$_;$_"}                       # "-1;1","-2;2","-3;3","-3;3","-3;3","-2;2","-1;1"
$d="$a"                                    # "-1;1 -2;2 -3;3 -3;3 -3;3 -2;2 -1;1"
$x=-join($d|Invoke-Expression)             # "-1-1-100111"
$x-match'^(-\d)+0*\d+$'-and$x[1]-eq$x[-1]  # $true or $false

}

@(
    ,($True , 1,2,3,2,1 )
    ,($True , 1,2,3,3,3,2,1 )
    ,($True , 9,9 )
    ,($True , 3 )
    ,($True , 2,3,4,5,6,7,9,9,2 )
    ,($False, 1,2,3,2 )
    ,($False, 7,7,8,8,9,6 )
    ,($False, 2,3,2,3,2 )
    ,($False, 4,5,5,6,6,5,5,4 )
    ,($False, 5,6,4,5 )
) | % {
    $expected,$a = $_
    $result = &$f @a
    "$($result-eq$expected): $result"
}

Output:

True: True
True: True
True: True
True: True
True: True
True: False
True: False
True: False
True: False
True: False
\$\endgroup\$
0
\$\begingroup\$

Python 3, 114 bytes

def f(r):
 l=[*r]
 for i in-1,0:
  while 1<len(l)and l[i]<l[(1,-2)[i]]:l.pop(i)
 return 2>len({*l})and r[0]==r[-1]

Try it online!

Way longer than some Python 2 solutions, but this one is def-based and I like it.

\$\endgroup\$

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.