Número que pode se comer


30

Dado um número inteiro positivo, produza um valor de verdade / falsidade para saber se o número pode comer sozinho.

Regras

Mais à esquerda é a cabeça, mais à direita é a cauda

Se a cabeça é maior ou igual à cauda, ​​a cabeça come a cauda e a nova cabeça se torna sua soma.

Se , a cabeça é substituída por .sum≥10summod10

svocêm=0 0 não pode ser ignorado, no entanto, o número de entrada nunca terá nenhum zero inicial.

Exemplo:

number=2632
head-2, tail-2

2632 -> 463
head-4, tail-3

463 -> 76
head-7, tail-6

76 -> 3
If only one digit remains in the end, the number can eat itself.

Se em algum momento a cabeça não puder comer o rabo, a resposta será falsa.

number=6724
072
False (0<2)

Casos de teste:

True:
[2632, 92258, 60282, 38410,3210, 2302, 2742, 8628, 6793, 1, 2, 10, 100, 55, 121]

False:
[6724, 47, 472, 60247, 33265, 79350, 83147, 93101, 57088, 69513, 62738, 54754, 23931, 7164, 5289, 3435, 3949, 8630, 5018, 6715, 340, 2194]

Isso é código-golfe, então o código mais curto vence.


Podemos considerar a entrada como uma string?
— lirtosiast

@lirtosiast, sim, mas não a lista de dígitos.
— Vedant Kandoi

14
Eles poderiam ser chamados de números autocannibalistic .
— Arnauld

6
Qual é o motivo pelo qual não podemos considerar uma lista de dígitos? Esse problema já os trata como se fossem listas de dígitos. Forçá-los a serem números significa que você apenas precisa fixar um código extra para convertê-los em uma lista.
— Assistente de trigo

11
Dois valores distintos consistentes podem ser retornados em vez de verdade / falsidade?
— Olivier Grégoire

Respostas:


7

JavaScript (ES6),  52 51  50 bytes

Guardado 1 byte graças a @tsh

Recebe a entrada como uma sequência. Retorna um valor booleano.

f=n=>n>[n%10]?f(-(-n[0]-n)%10+n.slice(1,-1)):!n[1]

Experimente online!

Comentado

f = n =>                 // f = recursive function taking n (a string)
  n > [n % 10]           // The last digit is isolated with n % 10 and turned into a
                         // singleton array, which is eventually coerced to a string
                         // when the comparison occurs.
                         // So we do a lexicographical comparison between n and its
                         // last digit (e.g. '231'>'1' and '202'>'2', but '213'<'3').
  ?                      // If the above result is true:
    f(                   //   do a recursive call:
      -(-n[0] - n) % 10  //     We compute (int(first_digit) + int(n)) mod 10. There's no
                         //     need to isolate the last digit since we do a mod 10 anyway.
      + n.slice(1, -1)   //     We add the middle part, as a string. It may be empty.
    )                    //   end of recursive call
  :                      // else:
    !n[1]                //   return true if n has only 1 digit, or false otherwise


6

Gelatina , 11 bytes

Ṛṙ-µṖÄ%⁵:ḊẠ

Experimente online!

Como funciona

Ṛṙ-µṖÄ%⁵:ḊẠ  Main link. Argument: n

Ṛ            Reverse n, after casting it to a digit list.
 ṙ-          Rotate the result -1 units to the left, i.e., 1 unit to the right.
             Let's call the resulting digit list D.
   µ         Begin a new chain with argument D.
    Ṗ        Pop; remove the last digit.
     Ä       Accumulate; take the cumulative sum of the remaining digits.
      %⁵     Take the sums modulo 10.
         Ḋ   Dequeue; yield D without its first digit.
        :    Perform integer division between the results to both sides.
             Integer division is truthy iff greater-or-equal is truthy.
          Ạ  All; return 1 if all quotients are truthy, 0 if not.

6

Perl 6 , 63 62 bytes

{!grep {.[*-1]>.[0]},(.comb,{.[0,*-1].sum%10,|.[1..*-2]}...1)}

Experimente online!

Explicação:

