这个数字是小山数字吗?


17

小山号是在第一个和最后一个具有相同数字的数字,但这还不是全部。在山丘数中,前几位数严格增加,而后几位数严格减少。可以重复的最大数字

这是一个山顶数字的示例:

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

不是

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

挑战

给定一个正整数,编写一个完整的程序或一个函数,该函数将返回希尔数为真但其他值则为假的函数。

笔记:

  • 输入和输出可以采用任何合理的格式
  • 这是所以每种语言的最短答案都可以胜出!

测试用例

12321 -> Truthy
1233321 -> Truthy
99 -> Truthy
3 -> Truthy
234567992 -> Truthy
1232 -> Falsy
778896 -> Falsy
23232 -> Falsy
45566554 -> Falsy
5645 -> Falsy

5
222222222呢 它是平坦的山顶数字吗?
frarugi87 '18

1
222222222是山丘数字,最大位数为2,因此可以重复
u_ndefined

1
字符串合理吗?
桑契斯

@ frarugi87参见上面的评论。
丹尼斯

1230321山号吗?
HelloGoodbye

Answers:


10

果冻,8字节

_ƝṠÞ+SƊƑ

在线尝试!

怎么运行的

_ƝṠÞ+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.

6

JavaScript(ES6),62 54字节

将输入作为字符串。返回一个布尔值。

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

在线尝试!

已评论

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个字节

01个

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

在线尝试!

怎么样?

[-99]

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

例:

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

该数组被强制为字符串,该字符串给出:

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

我们应用以下正则表达式:

 +-----------------------> 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-]*$/

最后,我们还要测试最后一位p是否等于第一位s[0]


通过将输入作为数字数组可以节省5个字节。
毛茸茸的

@Shaggy我希望可以,但是显然不允许这样做
Arnauld

从规范开始,我们首先强调:“输入和输出可以采用任何合理的格式 ”-我们通常认为数字数组是整数的合理格式。
毛茸茸的

4

Pyth,16个字节

&SI_._MJ.+jQT!sJ

尝试测试套件

          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.

4

果冻,11字节

DIµṠNṢƑaS¬$

说明:

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.

在线尝试!


4

Perl 6 6,39个字节

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

在线尝试!

说明

{ ... }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

从字面上我离发布这个笑声只有几秒钟的路程。
Jo King


3

[R,65个字节

需要字符串。提出了从Pyth答案检查排序不变性的想法。

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

在线尝试!


2

05AB1E19 17 13 12 字节

¥D.±Â{RQsO_*

通过创建@lirtosiast的Pyth答案的端口来生成-5字节。

在线尝试验证所有测试用例

说明:

¥           # 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也可以(Â{Q针对相同的字节数,其中(每个符号取反:在线尝试


2

J,23个字节

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

从果冻答案中窃取的主意。只想看看我在J中能做多短。

在线尝试!


2

MATL,12字节

dZSd1<AGds~*

在线尝试!

说明

输入是一串数字。输出为10。该编号222222是根据此程序的山坡编号。通过复制Dennis的方法来检查前两位数字是否相等,从而节省了2个字节。

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).

1

Python 2,53个字节

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

将输入作为字符串。输出是通过是否存在异常来进行的

在线尝试!


Python 2,62个字节

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

将输入作为字符串并返回布尔值。

在线尝试!


哇,我已经伤了好几个小时了,我什至无法想出比您的2个解决方案的总字节数还短的东西!干杯。
etene

1

Mathematica / Wolfram语言,69 64字节

纯功能。将输入作为整数,返回TrueFalse

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

说明:

第一条检查“湿度”:

  • IntegerDigits:从整数获取数字。存放在y
  • -Differences:采取连续的差异并翻转标志。
  • Sign:将每个条目替换为+1(如果为正),0(如果为零)和-1(如果为负)。存放在x
  • Sort:将+ 1、0,-1的列表从最小到最大排序。与中的原始列表进行比较x

第二个子句检查第一位和最后一位是否相等。

@IanMiller的技巧提示,以完善此代码。


IntegerDigitsDifferences是相当长的函数名称的事实有点令人讨厌。
迈克尔·塞弗特

可以保存5个字节,并进行以下更改:Sort[x=Sign@-Differences[y=IntegerDigits@#]]==x&&y[[1]]==Last@y&
伊恩·米勒

1

Japt,11个字节

将输入作为数字数组。

ä-
eUñg)«Ux

尝试运行所有测试用例

             :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

0

视网膜0.8.2,52字节

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

在线尝试!链接包括测试用例。说明:

.
$*1;$&$*1,

将每个数字转换为一元两次,以;s 分隔并以s终止,。但是,您可以将结果视为第一个数字a ;,然后是所有相邻数字对,每个对的数字,;s 分隔,而对对被s 分隔,然后是另一个;,然后是最后一个数字,最后是final ,

(1+),\1
,

减去相邻的数字对。留下;,;相等的数字,而1s留在较大的一侧,代表不相等的数字。(这可以作为以下正则表达式的一部分来完成,但显然并不是那么容易。)

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

匹配第一个数字,然后匹配任意对的升序数字对,然后匹配任意对的等位数数字对,然后匹配任意对的降序数字对,然后在最末端再次匹配第一个数字。


0

红色,181字节

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)]

在线尝试!

更具可读性:

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)
]

0

Powershell,77个字节

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

少打高尔夫的测试脚本:

$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"
}

输出:

True: True
True: True
True: True
True: True
True: True
True: False
True: False
True: False
True: False
True: False

0

C#(Visual C#交互式编译器),161字节

s=>{var m=s.OrderBy(c=>c).Last();return s[0]==s.Last()&Enumerable.Range(1,s.Length-1).All(i=>i>s.LastIndexOf(m)?s[i-1]>s[i]:i>s.IndexOf(m)?m==s[i]:s[i-1]<s[i]);}

在线尝试!

这是其工作原理的概述...

  1. 输入形式为 string
  2. 找到最大的数字
  3. 确保第一位和最后一位数字相同
  4. 确保最后一次出现的最大位数减少
  5. 确保最大位数的第一个和最后一个出现之间的位数等于最大位数
  6. 确保在第一次出现最大位数之前数字增加

0

Python 3,114字节

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]

在线尝试!

比某些Python 2解决方案更长的时间,但这是基于def的,我喜欢它。


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.