GET your dubs together

25

2

On 4chan, a popular game is get. Every post on the site gets a sequential post ID. Since you can't influence or determine them, people try to guess (at least a part of) their own post number, usually the first few digits. Another version of the game is called dubs, and it's goal is to get repeating digits at the end of the number (i.e 1234555).

Your task, if you wish to accept it, is to write a program that takes a post id as input (standard integer, you can assume below 2^32), and returns how many repeating digits are on the end.

Rules

  • Standard loopholes are disallowed.
  • The program can be a function, full program, REPL command, whatever works, really, as long as no external uncounted code/arguments are needed to run it.
  • Input can come from STDIN, function arguments, command line argument, file, whatever suits you.

Test Cases

Input: 14892093
Output: 1

Input: 12344444
Output: 5

Input: 112311
Output: 2

Input: 888888
Output: 6

Input: 135866667 //Post number I got on /pol/ few days ago, rip
Output: 1

sagiksp

Posted 2017-03-28T08:51:40.363

Reputation: 1 249

1Are we allowed to take input as string? – Dead Possum – 2017-03-28T09:11:51.967

6@DeadPossum I would assume that's allowed, since you get a string anyway if you read the input from STDIN, command-line argument or file (which are all admissible input methods). – Martin Ender – 2017-03-28T09:19:50.253

1Can we assume that the input will be greater than 0? – Martin Ender – 2017-03-28T10:01:33.423

1@MartinEnder Yes – sagiksp – 2017-03-28T10:05:07.743

2Upvote for the dubs game! Check'em! – ZombieChowder – 2017-03-28T12:31:07.083

@sagiksp That goes against our default. Is that really your intent?

– Mego – 2017-03-28T13:47:14.787

@Mego Nevermind you can use it all – sagiksp – 2017-03-28T16:15:23.557

Could someone make a solution that actually uses 4chan and some URL-related feature? – ckjbgames – 2017-03-28T20:31:42.607

@ckjbgames What would it be, the user gets a url and has to regex the number out first? I'm thinking maybe a comment finder by ID would work (Looks through all threads with sequential id to find a specific id comment, because you can't index by comment in the 4chan api), but for this challeange it just won't work. – sagiksp – 2017-03-28T20:39:35.060

Disappointed: The question ID on SE does not have dubs. – Num Lock – 2017-03-30T09:42:12.147

@NumLock That would have been so perfect :D – sagiksp – 2017-03-30T19:30:58.450

Answers

19

Mathematica, 29 bytes

How about an arithmetic solution?