{                                                            } # Anonymous code block
                     (                                  ... )       # Create a sequence
                      .comb,  # Starting with the input converted to a list of digits
                            {                          }   # With each element being
                             .[0,*-1]   # The first and last element of the previous list
                                     .sum%10  # Summed and modulo 10
                                            ,|.[1..*-2]   # Followed by the intermediate elements
                                                        ...1 # Until the list is length 1
 !grep   # Do none of the elements of the sequence
       {.[*-1]>.[0]},   # Have the last element larger than the first?

5

Java (JDK) , 83 bytes

n->{int r=0,h=n;while(h>9)h/=10;for(;n>9;h=(h+n)%10,n/=10)r=h<n%10?1:r;return r<1;}

Experimente online!

Créditos


Dada a extensão das respostas do Python, sinto que perdi alguma coisa ... embora os casos de teste estejam corretos.
— Olivier Grégoire

Acho que você não perdeu nada. As respostas do Python tomam a entrada como string e usam indexação, e você toma a entrada como número inteiro e usa /10e %10em um loop. Tão bem feito ao vencer as respostas do Python; +1 de mim. :)
— Kevin Cruijssen

11
Você pode jogar um byte de golfe alterando r+=para r=e ?1:0para ?1:r.
— Kevin Cruijssen

@KevinCruijssen De fato ... as respostas do Python são abaixo do ideal: os comentários nos golfe são mais curtos que essa resposta. Além disso, obrigado pelo byte salvo! ;-)
— Olivier Grégoire

Você pode retornar ou 1 iniciando e executando (economizando 1 byte). 01r=1r&=h<n%10?0:r;return r;
— Arnauld

4

Mathematica, 62 bytes

