31
\$\begingroup\$

Given a positive integer, output a truthy/falsy value as to whether the number can eat itself.

Rules

Leftmost is the head, rightmost is the tail

If the head is greater than or equal to the tail, the head eats the tail and the new head becomes their sum.

If \$sum \ge 10 \$ then the head is replaced by \$sum \mod 10\$.

\$sum=0\$ cannot be ignored, however the input number will never have any leading zeroes.

Example:

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.

If at any point the head cannot eat the tail, the answer will be False.

number=6724
072
False (0<2)

Test Cases:

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]

This is code-golf so shortest code wins.

\$\endgroup\$
6
  • \$\begingroup\$ Can we take input as a string? \$\endgroup\$
    – lirtosiast
    Dec 7, 2018 at 8:20
  • \$\begingroup\$ @lirtosiast, yes, but not list of digits. \$\endgroup\$ Dec 7, 2018 at 8:23
  • 15
    \$\begingroup\$ They could be called Autocannibalistic Numbers. \$\endgroup\$
    – Arnauld
    Dec 7, 2018 at 10:20
  • 7
    \$\begingroup\$ What is the reason we can't take as a list of digits? This problem already treats them as if they are lists of digits. Forcing them to be numbers means that you just have to pin extra code to convert them to a list. \$\endgroup\$
    – Wheat Wizard
    Dec 7, 2018 at 14:09
  • 1
    \$\begingroup\$ Can two consistent distinct values be returned instead of truthy/falsy? \$\endgroup\$ Dec 7, 2018 at 17:22

26 Answers 26

7
\$\begingroup\$

JavaScript (ES6),  52 51  50 bytes

Saved 1 byte thanks to @tsh

Takes input as a string. Returns a Boolean value.

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

Try it online!

Commented

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

Jelly, 11 bytes

Ṛṙ-µṖÄ%⁵:ḊẠ

Try it online!

How it works

Ṛṙ-µṖÄ%⁵:ḊẠ  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.
\$\endgroup\$
6
\$\begingroup\$

Perl 6, 63 62 bytes

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

Try it online!

Explanation:

{                                                            } # 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?
\$\endgroup\$
5
\$\begingroup\$

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;}

Try it online!

Credits

\$\endgroup\$
7
  • \$\begingroup\$ Given the length of the Python answers, I feel like I missed something... though the test cases are ok. \$\endgroup\$ Dec 7, 2018 at 12:22
  • \$\begingroup\$ I don't think you've missed anything. The Python answers both take the input as string and use indexing, and you take the input as integer and use /10 and %10 in a loop. So well done beating the Python answers; +1 from me. :) \$\endgroup\$ Dec 7, 2018 at 12:34
  • 1
    \$\begingroup\$ You can golf a byte changing r+= to r= and ?1:0 to ?1:r. \$\endgroup\$ Dec 7, 2018 at 12:37
  • \$\begingroup\$ @KevinCruijssen Indeed... the Python answers are suboptimal: golfs in comments are shorter than this answer. Also, thanks for the byte saved! ;-) \$\endgroup\$ Dec 7, 2018 at 12:42
  • \$\begingroup\$ You could return \$0\$ or \$1\$ by starting with r=1 and doing r&=h<n%10?0:r;return r; (saving 1 byte). \$\endgroup\$
    – Arnauld
    Dec 7, 2018 at 16:01
4
\$\begingroup\$

Mathematica, 62 bytes

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

First calls IntegerDigits on the input to get a list of its digits, then repeatedly applies the following rule:

{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 *)

The rule is applied until the pattern no longer matches, in which case either there is only one digit left (truthy) or the head is less than the tail (falsy).

Instead of calling Length[__]==1, we can save a few bytes with 0(__)=={0}, multiplying all elements in the list by 0 and then comparing with the list {0}.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ In case you didn't know, TIO has Mathematica now. Try it online! \$\endgroup\$
    – Dennis
    Dec 7, 2018 at 15:36
4
\$\begingroup\$

Python 3, 50 bytes

First line stolen from Black Owl Kai's answer.

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

Try it online!

Output is via exit code. Fails (1) for falsy inputs and finishes (0) for truthy inputs.