IntegerExponent[9#+#~Mod~10]&

I'm very pleased to see that this beats the straight-forward Mathematica approach.

Explanation

The code itself computes 9*n + n%10 and then finds the largest power of 10 that divides the input, or in other words, counts the trailing zeros. We need to show if n ends in k repeated digits, that 9*n + n%10 has k trailing zeros.

Rep-digits are most easily expressed mathematically by dividing a number like 99999 (which is 105-1) by 9 and then multiplying by the repeated digit. So we can write n = m*10k + d*(10k-1)/9, where m ≢ d (mod 10), to ensure that n doesn't end in more than k repeated digits. Note that d = n%10.

Let's plug that into our formula 9*n + n%10. We get 9*m*10k + d*(10k-1) + d. The d at the end is cancelled, so we're left with: 9*m*10k + d*10k = (9*m + d)*10k. But 9 ≡ -1 (mod 10), so 9*m + d ≡ d - m (mod 10). But we've asserted that m ≢ d (mod 10) and hence d - m ≢ 0 (mod 10).

In other words, we've shown that 9*m + d is not divisible by 10 and therefore, the largest power of 10 that divides 9*n + n%10 = (9*m + d)*10k is k, the number of trailing repeated digits.

As a bonus, this solution prints the correct result, , for input 0.

Martin Ender

Posted 2017-03-28T08:51:40.363

Reputation: 184 808

1It's times like this that I wish this site supported MathJax; bold formulae are not as nice as typeset ones. It's nice that you took the time to write the exponents superscript though. – wizzwizz4 – 2017-03-30T17:49:47.693

1@wizzwizz4 I used to use code formatting, but I've found that bold (which is usually used by Dennis) is a bit more readable than that. But agreed, it's not as nice as MathJax. – Martin Ender – 2017-03-30T17:57:32.110

13

Retina, 9 bytes

&`(.)\1*$

Try it online!

Counts the number of overlapping matches of (.)\1*$ which is a regex that matches a suffix of identical characters.

Martin Ender

Posted 2017-03-28T08:51:40.363

Reputation: 184 808

2This must be a meme: you and your regex – Christopher – 2017-03-28T10:13:17.463

I need to learn all of these modifiers - I would have just gone for (.)(?=\1*$). – Neil – 2017-03-28T11:56:34.243

1@DownChristopher he literally made a regex-based language, this goes beyond meme material c: – Rod – 2017-03-28T12:00:32.573

1@Neil If it's any consolation, my first attempt was (?=(.)\1*$) (so basically the same as yours). – Martin Ender – 2017-03-28T12:07:07.170

1Yes it is, thanks! – Neil – 2017-03-28T12:18:46.533

9

Brachylog, 4 bytes

ẹḅtl

Try it online!

Explanation

ẹ       Elements: split to a list of digits
 ḅ      Blocks: group consecutive equal digits into lists
  t     Tail: take the last list
   l    Length: Output is the length of that last list

If worked directly on integers (and I'm not sure why I didn't implement it so that it does), this would only be 3 bytes as the would not be needed.

Fatalize

Posted 2017-03-28T08:51:40.363

Reputation: 32 976

9

Python 2, 47 41 bytes

lambda s:len(`s`)-len(`s`.rstrip(`s%10`))

Try it online!

36 bytes - For a more flexible input

lambda s:len(s)-len(s.rstrip(s[-1]))

Try it online!

Rod

Posted 2017-03-28T08:51:40.363

Reputation: 17 588

Wow. I gotta learn builtins more attentively. +1 – Dead Possum – 2017-03-28T12:48:02.770

2@DeadPossum dir(object) is our friend c: – Rod – 2017-03-28T12:50:02.873

BTW we are not allowed to take string as input. "If your method of input automatically returns strings then sure, but you cannot assume that the input will be provided as strings." :C – Dead Possum – 2017-03-28T13:00:57.230

1@DeadPossum I think that the author changed his mind about that. The comment seems to have been deleted. – Brian McCutchon – 2017-03-29T03:15:10.413

8

Javascript (ES6), 55 52 32 30 bytes

a=>a.match`(.)\\1*$`[0].length
  • Saved 19 bytes thanks to @MartinEnder by replacing the regex
  • Saved 2 bytes thanks to @user81655 using tagged templates literals

Using a regex to match the last group of the last digit

Note: First time posting. Do not hesitate to make remarks.

f=a=>a.match`(.)\\1*$`[0].length


console.log(f("14892093"));//1
console.log(f("12344444"));//5
console.log(f("112311"));//2
console.log(f("888888"));//6
console.log(f("135866667 "));//1

Weedoze

Posted 2017-03-28T08:51:40.363

Reputation: 931

Welcome to PPCG! You can save a lot of bytes by using a backreference instead of filling in the repeated character manually: /(.)\1*$/ – Martin Ender – 2017-03-28T10:02:46.547

Also, unnamed functions are completely fine (unless you need the name for recursive calls for example), so you can save two bytes on the f=. – Martin Ender – 2017-03-28T10:03:15.133

Good job! This for sure passes review but this could be golfed – Christopher – 2017-03-28T10:07:46.467

@MartinEnder Thanks ! I still have to learn how to golf – Weedoze – 2017-03-28T10:13:34.723

@DownChristopher Thanks ! I will try to do better next time – Weedoze – 2017-03-28T10:13:54.547

@Weedoze Yeah golfing is really hard but good job – Christopher – 2017-03-28T10:19:00.313

Anonymous functions are allowed, so you can remove the f= from your byte count. :) Also, another trick you could use is tagged template literals. match passes its first argument into RegExp(arg), so you can pass a string and it will turn into a RegExp object. Knowing this, you could call it like match\(.)\1*$`` for one less byte.

– user81655 – 2017-03-28T13:37:53.430

@user81655 Thanks ! I am still learning the tricks of golfing – Weedoze – 2017-03-28T13:43:55.197

@Weedoze Make sure to explicitly say if it's Javascript ES6 or not (for clarity). – Feathercrown – 2017-03-28T16:07:48.493

7

C, 62 56 48 47 bytes

Saved a byte thanks to @Steadybox!

j,k;f(n){for(k=j=n%10;j==n%10;n/=10,k++);k-=j;}

Try it online!

betseg

Posted 2017-03-28T08:51:40.363

Reputation: 8 493

7

PHP, 47 45 40 bytes

while($argn[-++$i]==$argn[-1]);echo$i-1;

Run with echo <n> | php -nR '<code>

seems a loop is still smaller than my first answer. simply count the chars that are equal to the last. This uses negative string offsets of PHP 7.1.

-5 bytes by Titus. Thanks !


Old answer:

<?=strlen($a=$argv[1])-strlen(chop($a,$a[-1]));

removes from the right every character matching the rightmost character and calculates the difference in the length.

Christoph

Posted 2017-03-28T08:51:40.363

Reputation: 1 489

-R and $argn could save 5 bytes. – Titus – 2017-03-30T08:58:55.550

6

05AB1E, 4 bytes

.¡¤g

Try it online! or as a Test suite

Explanation

.¡    # group consecutive equal elements in input
  ¤   # get the last group
   g  # push its length

Emigna

Posted 2017-03-28T08:51:40.363

Reputation: 50 798

6

CJam, 7 bytes

re`W=0=

Try it online!

Explanation

r   e# Read input.
e`  e# Run-length encode.
W=  e# Get last run.
0=  e# Get length.

Martin Ender

Posted 2017-03-28T08:51:40.363

Reputation: 184 808

6

Perl 5, 22 bytes

21 bytes of code + -p flag.

/(.)\1*$/;$_=length$&

Try it online!

/(.)\1*$/ gets the last identical numbers, and then $_=length$& assigns its length to $_, which is implicitly printed thanks to -p flag.

Dada

Posted 2017-03-28T08:51:40.363

Reputation: 8 279

6

Jelly, 5 bytes

DŒgṪL

Try it online!

Explanation

D      # convert from integer to decimal   
 Œg    # group runs of equal elements
   Ṫ   # tail
    L  # length

Emigna

Posted 2017-03-28T08:51:40.363

Reputation: 50 798

6

Python 2, 38 32 bytes

f=lambda n:0<n%100%11or-~f(n/10)

Thanks to @xnor for saving 6 bytes!

Try it online!

Dennis

Posted 2017-03-28T08:51:40.363

Reputation: 196 637

6

C (gcc), 32 29 bytes

f(x){x=x%100%11?1:-~f(x/10);}

This is a port of my Python answer.

This work with gcc, but the lack of a return statement is undefined behavior.

Try it online!

Dennis

Posted 2017-03-28T08:51:40.363

Reputation: 196 637

I'm confused, how come you neither pass a pointer, and change the value at the location, or just return the value. This looks like it just changes the local copy, which would make the function unusable, but this works on TIO. You also add 1 to n in the footer, rather then sizeof(int), wouldn't that move it 1 byte forwards, rather than the full width of an int? Clearly there are some tricks I could learn here, and I could probably use the first one in my own answer. – Bijan – 2017-03-29T00:01:51.673

2All the return statement does is storing the return value in EAX. With gcc, assigning it to a variable happens to do the same thing. As for the pointer arithmetic, when you add 1 to an int pointer, it moves to the next int, not the next byte. – Dennis – 2017-03-29T03:54:15.690

Are there cases (when using ints) when it would be better to return, it seems like in the worst case you would make a new int, and assign that. – Bijan – 2017-03-29T12:40:52.677

@Bijan C compilers always align direct memory access to the size of an atom of the primitive in question -- i don't remember if it's in the standard, though – cat – 2017-03-29T13:00:22.630

5

Python 2, 51 bytes

Takes integer as input. Try it online

lambda S:[x==`S`[-1]for x in`S`[::-1]+'~'].index(0)

48 bytes for string as input. Try it online

lambda S:[x==S[-1]for x in S[::-1]+'~'].index(0)

Dead Possum

Posted 2017-03-28T08:51:40.363

Reputation: 3 256

5

C#, 63 62 bytes


Golfed

i=>{int a=i.Length-1,b=a;while(a-->0&&i[a]==i[b]);return b-a;}

Ungolfed

i => {
    int a = i.Length - 1,
        b = a;

    while( a-- > 0 && i[ a ] == i[ b ] );

    return b - a;
}

Ungolfed readable

i => {
    int a = i.Length - 1, // Store the length of the input
        b = a ;           // Get the position of the last char

    // Cycle through the string from the right to the left
    //   while the current char is equal to the last char
    while( a-- > 0 && i[ a ] == i[ b ] );

    // Return the difference between the last position
    //   and the last occurrence of the same char
    return b - a;
}

Full code

using System;

namespace Namespace {
   class Program {
      static void Main( String[] args ) {
         Func<String, Int32> f = i => {
            int a = i.Length - 1, b = a;
            while( a-- > 0 && i[ a ] == i[ b ] );
            return b - a;
         };

         List<String>
            testCases = new List<String>() {
               "14892093",
               "12344444",
               "112311",
               "888888",
               "135866667"
            };

         foreach( String testCase in testCases ) {
            Console.WriteLine( $" Input: {testCase}\nOutput: {f( testCase )}\n" );
         }

         Console.ReadLine();
      }
   }
}

Releases

  • v1.1 - - 1 byte  - Thanks to Kevin's comment.
  • v1.0 -  63 bytes - Initial solution.

Notes

Nothing to add

auhmaan

Posted 2017-03-28T08:51:40.363

Reputation: 906

+1 You can golf it by 1 byte, though. Like this: i=>{int a=i.Length-1,b=a;while(a-->0&&i[a]==i[b]);return b-a;}

– Kevin Cruijssen – 2017-03-28T13:19:57.773

4

MATL, 6 5 bytes

1 byte saved thanks to @Luis

&Y'O)

Try it at MATL Online

Explanation

        % Implicitly grab input as a string
&Y'     % Perform run-length encoding on the string but keep only the second output
        % Which is the number of successive times an element appeared
O)      % Grab the last element from this array
        % Implicitly display

Suever

Posted 2017-03-28T08:51:40.363

Reputation: 10 257

I had forgotten that & did that to Y':-D Why not take input as a string enclosed in quotes and get rid of j? – Luis Mendo – 2017-03-28T14:07:19.260

@LuisMendo I wasn't sure if I could do that since the challenge explicitly said that input was an "integer" – Suever – 2017-03-28T14:17:06.707

I assumed so from Martin's comment and from the default rules, which allow that. But I'm not really sure

– Luis Mendo – 2017-03-28T14:18:46.780

@LuisMendo Ah ok didn't see his comment. Will update! – Suever – 2017-03-28T14:20:23.497

4

Cubix, 24 19 bytes

)uO)ABq-!wpUp)W.@;;

Note

  • Actually counts how many of the same characters are at the end of the input, so this works for really big integers and really long strings as well (as long as the amount of same characters at the end is smaller than the maximum precision of JavaScript (around 15 digits in base-10).
  • Input goes in the input field, output is printed to the output field

Try it here

Explanation

First, let's expand the cube

    ) u
    O )
A B q - ! w p U
p ) W . @ ; ; .
    . .
    . .

The steps in the execution can be split up in three phases:

  1. Parse input
  2. Compare characters
  3. Print result

Phase 1: Input

The first two characters that are executed are A and B. A reads all input and pushes it as character codes to the stack. Note that this is done in reverse, the first character ends up on top of the stack, the last character almost at the bottom. At the very bottom, -1 (EOF) is placed, which will be used as a counter for the amount of consecutive characters at the end of the string. Since we need the top of the stack to contain the last two characters, we reverse the stack, before entering the loop. Note that the top part of the stack now looks like: ..., C[n-1], C[n], -1.

The IP's place on the cube is where the E is, and it's pointing right. All instructions that have not yet been executed, were replaced by no-ops (full stops).

    . .
    . .
A B E . . . . .
. . . . . . . .
    . .
    . .

Phase 2: Character comparison

The stack is ..., C[a-1], C[a], counter, where counter is the counter to increment when the two characters to check (C[a] and C[a-1]) are equal. The IP first enters this loop at the S character, moving right. The E character is the position where the IP will end up (pointing right) when C[a] and C[a-1] do not have the same value, which means that subtracting C[a] from C[a-1] does not yield 0, in which case the instruction following the ! will be skipped (which is a w).

    . .
    . .
. S q - ! w E .
p ) W . . ; ; .
    . .
    . .

Here are the instructions that are executed during a full loop:

q-!;;p) # Explanation
q       # Push counter to the bottom of the stack
        #     Stack (counter, ..., C[a-1], C[a])
 -      # Subtract C[a] from C[a-1], which is 0 if both are equal
        #     Stack (counter, ..., C[a-1], C[a], C[a-1]-C[a])
  !     # Leave the loop if C[a-1]-C[a] does not equal 0
   ;;   # Remove result of subtraction and C[a] from stack
        #     Stack (counter, ..., C[a-1])
     p  # Move the bottom of the stack to the top
        #     Stack (..., C[a-1], counter)
      ) # Increment the counter
        #     Stack (..., C[a-1], counter + 1)

And then it loops around.

Phase 3: Print result

Since we left the loop early, the stack looks like this: counter, ..., C[a-1]-C[a]. It's easy to print the counter, but we have to increment the counter once because we didn't do it in the last iteration of the loop, and once more because we started counting at -1 instead of 0. The path on the cube looks like this, starting at S, pointing right. The two no-ops that are executed by the IP are replaced by arrows that point in the direction of the IP.

    ) u
    O )
. B . . . S p U
. ) . . @ . . .
    > >
    . .

The instructions are executed in the following order. Note that the B) instructions at the end change the stack, but don't affect the program, since we are about to terminate it, and we do not use the stack anymore.

p))OB)@ # Explanation
p       # Pull the counter to the top
        #     Stack: (..., counter)
 ))     # Add two
        #     Stack: (..., counter + 2)
   O    # Output as number
    B)  # Reverse the stack and increment the top
      @ # End the program

Alea iacta est.

Luke

Posted 2017-03-28T08:51:40.363

Reputation: 4 675

3

Batch, 91 bytes

@set s=-%1
@set n=1
:l
@if %s:~-2,1%==%s:~-1% set s=%s:~,-1%&set/an+=1&goto l
@echo %n%

The - prevents the test from running off the start of the string.

Neil

Posted 2017-03-28T08:51:40.363

Reputation: 95 035

3

JavaScript (ES6), 34 bytes

f=(n,p)=>n%10-p?0:1+f(n/10|0,n%10)

Not shorter than the regex solution.

Recursive function which evaluates the digits from right-to-left, stopping when a different digit is encountered. The result is the number of iterations. p is undefined on the first iteration, which means n%10-p returns NaN (falsy). After that, p equals the previous digit with n%10. When the current digit (n%10) and the previous (p) are different, the loop ends.

user81655

Posted 2017-03-28T08:51:40.363

Reputation: 10 181

3

Röda, 12 bytes

{count|tail}

Try it online!

This is an anonymous function that expects that each character of the input string is pushed to the stream (I think this is valid in spirit of a recent meta question).

It uses two builtins: count and tail:

  1. count reads values from the stream and pushes the number of consecutive elements to the stream.
  2. tail returns the last value in the stream.

fergusq

Posted 2017-03-28T08:51:40.363

Reputation: 4 867

3

T-SQL, 238 214 Bytes

declare @ varchar(max) = '' declare @i int=0, @e int=0, @n int=right(@,1), @m int while (@i<=len(@)) begin set @m=(substring(@,len(@)-@i,1)) if (@n=@m) set @e=@e+1 else if (@i=0) set @e=1 set @i=@i+1 end select @e

Or:

declare @ varchar(max) = '12345678999999'
declare 
    @i int = 0,
    @e int = 0,
    @n int = right(@,1),
    @m int

while (@i <= len(@))
begin
    set @m = (substring(@,len(@)-@i,1))
    if (@n = @m) set @e = @e + 1
    else
    if (@i) = 0 set @e = 1
    set @i = @i + 1
end
select @e

Nelz

Posted 2017-03-28T08:51:40.363

Reputation: 321

2

Mathematica, 33 30 bytes

Thanks to Greg Martin for saving 3 bytes.

Tr[1^Last@Split@Characters@#]&

Takes input as a string.

Gets the decimal digits (in the form of characters), splits them into runs of identical elements, gets the last run and computes the length with the standard trick of taking the sum of the vector 1^list.

Martin Ender

Posted 2017-03-28T08:51:40.363

Reputation: 184 808

Characters instead of IntegerDigits? – Greg Martin – 2017-03-28T17:23:15.453

@GregMartin Ah yeah, I guess. Thanks. – Martin Ender – 2017-03-28T17:24:22.197

You still don't beat that other shrewd Mathematica golfer for this question ;)

– Greg Martin – 2017-03-28T17:26:40.793

@GregMartin What a shame. :) – Martin Ender – 2017-03-28T17:27:05.627

2

Java 7, 78 bytes

int c(int n){return(""+n).length()-(""+n).replaceAll("(.)\\1*$","").length();}

Try it here.

I tried some things using recursion or a loop, but both ended up above 100 bytes..

Kevin Cruijssen

Posted 2017-03-28T08:51:40.363

Reputation: 67 575

2

Powershell, 41 Bytes

for($n="$args";$n[-1]-eq$n[-++$a]){};$a-1

straightforward loop backwards until a char doesn't match the last char in the string, return the index of that char -1.

-3 thanks to @AdmBorkBork - using a for loop instead of a while.

colsw

Posted 2017-03-28T08:51:40.363

Reputation: 3 195

2

JavaScript (ES6), 39 38 37 27 bytes

f=n=>n%100%11?1:1+f(n/10|0)

Maybe not shorter than the regex-based solution, but I couldn't resist writing a solution entirely based on arithmetic. The technique is to repeatedly take n % 100 % 11 and divide by 10 until the result is non-zero, then count the iterations. This works because if the last two digits are the same, n % 100 % 11 will be 0.

ETHproductions

Posted 2017-03-28T08:51:40.363

Reputation: 47 880

Ah, you finished just before me haha! I'm not sure whether to post another answer, since they will most likely converge after golfing, but here's my solution using 34 bytes: f=(n,p)=>n%10-p?0:1+f(n/10|0,n%10) – user81655 – 2017-03-28T13:44:57.837

@user81655 That's great, feel free to post it. I don't think mine will converge down to that without a complete makeover, and of course now that I've seen yours that won't happen ;-) – ETHproductions – 2017-03-28T13:51:34.383

2

Python 3 - 50 44 bytes

Full program (in Python 3, input() returns a string, no matter the input):

g=input();print(len(g)-len(g.rstrip(g[-1]))) 

Mr. Xcoder

Posted 2017-03-28T08:51:40.363

Reputation: 39 774

2

Bash + Unix utilities, 34 bytes

sed s/.*[^${1: -1}].//<<<x$1|wc -c

Try it online!

Mitchell Spector

Posted 2017-03-28T08:51:40.363

Reputation: 3 392

2

Haskell, 33 bytes

f(h:t)=sum[1|all(==h)t]+f t
f _=0

Try it online!

Takes string input. Repeatedly cuts off the first character, and adds 1 if all characters in the suffix are equal to the first one.

xnor

Posted 2017-03-28T08:51:40.363

Reputation: 115 687

2

R, 35 bytes

rle(rev(charToRaw(scan(,''))))$l[1]

Brief explanation

                  scan(,'')         # get input as a string
        charToRaw(         )        # convert to a vector of raws (splits the string)
    rev(                    )       # reverse the vector
rle(                         )$l[1] # the first length from run length encoding

MickyT

Posted 2017-03-28T08:51:40.363

Reputation: 11 735

2

Befunge-98, 19 bytes

01g3j@.$~:01p-!j$1+

Try it online!

This could be made shorter if I managed to only use the stack.

How it works:

01g3j@.$~:01p-!j$1+
01g                 ; Get the stored value (default: 32)                 ;
   3j               ; Skip to the ~                                      ;
        ~           ; Get the next character of input                    ;
         :01p       ; Overwrite the stored value with the new char       ;
             -!     ; Compare the old value and the new                  ;
               j$   ; Skip the $ when equal, else pop the counter        ;
                 1+ ; Increment the counter                              ;

; When the input runs out, ~ reflects the IP and we run: ;
   @.$
     $              ; Pop the extraneous value (the stored value) ;
   @.               ; Print the number and exit                   ;

Justin

Posted 2017-03-28T08:51:40.363

Reputation: 19 757

1

C, 62 55 bytes

i,j;f(n){for(i=0,j=n%10;++i;n/=10)if(j-n%10)return--i;}

Try it online!

Steadybox

Posted 2017-03-28T08:51:40.363

Reputation: 15 798

1

REXX, 50 bytes

arg ''-1 # 1 n
say length(n)-length(strip(n,T,#))

Parse argument with empty string, causing parsing cursor to move to end of argument, then left one step, put remainder (one character) of argument in # variable, move to first character and put first word of argument in n variable.

Strip trailing characters equivalent to # from n and compare length to n.

idrougge

Posted 2017-03-28T08:51:40.363

Reputation: 641

1

Ruby, 28 22 bytes

->s{s[/(.)\1*$/].size}

Anonymous function that takes the number as a string.

m-chrzan

Posted 2017-03-28T08:51:40.363

Reputation: 1 390

1I believe you can get the match of a regex in Ruby like s[/(.)\1*$/]. – user81655 – 2017-03-28T13:57:07.137

1

Octave, 30 bytes

@(s)find(flip(diff([0 +s])),1)

Try it online!

Luis Mendo

Posted 2017-03-28T08:51:40.363

Reputation: 87 464

1

C (clang), 41 bytes

f(x){return x&&x%10-x/10%10?1:f(x/10)+1;}

There are already 2 other C solutions, but they both depend on loops. This uses recursion. If the last 2 digits are different then it's 1, otherwise you do 1+ the number of consecutive digits of the number with the last digit removed.

Try it online!

Bijan

Posted 2017-03-28T08:51:40.363

Reputation: 781

1

JavaScript (ES6), 53 bytes

f=(n,i=1)=>(a=[...n]).pop()==a[a.length-1]?f(a,i+1):i

Huntro

Posted 2017-03-28T08:51:40.363

Reputation: 459

1

Japt, 23 bytes

¬â l ¥1?Ul :Uw ¬b@X¦UgJ

Try it online!

Explanation:

¬â l ¥1?Ul :Uw ¬b@X¦UgJ
¬                         // Split the input into an array of chars
 â                        // Return all unique permutations
   l ¥1                   // Check if the length is equal to 1
       ?                  // If yes, return: 
        Ul                //   The length of the input
            :             // Else, return:
             Uw           //   The input, reversed
                ¬         //   Split into an array of chars
                  @       //   Iterate through, where X is the iterative item
                 b        //   Return the first index where:
                   X¦     //     X != 
                     UgJ  //     The last char in the input

Oliver

Posted 2017-03-28T08:51:40.363

Reputation: 7 160

1

Haskell, 36 bytes

Without import solution (39 bytes)

f n=length.takeWhile(==last n)$reverse n

Note that a pointfree solution is longer (and less understandable): EDIT: since anonymous functions are allowed, let's shave off two bytes which brings us to 39 (still longer than 36):

(length.).takeWhile.(==).last<*>reverse

With import solution (36 bytes, 19 without import)

import Data.List
f=length.last.group

Run like f "2394398222222" either way

Generic Display Name

Posted 2017-03-28T08:51:40.363

Reputation: 365

1

Befunge-93, 45 bytes

<_v#`0:~
pv>$00p110
p>00g-#v_10g1+10
  @.g01<

Try it online!

user55852

Posted 2017-03-28T08:51:40.363

Reputation:

1

Jelly, 4 bytes

ŒrṪṪ

Takes input as a string, returns a number.

Try it online!

Relatively simply, Œr Run-length encodes the input, pushes the last pair, then pushes its second item. Which thus gives us the length of consecutive digits at the end of the string.

ATaco

Posted 2017-03-28T08:51:40.363

Reputation: 7 898

1

Clojure, 48 bytes

#(-> (partition-by identity (str %)) last count)

Usage: (#(-> (partition-by identity (str %)) last count) 123455)

=> 2

Ungolfed:

(defn count-digits [n]
                  (-> (partition-by identity (str n))
                      last
                      count))

Common Lisp, 82 bytes

(defun c (n) (if (eq (mod n 10) (floor (mod n 100) 10)) (+ 1 (c (floor n 10))) 1))

Ungolfed:

(defun c (n)
  (if (eq (mod n 10)
          (floor (mod n 100) 10))
      (+ 1 (c (floor n 10))) 1))

zelcon

Posted 2017-03-28T08:51:40.363

Reputation: 121

1Welcome To PPCG! Wonderful first post, It looks like you have the basics of formatting down, just note that in the future you an make multiple answers if you use multiple languages (good for getting more rep :) ) – Taylor Scott – 2017-03-31T01:50:22.933

0

PHP 40chars

(Does not take into account php tags)

strlen(preg_match('/(.)\1*$/',$argv[1]))

Jackal

Posted 2017-03-28T08:51:40.363

Reputation: 1

I think you mean preg_match('/(.)\1*$/',$argv[1],$t);echo strlen($t[0]); or as alternative <?=strlen(preg_filter('/.*?((.)\2*)$/','\1',$argv[1])); – Jörg Hülsermann – 2017-03-31T02:08:26.340

0

C#, 49 bytes

i=>i.Reverse().TakeWhile(x=>x==i.Last()).Count();

Try it here

Full code

  using System;
  using System.Linq;

  class Program
  {
      static void Main()
      {
          Func<string, int> func = i=>i.Reverse().TakeWhile(x=>x==i.Last()).Count();

          Console.WriteLine(func("14892093"));
          Console.WriteLine(func("12344444"));
          Console.WriteLine(func("112311"));
          Console.WriteLine(func("888888"));
          Console.WriteLine(func("135866667"));
          Console.ReadLine();
      }
  }

Daniel Dreibrodt

Posted 2017-03-28T08:51:40.363

Reputation: 101

0

Java 7, 64 62 bytes

Golfed:

int w(int x){int r=1,d=x%10;while((x/=10)%10==d)r++;return r;}

Ungolfed:

int w(int x)
{
    int r = 1, d = x % 10;
    while ((x /= 10) % 10 == d)
        r++;
    return r;
}

Try it online

peech

Posted 2017-03-28T08:51:40.363

Reputation: 309

0

Vim - 39

ix^[Y$d?[^^R=@@[len(@@)-2]^M]^Mcc^R=len(@2)^M

(^[, ^Ms and ^Rs are one char each)

  • insert non-number (for 88888 input), copy line, move to the end
  • delete searching backwards for a char other then the last char
  • replace line with length of deleted text

pacholik

Posted 2017-03-28T08:51:40.363

Reputation: 490

0

J, 14 bytes

>:i.&1}.~:|.":

Try it online!

It's fortunate that the challenge allows a REPL command. As a verb (function) it's 20 bytes:

3 :'>:i.&1}.~:|.":y'

For arbitrarily large integers, the literal must be suffixed by x.

Explained

Applied right to left, all monadic verbs:

  • ": Format - Stringifies its argument
  • |. Reverse
  • ~: Nub sieve - Produces a boolean array of 1's each time a new item is introduced, 0 otherwise
  • }. Behead - Removes first item of array
  • i.&1 Index of - Gets index of first 1. i. is actually a dyadic verb, but &1 ties right argument to 1.
  • >: Increment

kaoD

Posted 2017-03-28T08:51:40.363

Reputation: 584

0

Common Lisp, 72 chars

(lambda(i)(do((n i(floor n 10))(c 1(1+ c)))((/= 0(mod(mod n 100)11))c)))

Unoglfed

(lambda (i)
  (do ((n i (floor n 10))
       (c 1 (1+ c)))
      ((/= 0 (mod (mod n 100) 11)) c)))

Explanation

(/= 0 (mod (mod n 100) 11))

This checks to see if the last two digits of n are different- if n%100 is not divisible by 11.

(do ((n i (floor n 10))
     (c 1 (1+ c)))
    (... c))

do is a powerful generic looping construct in lisp. Its first argument is a list describing the looping variables. Each element is a list of (variable initial-value step-form) where step-form is evaluated each time through the loop to update that variable. The second argument is a test to perform to end the loop (the test I covered above) and a list of values to return after looping (in this case just c, which has been incrementing each time though the loop).

(lambda (i) ...) Wraps the operation in an anonymous function that takes the number as an integer.

djeis

Posted 2017-03-28T08:51:40.363

Reputation: 281

0

05AB1E, 3 bytes

Åγθ

Try it online or verify all test cases.

Or alternatively:

γθg

Try it online or verify all test cases.

Explanation:

Åγ   # Run-length decode the (implicit) input-integer
     #  i.e. 1333822 → [1,3,1,2]
  θ  # Pop and push the last item
     #  → 2
     # (which is output implicitly as result)

γ    # Split the (implicit) input-integer into parts of subsequent equal digits
     #  i.e. 1333822 → [1,333,8,22]
 θ   # Pop and push the last item
     #  → 22
  g  # Pop and push its length
     #  → 2
     # (which is output implicitly as result)

Kevin Cruijssen

Posted 2017-03-28T08:51:40.363

Reputation: 67 575

0

Pyth, 4 bytes

her9

Kinda surprised this hasn't been posted yet.

Try it online!

famous1622

Posted 2017-03-28T08:51:40.363

Reputation: 451

0

x86-16 machine code, IBM PC DOS, 22 21 20 bytes

Binary:

00000000: d1ee 8a1c 8d38 8a05 fdf3 aef6 d191 052f  .....8........./
00000010: 0ecd 10c3                                ....

Build and test DUBS.COM with xxd -R.

Unassembled listing:

D1 EE       SHR  SI, 1              ; SI to command line tail (80H) 
8A 1C       MOV  BL, BYTE PTR[SI]   ; BX = input string length 
8D 38       LEA  DI, [BX][SI]       ; DI to end of string 
8A 05       MOV  AL, BYTE PTR[DI]   ; AL = last char
FD          STD                     ; set LODS to decrement 
F3 AE       REPZ SCASB              ; scan [DI] backwards until AL doesn't match
F6 D1       NOT  CL                 ; negate CL to get number of matches + 1
91          XCHG AX, CX             ; AL = CL 
05 2F0E     ADD  AX, 0E2FH          ; ASCII convert and adjust, BIOS tty function
CD 10       INT  10H                ; write number to console 
C3          RET                     ; return to DOS

A standalone PC DOS executable program. Input via command line, output number to console.

Notes:

This takes advantage of a few "features" of PC DOS register startup values; specifically BH = 0, CX = 00FFH and SI = 100H. REPZ decrements CX on every compare operation, so starting at 00FFH will yield a negative count of reps. It is off-by-one because REPZ decrements before comparison, so the first non-match still gets counted. That number is ones-complimented and adjusted by 1 to get the count of matched digits.

Also, since CH = 0 it's possible to combine ADD AL, '0'-1 and MOV AH, 0EH into a single instruction ADD AX, 0E2FH to save 1 byte, since AH will be 0. Old-school SIMD for you!

I/O:

enter image description here

640KB

Posted 2017-03-28T08:51:40.363

Reputation: 7 149

0

Ruby -nl, 16 bytes

Input is STDIN. Subtracts the position of the start of the dubs sequence from the length of the string (technically, the position of the end of the string).

p~/$/-~/(.)\1*$/

Try it online!

Value Ink

Posted 2017-03-28T08:51:40.363

Reputation: 10 608