0(IntegerDigits@#//.{a_,r___,b_}/;a>=b:>{Mod[a+b,10],r})=={0}&

Primeiro chame IntegerDigitsa entrada para obter uma lista de seus dígitos e, em seguida, aplique repetidamente a seguinte regra:

{a_,r___,b_}       (* match the first digit, 0 or more medial digits, and the last digit... *)
/;a>=b             (* under the condition that the number is edible... *)
:>{Mod[a+b,10],r}  (* and replace it with the next iteration *)

A regra é aplicada até que o padrão não corresponda mais; nesse caso, resta apenas um dígito (verdade) ou a cabeça é menor que a cauda (falsidade).

Em vez de chamar Length[__]==1, podemos salvar alguns bytes 0(__)=={0}, multiplicando todos os elementos da lista 0 e comparando-os com a lista {0}.


11
Caso você não saiba, o TIO possui o Mathematica agora. Experimente online!
— 217 Dennis

4

Python 3 , 50 bytes

Primeira linha roubada da resposta de Black Owl Kai .

p,*s=map(int,input())
while s:*s,k=s;p%10<k>q;p+=k

Experimente online!

A saída é via código de saída. Falha (1) para entradas falsas e acabamentos (0) para entradas verdadeiras.


Você pode explicar por p%10<k>qque não lança um NameError se p%10 >= k?
— Black Owl Kai

11
As comparações encadeadas do @BlackOwlKai são avaliadas preguiçosamente no Python. Isso significa que, assim que uma primeira comparação falsa aparecer, a cadeia não será mais avaliada. Nesse caso, p%10<k>qfaz o mesmo que p%10<k and k>q.
— ovs 11/12/19

4

Python 2 , 105 82 81 bytes

i,x=map(int,input()),1
for y in i[:0:-1]:
 if i[0]%10<y:x=0
 else:i[0]+=y
print x

Experimente online!

Muito obrigado por um enorme -23 de @ ØrjanJohansen

Obrigado a @VedantKandoi (e @ ØrjanJohansen) por mais -1


11
Você pode usar forcom uma fatia inversa e também fazer o %10único ao testar: Experimente online!
— Ørjan Johansen

11
Troque a condição if-else if i[0]<i[-1]:x=0e , em seguida else:..... @ ØrjanJohansen, na sua resposta também.
— Vedant Kandoi

@ ØrjanJohansen - Obrigado. Isso é bem legal.
— ElPedro

Ei, @VedantKandoi. Parece bom, mas não sei exatamente o que você quer dizer. Você me derrotou nessa. Você pode adicionar um TIO, por favor? Quando eu tento, funciona para todos os Truecasos, mas não para todos os False.
— ElPedro

11
Eu acho que @VedantKandoi significa isso .
— Ørjan Johansen

4

Braquilog , 23 bytes

ẹ{bkK&⟨h{≥₁+tg}t⟩,K↰|Ȯ}

Experimente online!

Esta é uma economia de 1 byte na solução da Fatalize . Isso usa uma abordagem recursiva em vez de uma iterativa

Explicação

ẹ                          Input into a list of digits
 {                    }    Assert that either
  bk                       | the list has at least 2 elements (see later)
      ⟨h{     }t⟩           | and that [head, tail]
         ≥₁                |  | is increasing (head >= tail)
           +               |  | and their sum
            t              |  | mod 10 (take last digit)
             g             |  | as single element of a list
                ,          | concatenated with
  bkK            K         | the number without head and tail (this constrains the number to have at least 2 digits)
                  ↰        | and that this constraint also works on the newly formed number
                   |Ȯ      | OR is a 1 digit number

3

APL (Dyalog Unicode) , SBCS de 33 bytes

Função de prefixo tácito anônimo usando uma string como argumento.

{⊃⍵<t←⊃⌽⍵:0⋄3::1⋄∇10|t+@1⊢¯1↓⍵}⍎¨

Experimente online!

⍎¨ avalie cada caractere (isso nos fornece uma lista de dígitos)

{... } aplique o seguinte "dfn" a isso; ⍵é o argumento (lista de dígitos):

  ⌽⍵ inverter o argumento

  ⊃ escolha o primeiro elemento (esta é a cauda)

  t← atribuir a t(para t ail)

  ⍵< para cada um dos dígitos originais, veja se é menor que isso

  ⊃ escolha o primeiro verdadeiro / falso

 : se então:

  0 retorna falso

 ⋄ então:

 3:: se a partir de agora, ocorrer um erro de índice (fora dos limites):

  1 retornar verdadeiro

  ¯1↓⍵ solte o último dígito

  ⊢ produz que (separa 1e ¯1assim eles não formarão uma única matriz)

  t+@1 adicione a cauda ao primeiro dígito (a cabeça)

  10| mod-10

  ∇ recurso

Quando atingirmos um único dígito, a lista ¯1↓será vazia e @1causará um erro de índice, pois não há um primeiro dígito, fazendo com que a função retorne verdadeira.



3

Braquilog , 24 bytes

ẹ;I⟨⟨h{≥₁+tg}t⟩c{bk}⟩ⁱ⁾Ȯ

Experimente online!

Devo alterar ⁱo comportamento padrão da iteração para iterar um número desconhecido de vezes (atualmente, iterará 1 vez por padrão, o que é completamente inútil). Eu então não precisaria do […];I[…]⁾, economizando 3 bytes

Explicação

Este programa contém um garfo feio dentro de um garfo. Há também algum encanamento necessário para trabalhar em listas de dígitos em vez de números (porque se removermos a cabeça e a cauda de 76nós, ficaremos com isso 0, o que não funcionará ao contrário de [7,6]onde terminamos []).

ẹ                          Input into a list of digits
                       Ȯ   While we don't have a single digit number…
 ;I                  ⁱ⁾    …Iterate I times (I being unknown)…
   ⟨                ⟩      …The following fork:
               c           | Concatenate…
    ⟨         ⟩            | The output of the following fork:
     h       t             | | Take the head H and tail T of the number
      {     }              | | Then apply on [H,T]:
       ≥₁                  | | | H ≥ T
         +                 | | | Sum them
          tg               | | | Take the last digit (i.e. mod 10) and wrap it in a list
                {  }       | With the output of the following predicate:
                 bk        | | Remove the head and the tail of the number

Usando recursão em vez de iteração e substituindo o garfo c para usar, ,eu poderia remover 1 byte Experimente online!
— Kroppeb

@Kroppeb Muito legal. Eu acho que você deve postar sua própria resposta, porque é significativamente diferente da minha!
— Fatalize

3

Haskell, 70 64 60 bytes

f(a:b)=b==""||a>=last b&&f(last(show$read[a]+read b):init b)

A entrada é tomada como uma sequência.

Experimente online!

Edite: -6 bytes usando o truque de @ Laikoni em|| vez de usar guardas separados. Mais -4 bytes graças a @Laikoni.


3
read[l b]pode ser apenas read bporque você olha apenas para o último dígito de qualquer maneira. Economiza mais 4 bytes também alinhando last: Experimente on-line!
— Laikoni


2

Python 2 , 75 67 bytes

l=lambda n:n==n[0]or n[-1]<=n[0]*l(`int(n[0]+n[-1],11)%10`+n[1:-1])

Experimente online!

Abordagem recursiva lambda. Recebe a entrada como uma sequência. Muito obrigado a Dennis por economizar 8 bytes!


2

Haskell , 69 64 bytes

f n=read[show n!!0]#n
h#n=n<10||h>=mod n 10&&mod(h+n)10#div n 10

Experimente online! Exemplo de uso: f 2632rendimentos True.

Editar: -5 bytes porquemod (h + mod n 10) 10 = mod (h + n) 10


bom uso de ||, o que também me ajudou a diminuir minha resposta. Obrigado!
— nimi

2

Ruby, 139 bytes

->(a){a.length==1?(p true;exit):1;(a[0].to_i>=a[-1].to_i)?(a[0]=(a[-1].to_i+a[0].to_i).divmod(10)[1].to_s;a=a[0..-2];p b[a]):p(false);exit}

Experimente online! (possui algum código extra para processar a entrada, pois é uma função)

Código não destruído:

->(a) do
    if a.length == 1
        p true
        exit
    if a[0].to_i >= a[-1].to_i
        a[0] = (a[-1].to_i + a[0].to_i).divmod(10)[1].to_s
        a = a[0..-2]
        p b[a]
    else
        p false
        exit
    end
end

1

Retina 0.8.2 , 42 bytes

\d
$*#;
^((#*).*;)\2;$
$2$1
}`#{10}

^#*;$

Experimente online!O link inclui casos de teste. Explicação:

\d
$*#;

Converta os dígitos em unários e insira separadores.

^((#*).*;)\2;$
$2$1

Se o último dígito não for maior que o primeiro, adicione-os.

#{10}

Reduza o módulo 10, se apropriado.

}`

Repita até o último dígito ser maior que o primeiro ou restar apenas um dígito.

^#*;$

Teste se resta apenas um dígito.


1

05AB1E , 26 25 24 bytes

[DgD#\ÁD2£D`›i0qëSOθs¦¦«

Provavelmente pode ser jogado um pouco mais .. Parece muito longo, mas talvez o desafio seja em termos de código mais complexo do que eu pensava anteriormente.

Experimente online ou verifique todos os casos de teste .

Explicação:

[                 # Start an infinite loop
 D                #  Duplicate the top of the stack
                  #  (which is the input implicitly in the first iteration)
  gD              #  Take its length and duplicate it
    #             #  If its a single digit:
                  #   Stop the infinite loop
                  #   (and output the duplicated length of 1 (truthy) implicitly)
                  #  Else:
  \               #   Discard the duplicate length
   Á              #   Rotate the digits once towards the left
    D2£           #   Duplicate, and take the first two digits of the rotated number
       D`         #   Duplicate, and push the digits loose to the stack
         ›i       #   If the first digit is larger than the second digit:
           0      #    Push a 0 (falsey)
            q     #    Stop the program (and output 0 implicitly)
          ë       #   Else (first digit is smaller than or equal to the second digit):
           SO     #    Sum the two digits
             θ    #    Leave only the last digit of that sum
           s      #    Swap to take the rotated number
            ¦¦    #    Remove the first two digits
              «   #    Merge it together with the calculated new digit

1

C ++ (gcc) , 144 bytes

bool f(std::string b){int c=b.length();while(c>1){if(b[0]<b[c-1])return 0;else{b[0]=(b[0]-48+b[c-1]-48)%10+48;b=b.substr(0,c-1);--c;}}return 1;}

Experimente online!

Na primeira vez que estou tentando algo assim, se formatar algo errado, avise-me. Não tenho 100% de certeza sobre as regras para coisas como o uso de namespace para eliminar os 5 bytes "std ::", então deixei dentro.

Ungolfed:

bool hunger(std::string input)
{
    int count=input.length();
    while (count>1)
    {
        if (input[0]<input[count-1])                         //if at any point the head cannot eat the tail we can quit the loop
                                                             //comparisons can be done without switching from ascii
        {
            return false;
        }
        else
        {
             input[0]=(input[0]-48+input[count-1]-48)%10+48; //eating operation has to occur on integers so subtract 48 to convert from ASCII to a number
             input=input.substr(0,count-1);                  //get rid of the last number since it was eaten
             --count;
        }

    }
    return true;                                             //if the end of the loop is reached the number has eaten itself
}

11
Em teoria, você também precisa de #includedeclarações. No entanto, eu proporia a programação no subdialeto std lib facilities do C ++ com o #include "std_lib_facilities.h"prefixado, o que também faz a using namespace std;. Esse cabeçalho foi escrito pelo autor do idioma de volta (a última versão é 2010) para os novos alunos do C ++.
— Yakk

@Yakk A menos que você crie e publique um intérprete que faça isso por você, você ainda precisará contar a inclusão de std_lib_facilities.h.
— Dennis

Bem-vindo ao PPCG! Você precisa da contagem de todas as inclusões necessárias para compilar sua função. O método mais curto que conheço é #import<string>. Experimente online!
— Dennis

@ Dennis #!/usr/bin/shnewline gcc -include "std_lib_facilities.h" $@- se eu encontrar um curso C ++ que forneça esse shell script, isso contaria?
— Yakk

@Yakk Não sabia sobre essa opção. Diferentemente das instruções #include, os argumentos da linha de comando são livres porque são essencialmente um novo idioma . No C ++ (gcc)-include iostream , trata-se de 144 bytes.
— Dennis

1

C #, 114 bytes

static bool L(string n){return n.Skip(1).Reverse().Select(x=>x%16).Aggregate(n[0]%16,(h,x)=>h>=x?(h+x)%10:-1)>=0;}

Experimente online


1

C (gcc) (com string.h) , 110 108 bytes

c;f(char*b){c=strlen(b);if(!c)return 1;char*d=b+c-1;if(*b<*d)return 0;*b=(*b+*d-96)%10+48;*d=0;return f(b);}

Experimente online!

Ainda relativamente novo no PPCG, a sintaxe correta para vincular bibliotecas como um novo idioma é estranha para mim. Observe também que a função retorna 0 ou 1 para false / true e a impressão resultante para stdout exige stdio. Se estivermos sendo pedantes e o exercício exigir saída, o idioma requer stdio que tão bem.

Conceitualmente semelhante à resposta do @ BenH, mas em C, então parabéns pelo seu vencimento (Bem-vindo ao PPCG, btw), mas usando recursão. Ele também usa aritmética de ponteiro de matriz, porque o código sujo é mais curto que o código limpo.

A função é recursiva de cauda, ​​com condições de saída se o primeiro número não puder comer o último ou se o comprimento for 1, retornando falso ou verdadeiro, respectivamente. Esses valores são encontrados desreferenciando um ponteiro para a C-String (que fornece um caractere) no início e no final da string e fazendo as comparações sobre eles. A aritmética do ponteiro é feita para encontrar o final da string. finalmente, o último caractere é "apagado" substituindo-o por um terminador nulo (0).

É possível que a aritmética do módulo seja encurtada em um byte ou dois, mas eu já preciso de um banho após a manipulação do ponteiro.

Versão Ungolfed Aqui

Atualização: salvou dois bytes substituindo c == 1 por! C. Isso é essencialmente c == 0. Ele executará um tempo adicional e desnecessariamente se duplicará antes de se excluir, mas salva dois bytes. Um efeito colateral é que as cadeias de comprimento nulo ou zero não causam recursão infinita (embora não devamos obter cadeias nulas, pois o exercício indica números inteiros positivos).


Você não precisa vincular bibliotecas no caso de gcc- embora os avisos sejam gerados, gcco código será compilado sem #includes. Além disso, você pode salvar 4 bytes com -DR=return. Finalmente, no seu código de teste, os \0são desnecessários, pois a string já os inclui implicitamente.

11
Além disso, você pode retornar de uma função atribuindo à primeira variável: b=case1?res1:case2?res2:res_else;é o mesmo queif(case1)return res1;if(case2)return res2;return res_else;

Ainda mais, você pode liberar alguns bytes extras ao não usar c: você pode determinar se a string tem comprimento zero head-tail.


Não sabia que você poderia usar operadores ternários (condicionais) em C. Esse sempre foi o caso? Independentemente, é bom saber; Eu vou usá-los no futuro. Cheers
— Andrew Baumher

1

Powershell, 89 bytes

"$args"-notmatch'(.)(.*)(.)'-or(($m=$Matches).1-ge$m.3-and(.\g(''+(+$m.1+$m.3)%10+$m.2)))

Importante! O script se chama recursivamente. Então salve o script comog.ps1 arquivo no diretório atual. Além disso, você pode chamar uma variável de bloco de script em vez de arquivo de script (consulte o script de teste abaixo). Isso chama tem o mesmo comprimento.

Nota 1: O script usa uma avaliação lenta dos operadores lógicos -ore -and. Se "$args"-notmatch'(.)(.*)(.)'for True, a subexpressão correta de -ornão será avaliada. Além disso, se ($m=$Matches).1-ge$m.3for False, a subexpressão correta de -andtambém não será avaliada. Portanto, evitamos recursões infinitas.

Nota 2: A expressão regular '(.)(.*)(.)'não contém âncoras de início e fim porque a expressão(.*) é gananciosa por padrão.

Script de teste

$g={
"$args"-notmatch'(.)(.*)(.)'-or(($m=$Matches).1-ge$m.3-and(&$g(''+(+$m.1+$m.3)%10+$m.2)))
}

@(
    ,(2632, $true)
    ,(92258, $true)
    ,(60282, $true)
    ,(38410, $true)
    ,(3210, $true)
    ,(2302, $true)
    ,(2742, $true)
    ,(8628, $true)
    ,(6793, $true)
    ,(1, $true)
    ,(2, $true)
    ,(10, $true)
    ,(100, $true)
    ,(55, $true)
    ,(121, $true)
    ,(6724, $false)
    ,(47, $false)
    ,(472, $false)
    ,(60247, $false)
    ,(33265, $false)
    ,(79350, $false)
    ,(83147, $false)
    ,(93101, $false)
    ,(57088, $false)
    ,(69513, $false)
    ,(62738, $false)
    ,(54754, $false)
    ,(23931, $false)
    ,(7164, $false)
    ,(5289, $false)
    ,(3435, $false)
    ,(3949, $false)
    ,(8630, $false)
    ,(5018, $false)
    ,(6715, $false)
    ,(340, $false)
    ,(2194, $false)
) | %{
    $n,$expected = $_
   #$result = .\g $n   # uncomment this line to call a script file g.ps1
    $result = &$g $n   # uncomment this line to call a script block variable $g
                       # the script block call and the script file call has same length
    "$($result-eq-$expected): $result <- $n"
}

Saída:

True: True <- 2632
True: True <- 92258
True: True <- 60282
True: True <- 38410
True: True <- 3210
True: True <- 2302
True: True <- 2742
True: True <- 8628
True: True <- 6793
True: True <- 1
True: True <- 2
True: True <- 10
True: True <- 100
True: True <- 55
True: True <- 121
True: False <- 6724
True: False <- 47
True: False <- 472
True: False <- 60247
True: False <- 33265
True: False <- 79350
True: False <- 83147
True: False <- 93101
True: False <- 57088
True: False <- 69513
True: False <- 62738
True: False <- 54754
True: False <- 23931
True: False <- 7164
True: False <- 5289
True: False <- 3435
True: False <- 3949
True: False <- 8630
True: False <- 5018
True: False <- 6715
True: False <- 340
True: False <- 2194

PowerShell, 90 bytes

Sem recursão. Nenhuma dependência de nome de arquivo e nenhuma dependência de nome de bloco de script.

for($s="$args";$s[1]-and$s-ge$s%10){$s=''+(2+$s[0]+$s)%10+($s|% S*g 1($s.Length-2))}!$s[1]

Um PowerShell converte implicitamente um operando direito em um tipo de operando esquerdo. Portanto, $s-ge$s%10calcula o operando direito $s%10como integere o compara como um stringtipo porque o operando esquerdo é string. E 2+$s[0]+$sconverte um caractere $s[0]e uma string $spara integerporque o operando esquerdo 2é inteiro.

$s|% S*g 1($s.Length-2)é um atalho para$s.Substring(1,($s.Length-2))


1

C # (compilador interativo do Visual C #) , 69 bytes

x=>{for(int h=x[0],i=x.Length;i>1;)h=h<x[--i]?h/0:48+(h+x[i]-96)%10;}

Experimente online!

Sucesso ou fracasso é determinado pela presença ou ausência de uma exceção . A entrada está no formato de uma sequência.

Menos golfe ...

// x is the input as a string
x=>{
  // h is the head
  for(int h=x[0],
    // i is an index to the tail
    i=x.Length;
    // continue until the tail is at 0
    i>1;)
      // is head smaller larger than tail?
      h=h<x[--i]
        // throw an exception
        ?h/0
        // calculate the next head
        :48+(h+x[i]-96)%10;
}

Existem alguns bytes extras para lidar com a conversão entre caracteres e dígitos, mas no geral isso não afetou muito o tamanho.



1

Braquilog , 18 bytes

ẹ⟨k{z₁{≥₁+t}ᵐ}t⟩ⁱȮ

Experimente online!

Leva três bytes off solução de Fatalize apenas em virtude de superscriptless não-determinístico ⁱexistente agora, mas perde outros três, fazendo coisas vagamente inspirados Jelly com z₁evitar o uso c, gou até mesmo h. (Também inspirado por tentar, e falhar, usar um novo recurso diferente: o ʰmetapredicado.)

                 Ȯ    A list of length 1
                ⁱ     can be obtained from repeatedly applying the following
ẹ                     to the list of the input's digits:
 ⟨k{         }t⟩      take the list without its last element paired with its last element,
    z₁                non-cycling zip that pair (pairing the first element of the list with
                      the last element and the remaining elements with nothing),
      {    }ᵐ         and for each resulting zipped pair or singleton list:
       ≥₁             it is non-increasing (trivially true of a singleton list);
          t           take the last digit of
         +            its sum.

0

PowerShell , 94 91 bytes

for(;$n-and$n[0]-ge$n[-1]){$n=$n-replace"^.",((+$n[0]+$n[-1]-96)%10)-replace".$"}return !$n

Experimente online!


Script de teste

function f($n){

for(;$n-and$n[0]-ge$n[-1]){$n=$n-replace"^.",((+$n[0]+$n[-1]-96)%10)-replace".$"}return !$n

Remove-Variable n
}
Write-Host True values:
@(2632, 92258, 60282, 38410,3210, 2302, 2742, 8628, 6793, 1, 2, 10, 100, 55, 121) |
    % { Write-Host "  $_ $(' '*(6-$_.ToString().Length)) $(f $_.ToString())" }

Write-Host False values:
@(6724, 47, 472, 60247, 33265, 79350, 83147, 93101, 57088, 69513, 62738, 54754, 23931, 7164, 5289, 3435, 3949, 8630, 5018, 6715, 340, 2194) | 
    % { Write-Host "  $_ $(' '*(6-$_.ToString().Length)) $(f $_.ToString())" }

Código não destruído:

function f ($inVar){
    # While the Input exists, and the first character is greater than last
    while($inVar -and ($inVar[0] -ge $inVar[-1])){

        # Calculate the first integer -> ((+$n[0]+$n[-1]-96)%10)
        $summationChars = [int]$inVar[0]+ [int]$inVar[-1]
        # $summationChars adds the ascii values, not the integer literals. 
        $summationResult = $summationChars - 48*2
        $summationModulo = $summationResult % 10

        # Replace first character with the modulo
        $inVar = $inVar -replace "^.", $summationModulo

        # Remove last character
        $inVar = $inVar -replace ".$"
    }
    # Either it doesn't exist (Returns $True), or 
    # it exists since $inVar[0] < $inVar[-1] returning $False
    return !$inVar
}

11
Você não precisa verificar $n[0]sua fordeclaração - basta verificar $n.
— AdmBorkBork

Você poderia usar -6em vez -96porque é o suficiente para calc% 10
— Mazzy

você pode remover return e salvar 7 bytes
— mazzy

e acho que você deve incluir uma declaração de parâmetro na contagem de bytes. ou param($n)ou function f($n).
— Mazzy

11
@mazzy O pôster declarou nos comentários que você tinha permissão para usar strings, mas você não tinha permissão para fornecer a entrada como uma lista de números / strings. Eu interpretei isso como ["1","2","3"]entrada inválida, mas "123"é válida . se o @VedantKandoi tiver um problema, eu definitivamente posso mudá-lo!
— KGlasier
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.