\$\endgroup\$
2
  • \$\begingroup\$ Can you explain why p%10<k>q doesn't throw a NameError if p%10 >= k? \$\endgroup\$
    – Kateba
    Dec 11, 2018 at 19:36
  • 1
    \$\begingroup\$ @BlackOwlKai chained comparisons are lazily evaluated in Python. This means as soon as a first false comparison appears, the chain will no longer be evaluated. In this case p%10<k>q does the same as p%10<k and k>q. \$\endgroup\$
    – ovs
    Dec 11, 2018 at 19:45
4
\$\begingroup\$

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

Try it online!

Many thanks for a massive -23 from @ØrjanJohansen

Thanks to @VedantKandoi (and @ØrjanJohansen) for another -1

\$\endgroup\$
5
  • 1
    \$\begingroup\$ You can use for with a reverse slice, and also do the %10 only when testing: Try it online! \$\endgroup\$ Dec 7, 2018 at 10:59
  • 1
    \$\begingroup\$ Swap the if-else condition, if i[0]<i[-1]:x=0 and then else:..... @ØrjanJohansen, in your answer too. \$\endgroup\$ Dec 7, 2018 at 12:13
  • \$\begingroup\$ @ØrjanJohansen - Thanks. That's well cool. \$\endgroup\$
    – ElPedro
    Dec 7, 2018 at 21:00
  • \$\begingroup\$ Hey @VedantKandoi. Sounds good but not sure exactly what you mean. You have me beaten on that one. Can you add a TIO please? When I try it works for all True cases but not for all of the False. \$\endgroup\$
    – ElPedro
    Dec 7, 2018 at 21:15
  • 1
    \$\begingroup\$ I think @VedantKandoi means this. \$\endgroup\$ Dec 7, 2018 at 21:29
4
\$\begingroup\$

Brachylog, 23 bytes

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

Try it online!

This is a 1 byte save over Fatalize's solution. This uses a recursive approach instead of a iterative

Explanation

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

APL (Dyalog Unicode), 33 bytesSBCS

Anonymous tacit prefix function taking a string as argument.

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

Try it online!

⍎¨ evaluate each character (this gives us a list of digits)

{} apply the following "dfn" to that; is the argument (list of digits):

  ⌽⍵ reverse the argument

   pick the first element (this is the tail)

  t← assign to t (for tail)

  ⍵< for each of the original digits, see if it is less than that

   pick the first true/false

: if so:

  0 return false

 then:

3:: if from now on, an index error (out of bounds) happens:

  1 return true

  ¯1↓⍵ drop the last digit

   yield that (separates 1 and ¯1 so they won't form a single array)

  t+@1 add the tail to the first digit (the head)

  10| mod-10

   recurse

Once we hit a single digit, ¯1↓ will make that an empty list, and @1 will cause an index error as there is no first digit, causing the function to return true.

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

Python 3, 77 bytes

p,*s=map(int,input())
print(all(n<=sum(s[i+1:],p)%10for i,n in enumerate(s)))

Try it online!


And my old solution with a recursive approach

Python 3, 90 bytes

f=lambda x,a=0:2>len(x)if 2>len(x)or(int(x[0])+a)%10<int(x[-1])else f(x[:-1],a+int(x[-1]))

Try it online!

Takes input as a string.

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

Brachylog, 24 bytes

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

Try it online!

I should change 's default behaviour so that it iterates an unknown number of times (currently, it iterates 1 time by default which is completely useless). I then wouldn't need the […];I[…]⁾, saving 3 bytes

Explanation

This program contains an ugly fork inside a fork. There is also some plumbing needed to work on lists of digits instead of numbers (because if we remove the head and tail of 76 we are left with 0, which doesn't work contrary to [7,6] where we end up with []).

ẹ                          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
\$\endgroup\$
2
  • \$\begingroup\$ Using recursion instead of iteration and replacing the c-fork to use , instead i could remove 1 byte Try it online! \$\endgroup\$
    – Kroppeb
    Dec 10, 2018 at 14:00
  • \$\begingroup\$ @Kroppeb Really cool. I think you should post your own answer, because it's significantly different than mine! \$\endgroup\$
    – Fatalize
    Dec 10, 2018 at 14:01
3
\$\begingroup\$

Haskell, 70 64 60 bytes

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

Input is taken as a string.

Try it online!

Edit: -6 bytes by using @Laikoni's trick of using || instead of separate guards. Another -4 bytes thanks to @Laikoni.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ read[l b] can be just read b because you only look at the last digit anyway. Saves 4 more bytes by also in-lining last: Try it online! \$\endgroup\$
    – Laikoni
    Dec 8, 2018 at 17:19
2
\$\begingroup\$

Perl 5, 64 bytes

{local$_=pop;1while s/(.)(.*)(.)/$1<$3?'':(($1+$3)%10).$2/e;/./}

Try it online!

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

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

Try it online!

Recursive lambda approach. Takes input as a string. Many thanks to Dennis for saving 8 bytes!

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

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

Try it online! Example usage: f 2632 yields True.

Edit: -5 bytes because mod (h + mod n 10) 10 = mod (h + n) 10

\$\endgroup\$
1
  • \$\begingroup\$ nice use of ||, which helped me to shorten my answer, too. Thanks! \$\endgroup\$
    – nimi
    Dec 8, 2018 at 12:03
2
\$\begingroup\$

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}

Try it online! (has some extra code to process input, since it's a function)

Ungolfed code:

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

Retina 0.8.2, 42 bytes

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

^#*;$

Try it online! Link include test cases. Explanation:

\d
$*#;

Convert the digits to unary and insert separators.

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

If the last digit is not greater than the first then add them together.

#{10}

Reduce modulo 10 if appropriate.

}`

Repeat until the last digit is greater than the first or there is only one digit left.

^#*;$

Test whether there is only one digit left.

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

05AB1E, 26 25 24 bytes

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

Can probably be golfed a bit more.. It feels overly long, but maybe the challenge is in terms of code more complex than I thought beforehand.

Try it online or verify all test cases.

Explanation:

[                 # 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
\$\endgroup\$
1
\$\begingroup\$

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;}

Try it online!

First time I'm trying something like this so if I formatted something wrong please let me know. I'm not 100% sure on the rules for stuff like using namespace to eliminate the 5 bytes "std::" so I left it in.

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
}
\$\endgroup\$
5
  • 1
    \$\begingroup\$ In theory you also need #include statements. However, I'd propose programming in the std lib facilities subdialect of C++ with #include "std_lib_facilities.h" prepended, which also does a using namespace std;. That header was written by the author of the language way back (lastest version is 2010) for students new to C++. \$\endgroup\$
    – Yakk
    Dec 7, 2018 at 20:00
  • \$\begingroup\$ @Yakk Unless you make and publish an interpreter that does this for you, you still need to counts the include of std_lib_facilities.h. \$\endgroup\$
    – Dennis
    Dec 8, 2018 at 2:03
  • \$\begingroup\$ @BenH Welcome to PPCG! You need the count all includes that are required to compile your function. The shortest method I know is #import<string>. Try it online! \$\endgroup\$
    – Dennis
    Dec 8, 2018 at 2:08
  • \$\begingroup\$ @Dennis #!/usr/bin/sh newline gcc -include "std_lib_facilities.h" $@ -- if I find a C++ course that provides that shell script, would that count? \$\endgroup\$
    – Yakk
    Dec 8, 2018 at 2:19
  • \$\begingroup\$ @Yakk Didn't know about that switch. Unlike #include statements, command-line arguments are free because they're essentially a new language. In C++(gcc) -include iostream, this is indeed 144 bytes. \$\endgroup\$
    – Dennis
    Dec 8, 2018 at 2:26
1
\$\begingroup\$

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;}

Try it online

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

C (gcc) (with 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);}

Try it online!

Still relatively new to PPCG, so the correct syntax for linking libraries as a new language is foreign to me. Also note that the function returns 0 or 1 for false/true, and printing that result to stdout does require stdio. If we're being pedantic and the exercise requires output, the language requires stdio that as well.

Conceptually similar to @BenH's answer, but in C, so kudos where they are due (Welcome to PPCG, btw), but using recursion. It also uses array pointer arithmetic, because dirty code is shorter than clean code.

The function is tail recursive, with exit conditions if the first number can't eat the last or the length is 1, returning false or true, respectively. These values are found by dereferencing a pointer to the C-String (which gives a char) at the beginning and end of the string, and doing the comparisons on them. pointer arithmetic is done to find the end of the string. finally, the last char is "erased" by replacing it with a null terminator (0).

It's possible that the modulus arithmetic could be shortened by a byte or two, but I already need a shower after that pointer manipulation.

Ungolfed Version Here

Update: Saved two bytes by replacing c==1 with !c. This is essentially c == 0. It will run an additional time, and will needlessly double itself before deleting itself, but saves two bytes. A side effect is null or zero length strings won't cause infinite recursion (though we shouldn't get null strings as the exercise says positive integers).

\$\endgroup\$
6
  • \$\begingroup\$ You do not need to link libraries in the case of gcc - although warnings will be generated, gcc will happily compile your code without #includes. Also, you could save 4 bytes with -DR=return. Finally, in your test code, the \0s are unnecessary, as the string literally already include them implicitly. \$\endgroup\$
    – user77406
    Dec 8, 2018 at 11:14
  • 1
    \$\begingroup\$ Furthermore, you can return from a function by assigning to the first variable: b=case1?res1:case2?res2:res_else; is the same as if(case1)return res1;if(case2)return res2;return res_else; \$\endgroup\$
    – user77406
    Dec 8, 2018 at 11:22
  • \$\begingroup\$ Even further, you can shed some extra bytes by not using c: you can determine if the string is zero-length from head-tail. \$\endgroup\$
    – user77406
    Dec 8, 2018 at 11:25
  • \$\begingroup\$ 77 bytes \$\endgroup\$
    – user77406
    Dec 8, 2018 at 12:34
  • \$\begingroup\$ Didn't realize you could use ternary (conditional) operators in C. Has that always been the case? Regardless, good to know; I'll be using them in the future. Cheers \$\endgroup\$ Dec 9, 2018 at 0:59
1
\$\begingroup\$

Powershell, 89 bytes

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

Important! The script calls itself recursively. So save the script as g.ps1 file in the current directory. Also you can call a script block variable instead script file (see the test script below). That calls has same length.

Note 1: The script uses a lazy evaluation of logic operators -or and -and. If "$args"-notmatch'(.)(.*)(.)' is True then the right subexpression of -or is not evaluated. Also if ($m=$Matches).1-ge$m.3 is False then the right subexpression of -and is not evaluated too. So we avoid infinite recursion.

Note 2: The regular expression '(.)(.*)(.)' does not contain start and end anchors because the expression (.*) is greedy by default.

Test script

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

Output:

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

No recursion. No file name dependency and no script block name dependency.

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]

A Powershell implicitly converts a right operand to a type of a left operand. Therefore, $s-ge$s%10 calculates right operand $s%10 as integer and compare it as a string because type of the left operand is string. And 2+$s[0]+$s converts a char $s[0] and string $s to integer because left operand 2 is integer.

$s|% S*g 1($s.Length-2) is a shortcut to $s.Substring(1,($s.Length-2))

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

C# (Visual C# Interactive Compiler), 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;}

Try it online!

Success or failure is determined by presence or absence of an exception. Input is in the form of a string.

Less golfed...

// 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;
}

There are a couple extra bytes to deal with converting between characters and digits, but overall that didn't affect the size too much.

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

Perl 5 -pF, 53 bytes

$F[0]=($F[0]+pop@F)%10while$#F&&$F[0]>=$F[-1];$_=!$#F

Try it online!

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

Brachylog, 18 bytes

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

Try it online!

Takes three bytes off Fatalize's solution just by virtue of non-deterministic superscriptless existing now, but loses another three by doing vaguely Jelly-inspired things with z₁ to avoid using c, g, or even h. (Also inspired by trying, and failing, to use a different new feature: the ʰ metapredicate.)

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

PowerShell, 94 91 bytes

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

Try it online!


Test Script

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())" }

Ungolfed code:

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
}
\$\endgroup\$
6
  • 1
    \$\begingroup\$ You shouldn't need to check $n[0] in your for statement -- just checking $n should be enough. \$\endgroup\$ Dec 7, 2018 at 19:16
  • \$\begingroup\$ You could to use -6 instead -96 because it is enough to calc %10 \$\endgroup\$
    – mazzy
    Dec 8, 2018 at 12:48
  • \$\begingroup\$ you could remove return and save 7 bytes \$\endgroup\$
    – mazzy
    Dec 8, 2018 at 12:49
  • \$\begingroup\$ and I think you should include a parameter declaration to the bytes count. either param($n) or function f($n). \$\endgroup\$
    – mazzy
    Dec 8, 2018 at 13:04
  • 1
    \$\begingroup\$ @mazzy The poster stated in the comments that you were allowed to use strings, you just weren't allowed to give the input as a list of numbers/strings. I interpreted this as ["1","2","3"] isn't valid input but "123"is. if @VedantKandoi has an issue with it I can definitely change it! \$\endgroup\$
    – KGlasier
    Dec 10, 2018 at 15:12

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.