How can I get a repdigit?

32

3

In honor of how much rep I had several hours ago, when I first thought of this challenge:

enter image description here

Numbers like this that are made up of a single digit repeating are called repdigits. Repdigits are fun! Every body would be more happy if the amount of rep they had was a repdigit¹, but I am impatient, so you need to help me find out the fastest way to get to a repdigit.

Here is your challenge:

Given a positive integers representing reputation, output the minimum amount of rep they need to gain to get to a repdigit. For example, at the time of writing this challenge, user Martin Ender had 102,856 rep. The nearest rep-digit is 111,111, so he would need to gain: 8255 rep to be at a repdigit.

Since people dislike losing rep, we will only consider non-negative changes. This means that, for example, if someone is at 12 rep, rather than losing 1 rep, the solution is to gain 10 rep. This allows '0' to be a valid output, since anyone who has 111 rep is already at a repdigit.

Input and output can be in any reasonable format, and since it is impossible to have less than 1 rep on any Stack Exchange site, you can assume no inputs will be less than 1.

One cornercase to note:

If a user has less than 10 rep, they are already at a repdigit, and so they also need '0'.

Test IO:

#Input      #Ouput
8           0
100         11
113         109
87654321    1234567
42          2
20000       2222
11132       11090

Standard loopholes apply, and the shortest solution in bytes wins!

James

Posted 2016-08-24T06:25:33.790

Reputation: 54 537

Can I return the answer as a singleton array? It wouldn't actually save bytes, but I could make my answer a lot faster. – Dennis – 2016-08-24T06:43:54.617

1@Dennis I don't see why not. – James – 2016-08-24T06:53:52.727

Can we take input as a string? – Dennis – 2016-08-24T06:55:35.853

1@Dennis Why would I say no? I always try to avoid restrictive IO in my challenges, and a lot of languages (like my own) don't distinguish between string and integer input, so I don't see any reason I would restrict it. – James – 2016-08-24T07:10:49.537

2

Related: http://codegolf.stackexchange.com/q/73916/17602

– Neil – 2016-08-24T07:51:59.683

@DJMcMayhem Mind adding what a repdigit is in case the link is dead at some point? – Buffer Over Read – 2016-08-24T17:15:56.970

6@ColdGolf I highly doubt Wikipedia will die any time soon, but I added some more info. – James – 2016-08-24T17:18:06.623

The smallest possible rep gain is 2 rep from editing, right? Since the question says only positive changes are valid, wouldn't this affect the minimum actually possible increase to a repdigit in some cases, like 10 requiring +12 to get to 22, because there is no +1? The tests don't seem to consider this. – Anko – 2016-08-26T00:33:06.183

@Anko you can gain 2 by edit and lose 1 through negative vote, so it is possible to have one more rep than what you currently have, and while there is a loss involved, the absolute is still positive. – Brian H. – 2017-09-13T08:44:15.343

@BrianH. I guess the specificity of "we will only consider non-negative changes" is up to interpretation… I took it as "imagine nobody ever loses rep for anything". – Anko – 2017-09-13T10:13:52.850

@Anko, if it were impossible to lose rep, that would mean the lowest rep gain that turns odds to evens and viceversa would be 15 though, so the 100 would give 122 as result instead of 11 – Brian H. – 2017-09-13T10:18:07.077

1@brianh No, the smallest rep gain that turns odds to evens is 5 (question upvote). However, for the sake of this challenge, we're ignoring the fact that there are only certain amounts to gain rep. So 110 should give 1, even though there isn't a way to gain one rep. – James – 2017-09-13T12:09:53.577

Answers

9

Jelly, 6 bytes

DE$1#_

Output is a singleton array.

Try it online! or verify most test cases. Test case 87654321 is too slow for TIO.

How it works

DE$1#_  Main link. Argument: n

   1#   Call the link to the left with argument k = n, n + 1, n + 2, etc. until one
        match is found, then return the matching k.
  $       Combine the two links to the left into a monadic chain.
D           Convert k to base 10.
 E          Test if all decimal digits are equal.
     _  Subtract n from the result.

Dennis

Posted 2016-08-24T06:25:33.790

Reputation: 196 637

1Wow... all ASCII. This is a first. Are there any other Jelly solutions which are all ASCII? Just curious. – clismique – 2016-08-25T11:39:39.720

This one and that one were easy to find. There may be others. – Dennis – 2016-08-25T15:11:35.577

16

Haskell, 39 bytes

until(((==).head>>=all).show)(+1)>>=(-)

Try it online

Damien

Posted 2016-08-24T06:25:33.790

Reputation: 2 407

14

Brachylog, 9 bytes

:.#++#==,

Try it online!

This is pretty efficent as it makes use of constraints arithmetic.

Explanation

:.            The list [Input, Output].
  #+          Both elements must be positive or zero.
    +         The sum of those two elements…
     #=       …must result in an integer where all digits are the same.
       =,     Assign a value that matches those constraints.

Fatalize

Posted 2016-08-24T06:25:33.790

Reputation: 32 976

12I love how Brachylog reads like the answer. Like, you just define: This is the answer you're looking for. Figure it out for me :) – James – 2016-08-24T06:53:33.243

1@DJMcMayhem That's the cool factor of declarative languages! (though it's not always that magical :p) – Fatalize – 2016-08-24T06:54:58.657

Awesome solution! I think that Brachylog could always perform an implicit labeling of remaining CLP(FD) variables at the end of a program. To get this, wrap the whole execution in call_reside_vars/2, fetch the CLP(FD) variables, and label them. For example: call_residue_vars(Program, Vs0), include(fd_var, Vs0, Vs), label(Vs). What do you think? – mat – 2016-08-24T09:13:37.010

1@mat Thanks! I'll add implicit labeling at the end of programs to the list of enhancements to make, since I can't think of any situation where one would want to output a variable at the end of execution. – Fatalize – 2016-08-24T09:17:26.043

2Hey... – Leaky Nun – 2016-08-24T10:24:42.337

10

Python 2, 41 40 bytes

def f(n):r=10**len(`n`)/9;print-n/r*-r-n

Not the shortest approach, but very efficient. Test it on Ideone.

How it works

For input 10**len(`n`) rounds n up to the nearest power of 10. Afterwards, we divide the result by 9. This returns the repdigit 1…1 that has as many digits as n. We save the result in r. For example, if n = 87654321, then r = 11111111.

The desired repdigit will be a multiple or r. To decide which, we perform ceiling division of n by r. Since Python 2's division operator / floors, this can be achieved with -n/r, which will yield the correct absolute value, with negative sign. For example, if n = 87654321, this will return -8.

Finally, we multiply the computed quotient by -r to repeat the quotient once for each digit in n. For example, if n = 87654321, this returns 88888888, which is the desired repdigit.

Finally, to calculate the required increment, we subtract n from the previous result. For our example n = 87654321, this returns 1234567, as desired.

Dennis

Posted 2016-08-24T06:25:33.790

Reputation: 196 637

1Another 41 is lambda n:10**len(`n`)/9*-~int(`n*9`[0])-n. It almost works to do lambda n:int(`n*9`[0]*len(`n`))-n, but the digit is one too small and I don't see a good way to fix it. – xnor – 2016-08-24T07:27:38.487

1Would you mind explaining the logic behind this formula? Baffles me how it's O(1). – shooqie – 2016-08-24T07:32:14.590

1@shooqie I've edited my answer. – Dennis – 2016-08-24T07:51:16.887

@Dave: Huh, it's interesting actually. I always assumed that closed-form formula == O(1), but I guess it makes sense. – shooqie – 2016-08-24T07:53:50.117

Amazing approach. It may be slightly longer in terms of bytes for Python 2, but it saves a whopping 40 bytes in Java 7, so thanks. :) (Also thanks a lot for the "How it works" part.)

– Kevin Cruijssen – 2016-08-24T08:40:39.853

9

Python 2, 37 bytes

f=lambda n:1-len(set(`n`))and-~f(n+1)

Test it on Ideone. Note that this approach is too inefficient for test case 87654321.

How it works

If n is already a repdigit, 1-len(set(`n`)) will return 0 since the length of the set of n's digits in base 10 will be 1. In this case, f returns 0.

If n is not a repdigit, f(n+1) recursively calls f with the next possible value of n. -~ increments the return value of f (0 when a repdigit is found) by 1 each time f is called recursively, so the final return value equals the number of times f has been called, i.e., the number of times n had to be incremented to get a repdigit.

Dennis

Posted 2016-08-24T06:25:33.790

Reputation: 196 637

1I'm never clear for these things whether the L on longs needs to be handled. – xnor – 2016-08-24T06:59:04.763

4What the, how does-- it... You can't... what? For a moment there I was proud of my 52 byte answer... – James – 2016-08-24T06:59:12.000

1@xnor: Solutions in C aren't required to work for long integers by default, so I always assumed the same way true for Python. – Dennis – 2016-08-24T07:00:26.860

1@DJMcMayhem looks to me like it recursively counts up until it finds a repdigit via checking the size of a set built from the string representation of the number. The -~ allows the function to count the number of calls it made. – Value Ink – 2016-08-24T07:14:34.573

8

Perl 6, 23 bytes

{($_...{[==] .comb})-1}

A lambda that takes the input number as argument, and returns the result.

Explanation:

  1. Uses the ... sequence operator to increment the input number until it reaches a repdigit (tested by splitting its string representation into characters and seeing if they're all equal).
  2. Subtracts one from the length of the sequence.

smls

Posted 2016-08-24T06:25:33.790

Reputation: 4 352

The test can be replaced /(.)$0*/

– Jo King – 2019-05-05T22:08:18.340

7

Java 7, 116 76 bytes

int c(int i){int r=(int)Math.pow(10,(i+"").length())/9;return(-i/r-1)*-r-i;}

Used @Dennis' amazing approach to lower the byte-count by a whopping 40 bytes.

Ungolfed & test cases:

Try it here.

class Main{
  static int c(int i){
    int r = (int)Math.pow(10, (i+"").length()) / 9;
    return (-i / r - 1) * -r - i;
  }

  public static void main(String[] a){
    System.out.println(c(8));
    System.out.println(c(100));
    System.out.println(c(113));
    System.out.println(c(87654321));
    System.out.println(c(42));
    System.out.println(c(20000));
    System.out.println(c(11132));
  }
}

Output:

0
11
109
1234567
2
2222
11090

Kevin Cruijssen

Posted 2016-08-24T06:25:33.790

Reputation: 67 575

1Actually, your "try it" gives prints out 1 if you feed it 8 instead of printing 0 as it should. – SQB – 2016-08-24T15:48:51.040

@SQB Ah you're right. Hmm, that pretty weird, since the output in my post I've copy-pasted from my IDE console.. – Kevin Cruijssen – 2016-08-24T18:25:50.973

Shouldn't the second to last output be 2222 and the fourth output be 12345678? – DanTheMan – 2016-08-27T22:02:57.083

@DanTheMan Ah, the second to last should indeed be 2222 instead of 222. I fixed a mistake in the code, but had by accident still used the old output here. It's fixed now. As for the fourth, no, it should be 123467 (as you can also see at OP's question). – Kevin Cruijssen – 2016-08-28T08:13:33.990

4

Pyth, 9 8 7 bytes

1 byte thanks to @FryAmTheEggman.

-f@F`TQ

Try it online.

Very inefficient, loops through all numbers from the input to the next repdigit.

PurkkaKoodari

Posted 2016-08-24T06:25:33.790

Reputation: 16 699

@Emigna Thanks for notifying. Didn't have time to properly test it. – PurkkaKoodari – 2016-08-24T13:35:45.590

4

Brain-Flak 690 358 bytes

Here's my go at it

(({})[()])(()){{}(({}())){(({}))(<((()()()()()){}<>)>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}{}<>({}<{}>)<>(<((()()()()()){}(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>)}{}<>{(([])<{{}({}[()]<>)<>([])}{}><>){({}[()]<({}<>)<>>)}{}<>}([]){{}{(<({}<>)<>>)}{}([])}{}<>(([][()()])<{{}{}([][()()])}{}>)}{}({}[{}])

Try It Online

Explanation

Start by making a second copy of the input that is one less than the original. We will use the copy to search for the next repdigit. We subtract one in case the number itself was a repdigit

(({})[()])

Push one to satisfy the coming loop. (doesn't have to be one just not zero)

(())

This loop will run until there is a repdigit on top of the stack

{

Pop the crap. Their is a "boolean" on top that drives the loop, since it is no longer needed we pop it.

{}

Add one and duplicate the top. The copy will be decomposed into its digits.

(({}()))

While the copy is not zero...

{

Copy again

(({}))

Mod 10 and move to the other stack

(<((()()()()()){}<>)>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}{}<>({}<{}>)<>

Divide by 10 (Integer division)

(<((()()()()()){}(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>)

}

Pop the zero that was our copy

{}

We have now decomposed the number into its base 10 digits, So we swap over to the stack with all the digits.

<>

While the leading digit is not zero

{

We pick up a copy of the stack height (i.e. the number of digits)...

(([])<

Silently subtract one from every number on the stack

{
{}
({}[()]<>)<>
([])
}
{}

Put the stack height we picked up down. (and swap to the other stack)

><>)

We use the stack height to pull all the digits we placed on the other stack back onto the proper stack.

{
({}[()]<({}<>)<>>)
}

Pop the zero that was our stack height

{}

Swap back onto the stack with the digits (or what were the digits)

<>

End loop

}

Now we have subtracted the top digit from all the other digits. If all the digits are zero the orginal number (not the input but the number we are checking) was a repdigit.[citation needed]. So we need to check for non-zeroes.

While the stack height is not zero

([])
{
{}

If the digit is not zero move it to the other stack and replace it with a zero.

{
(<({}<>)<>>)
}

Pop it (now it is a zero)

{}

End loop

([])
}
{}

Swap over onto the other stack (duh..)

<>

Grab our selves a copy of the stack height minus two

(([][()()])<

While the stack height is not two (the original and the accumulator)

{
{}

Pop the top

{}

End the while

([][()()])
}
{}

Put down our copy of the stack height minus two. This ends up being the number of digits that are not the same as the first digit. In other words if it is zero it is a repdigit.

>)

If this loop ends we have found a repdigit

}

Pop the "boolean"

{}

Subtract the original from the repdigit

({}[{}])

Post Rock Garf Hunter

Posted 2016-08-24T06:25:33.790

Reputation: 55 382

Seriously, how do you do this? I was thinking "oh, I'd like to do it in brain flak, but I can't figure out how to determine if it's a repdigit or not". This is crazy! Do you use a script to generate most of these answers? – James – 2016-08-24T14:52:12.347

@DJMcMayhem Nope just practice. A explanation will follow. – Post Rock Garf Hunter – 2016-08-24T14:53:08.443

@DJMcMayhem I'm sorry perhaps I don't understand. 112+110 = 222? – Post Rock Garf Hunter – 2016-08-24T15:19:00.683

I'm sorry, you're totally right, I don't know what I'm saying. Please ignore that last comment. – James – 2016-08-24T15:20:44.790

3

Python 2, 52 bytes

a=b=input()
while len(set(str(a)))!=1:a+=1
print a-b

Python 2 has several tricks that make this shorter. For example, input is numeric, so we don't need to cast to int. (-5 bytes) We also don't need to put parenthesis around the a-b (-1 byte)

Use this script to verify all test cases:

def f(i):
    a=b=i
    while len(set(str(a)))!=1:a+=1
    return a-b

inputs = [8, 100, 113, 87654321, 42, 20000, 11132]
outputs = [0, 11, 109, 1234567, 2, 2222, 11090]

for i in range(len(inputs)):
    print(f(inputs[i]) == outputs[i])

You may also try it online!

James

Posted 2016-08-24T06:25:33.790

Reputation: 54 537

3

GNU sed, 223 + 1(r flag) = 224 bytes

s/$/:0%/
:;y/:%/%:/
/^(.)\1*%/{s/.*%(.*):/\1/;q}
:f;s/9(@*:)/@\1/;tf
s/8(@*:)/9\1/;s/7(@*:)/8\1/
s/6(@*:)/7\1/;s/5(@*:)/6\1/
s/4(@*:)/5\1/;s/3(@*:)/4\1/
s/2(@*:)/3\1/;s/1(@*:)/2\1/
s/0(@*:)/1\1/;s/(^|%)(@*:)/\11\2/
y/@/0/;t

Run:

sed -rf repdigit.sed <<< "112"

Output:

110

This is a pure sed solution, the arithmetic is simulated using regular expressions only. The algorithm works as follows:

  1. the pattern space format is set to ^current_reputation:needed_reputation%$
  2. in each iteration of the main loop the separators are switched:
    a) %: applies the increment to needed_reputation
    b) :% applies the increment to current_reputation
  3. if the current_reputation is a "repdigit", the needed_reputation is printed and the program ends

seshoumara

Posted 2016-08-24T06:25:33.790

Reputation: 2 878

2

05AB1E, 10 6 bytes

∞.Δ+Ë

Try it online!

Explanation

∞<      # from the infinite list of non-negative integers
  .Δ    # find the first number where
     Ë  # all digits are equal
    +   # after adding the input

Emigna

Posted 2016-08-24T06:25:33.790

Reputation: 50 798

1-2 bytes that no doubt weren't possible yet at time of posting: remove § and change ¹- to α. And here a rather similar 8-byte alternative: ∞+.ΔÙg}α – Kevin Cruijssen – 2019-05-06T11:47:45.570

2

JavaScript (ES6), 42 bytes

f=(n,p=1)=>n<p?-~(n*9/p)*~-p/9-n:f(n,p*10)

Explanation: Recursively computes p as the next power of 10 after n. The digit to be repeated is then computed as 1+floor(9n/p), and the repunit is simply (p-1)/9, from which the result follows.

Neil

Posted 2016-08-24T06:25:33.790

Reputation: 95 035

2

R, 102 98 91 bytes

a=scan(,'');i=0;while(length(unique(strsplit(a,"")[[1]]))!=1){a=paste(strtoi(a)+1);i=i+1};i

Ungolfed :

a=scan(,'') #Asks for input
i=0         #Initialize i to 0, surprisingly

while(length(unique(strsplit(a,"")[[1]]))!=1) 
    #Splits the input into its digits,  
    #compute the length of the vector created by the function `unique`, which gives all the digits once.
    #as long as the this length is different from one :
{
a=paste(strtoi(a)+1) #Increases by one the value of the input (while messing around with its format)
i=i+1                           #Increases by one the value of the counter
}

i #Outputs the counter

Messing around with the format (as.numeric and as.character) adds some bytes, but R is not really flexible !

Frédéric

Posted 2016-08-24T06:25:33.790

Reputation: 2 059

2

Perl, 40 + 1 (-n) = 41 bytes

/^(.)\1*$/&&say($v|0) or$_++&&++$v&&redo

If printing nothing instead of 0 when the number is already a repdigit is acceptable, then 37 bytes are enough :

/^(.)\1*$/&&say$v or$_++&&++$v&&redo

Run with -n (1 byte) and -E or -M5.010 (free) :

perl -nE '/^(.)\1*$/&&say($v|0) or$_++&&++$v&&redo'

Explanations : there are two major parts in the code : /^(.)\1*$/&&say$v and $_++&&++$v&&redo. The first one test if $_ is a repdigit; if yes it prints the number we added to the original number to make it a repdigit ($v), and if no, we had 1 to both $_ and $v, and start over.

Dada

Posted 2016-08-24T06:25:33.790

Reputation: 8 279

141 bytes of perl, duplicates 1st digit (or 1st digit+1 if any digit is larger than 1st) by length of string, then subtracts input: perl -pe '@x=sort/./g;//;$_=(($x[-1]>$&)+$&)x+@x-$_' – Eric – 2016-08-25T05:42:36.973

2

Java, 74 72 bytes

int c(int i){int n=0;while(!(i+++"").matches("^(.)\\1*$"))n++;return n;}

(If the other Java entry is 76 bytes, this one is 74 72, since it's two four bytes shorter).

Anyway, just increment the input until it's a repdigit while incrementing a counter. Return the counter.

Yes, those are three pluses in a row, two to increment the input, one to concatenate an empty string to make it a string.
No, I didn't think it would be legal without a space in between either, but there you go. That's what a typo will do for you: one byte shorter.

Using a for-loop instead of a while takes exactly as many bytes:

int c(int i){int n=0;for(;!(i+++"").matches("^(.)\\1*$");n++);return n;}

Edit:

An earlier version had matches("^(\\d)\\1*$") to check for a repdigit, but since we've just converted an int to a string, using a . to match is enough.


Ungolfed & test cases:

Try it here.

class Main{
  static int c(int i){
    int n=0;
    while(!(i++ + "").matches("^(.)\\1*$")) {
      n++;
    }
    return n;
  }

  public static void main(String[] a){
    System.out.println(c(8));
    System.out.println(c(100));
    System.out.println(c(113));
    System.out.println(c(87654321));
    System.out.println(c(42));
    System.out.println(c(20000));
    System.out.println(c(11132));
  }

}

Output:

0
11
109
1234567
2
2222
11090

SQB

Posted 2016-08-24T06:25:33.790

Reputation: 681

We normally recommend always using for loops as occasionally you can spot a way to save a byte in a way that you couldn't using a while loop. – Neil – 2016-08-24T20:19:24.323

@Neil Well, I'll be bleeped if I know how here. – SQB – 2016-08-24T21:55:49.437

I wasn't suggesting you could save a byte, I was just trying to point out that it was unremarkable that the for loop was the same length as you wouldn't expect it to be longer. – Neil – 2016-08-24T23:32:03.603

@Neill ah, okay. – SQB – 2016-08-25T04:54:06.347

1

Brachylog v2, 6 bytes

;.+=∧ℕ

Try it online!

  +       The sum of
          the input
;         and
 .        the output
   =      is a repdigit,
    ∧     and
          the output
     ℕ    is a whole number.

The 5-byte +↙.=∧ gets away with omitting because it doesn't try non-positive outputs at all, but it also fails when given a number which is already a repdigit because it doesn't try non-positive outputs at all.

Unrelated String

Posted 2016-08-24T06:25:33.790

Reputation: 5 300

1

Pyke, 13 11 bytes

o+`}ltIr)ot

Try it here!

            - o = 0
o+          -     o++ + input
  `         -    str(^)
   }        -   deduplicate(^)
    lt      -  len(^)-1
      I )   - if ^:
       r    -  goto_start()
         ot - o++ -1

Blue

Posted 2016-08-24T06:25:33.790

Reputation: 26 661

1

Actually, 15 bytes

;D;WXu;$╔l1<WX-

Try it online!

Explanation:

;D;WXu;$╔l1<WX-
;                dupe
 D;              decrement, dupe
   WXu;$╔l1<W    while top of stack is truthy:
    X              discard
     u             increment
      ;            dupe
       $╔l1<       1 if len(str(TOS)) > 1 else 0 (check if the string representation of the TOS contains only one unique digit)
                 after the loop, the stack will be [1 repdigit input]
             X   discard
              -  subtract input from repdigit

Mego

Posted 2016-08-24T06:25:33.790

Reputation: 32 998

1

Jellyfish, 20 bytes

p
<
)\&&&~j<i
->N>u0

Try it online! TIO can't handle the longer test cases, but given enough time and memory, they should work too.

Explanation

  • i is input, and < decrements it. This value is fed to the function on the left.
  • \> increments the value (at least once) until the function to the right gives a truthy value.
  • The test function is a composition (by &s) of four functions.
  • 0~j converts to string.
  • u removes duplicate digits.
  • > removes the head of the resulting string.
  • N is logical negation: it gives 1 for an empty string, and 0 for non-empty. Thus the function tests for a rep-digit, and the result of \ is the next rep-digit counting from <i.
  • )- subtracts the result from the function input, that is, <i.
  • This difference is off by one, so < decrements it. Finally, p prints the result.

Zgarb

Posted 2016-08-24T06:25:33.790

Reputation: 39 083

1

Excel, 85 79 bytes

Put the following formula in any cell except cell N since it's a name for reference cell of input:

=IF(1*(REPT(LEFT(N),LEN(N)))<N,REPT(LEFT(N)+1,LEN(N))-N,REPT(LEFT(N),LEN(N))-N)

Explanation:

  • N is the input and also name of reference cell.
  • LEFT(N) take the first digit of input value.
  • LEN(N) return the length of input value.
  • REPT(LEFT(N),LEN(N)) repeat the first digit of input value LEN(N) times and multiply it by 1 to convert text format to number format so we can use it for number comparison.
  • The syntax for the IF function in Microsoft Excel is: IF( condition, [value_if_true], [value_if_false]), hence makes the whole formula is self-explanatory.

Anastasiya-Romanova 秀

Posted 2016-08-24T06:25:33.790

Reputation: 1 673

You can omit Num_chars in LEFT and save 4 bytes: LEFT(N) – Wernisch – 2017-09-08T11:05:39.797

Make that 6 bytes – Wernisch – 2017-09-08T11:12:50.357

@Wernisch Thanks. Edited. – Anastasiya-Romanova 秀 – 2017-09-12T01:53:31.537

You can save 25 bytes by coercing the IF condition into a 1 or 0 using -- thus you do not need to repeat yourself just to +1: =REPT(LEFT(N)+(--1*(REPT(LEFT(N),LEN(N)))<N),LEN(N))-N – i_saw_drones – 2019-05-05T19:19:46.620

Actually, in this instance, you don't need to coerce it explicitly, you can instead just use: =REPT(LEFT(N)+(1*(REPT(LEFT(N),LEN(N)))<N),LEN(N))-N, saving 27 bytes to give a total of 52. – i_saw_drones – 2019-05-05T19:34:05.300

1

MATL, 10 bytes

q`QtVda}G-

Try it online!

This keeps incrementing the input until all digits are equal, so it's slow. The test case for input 87654321 times out in the online compiler.

q      % Take input implicitly. Subtract 1
`      % Do...while loop
  Q    %   Increment top of the stack
  tV   %   Duplicate and convert to string (i.e. digits of the number)
  d    %   Difference between consecutive digits
  a    %   True if any such difference is nonzero. This is the loop condition
}      % Finally (execute on loop exit)
  G-   %   Subtract input. This is the final result, to be (implicitly) displayed
       % End loop implicitly. If loop condition (top of the stack) is truthy: proceeds 
       % with next iteration. Else: executes the "finally" block and exits loop
       % Display implicitly

Luis Mendo

Posted 2016-08-24T06:25:33.790

Reputation: 87 464

1

PowerShell v2+, 66 bytes

param($n)for($x=+"$($n[0])";($y="$x"*$n.length)-lt$n;$x++){}+$y-$n

The usually-good-for-golf very loose casting of PowerShell is a major downfall here.

Takes input $n as a string, and enters a for loop. For the setup step, we extract out the first character $n[0], but have to convert it back to a string "$(...)" before casting as an int + and saving into $x. Otherwise, the later arithmetic will be using the ASCII value of the char-code.

The conditional checks whether a string constructed from $n.length "$x"s, temporarily stored in $y, is less-than $n. So long as it's not, we increment $x++, setting up the conditional for the next loop.

For example, for input 123, the value of $y when the conditional is first checked will be 111, which is less-than $n, so the loop continues. There's nothing in the loop body, so the step increment happens $x++, then the conditional is checked again. This time $y equals 222, which is greater than $n, so the loop terminates. If the input is already a repdigit, the conditional is not satisfied, because at that point $y is equal to $n.

Once out of the loop, we cast $y to an integer +, then subtract $n. That result is left on the pipeline and output is implicit.

AdmBorkBork

Posted 2016-08-24T06:25:33.790

Reputation: 41 581

1

PHP 5.6, 59 53 51 50 bytes

Saved 6 8 bytes thanks to @manatwork.

while(count_chars($argv[1]+$b,3)[1])$b++;echo$b?:0

Test with:

php test.php 11132

The count_chars() function with 3 as the second parameter returns a string with the distinct characters in a string. When this string is 1 character long ([1] will return false when it's length 1) then echo $b, otherwise increment $b and loop again.

Samsquanch

Posted 2016-08-24T06:25:33.790

Reputation: 271

1Cool use of count_chars(). What about 3 as $mode parameter? So this would be the while condition: count_chars($argv[1]+$b,3)[1]. – manatwork – 2016-08-24T16:08:55.670

That's really clever, thanks for the idea. I did try using 3 for the mode originally but couldn't think of a way to use it without count or strlen so it turned out to be the same length. – Samsquanch – 2016-08-24T16:23:14.340

1Oh, and without initializing $b: echo$b?:0; – manatwork – 2016-08-24T16:23:51.063

Ooo I forgot about the empty ternary. Good call! – Samsquanch – 2016-08-24T16:40:24.270

1

Matlab, 65 64 bytes

t=input('');i=0;while nnz(diff(+num2str(t+i)))
i=i+1;end
disp(i)

Because of the while loop it's rather slow...

Explanation

t=input('')  -- takes input
i=0          -- set counter to 0
while 
          num2str(t+i)   -- convert number to string 
         +               -- and then to array of corresponding ASCII codes
    diff(             )  -- produce vector of differences (all zeros for 'repdigit')
nnz(                   ) -- and count non-zero entries
i=i+1                    -- while not all digits are the same increase the counter
end          -- end while loop
disp(i)      -- print the counter

Saving one byte thanks to @Luis Mendo.

pajonk

Posted 2016-08-24T06:25:33.790

Reputation: 2 480

Do you really need that +0? diff automatically casts chars to numbers – Luis Mendo – 2016-08-25T00:39:22.907

In my version if I dont't add it, diff treats the string as sym and tries to differentiate. – pajonk – 2016-08-25T05:36:49.713

Then maybe move the plus to the front (as a unary operator) and remove the zero – Luis Mendo – 2016-08-25T09:10:54.853

1

Ruby, 42 characters

->n{i=0;n.next!&&i+=1while n.squeeze[1];i}

Expects string input.

Sample run:

irb(main):019:0> ->n{i=0;n.next!&&i+=1while n.squeeze[1];i}['87654321']
=> 1234567

Ruby, 39 characters

Recursive call, runs into “SystemStackError: stack level too deep” on bigger results.

r=->n,i=0{n.squeeze[1]?r[n.next,i+1]:i}

Sample run:

irb(main):001:0> r=->n,i=0{n.squeeze[1]?r[n.next,i+1]:i}
=> #<Proc:0x00000002367ca0@(irb):10 (lambda)>

irb(main):002:0> r['20000']
=> 2222

manatwork

Posted 2016-08-24T06:25:33.790

Reputation: 17 865

0

J, 39 bytes

f=.$:&>:`[@.(1=#@~.@(10&#.inv)@])
g=.0&f

Take the digits (10&#.inv)@], remove dups ~., check if the length is 1 (same basic idea as Dennis's solution). Recurse with incremented left and right args if it's not.

Note because $: recurses on the entire verb, we need to define a second verb to give the left arg an initial value of 0. I'd be curious to know how to avoid that, if possible.

Also, I'd be curious to know if there is a way to do this with ^: (do... while version).

Try it online!

Jonah

Posted 2016-08-24T06:25:33.790

Reputation: 8 729

0

TI-BASIC, 51 bytes

Ans→A:Ans→B:Repeat dim(Ans)=sum(Ans(1)=Ans:B+1→B:int(10fPart(B₁₀^(seq(⁻X-1,X,0,log(B:End:B-A

Slowly iterates through all integers greater than the input until the next repdigit has been reached.
Checks \$\approx20\$ numbers per second.

Input is the current reputation in Ans.
Output is the amount of rep required to reach the next repdigit.

Examples:

100
             100
prgmCDGF1D
              11
11132
           11132
prgmCDGF1D
           11090

Test case 11132 took \$\approx9.5\$ minutes to run.

Explanation:

Ans→A                                ;store the input into A and B
Ans→B
Repeat dim(Ans)=sum(Ans(1)=Ans       ;"do-while" the digits of B are not equal
B+1→B                                ;increment B
int(10fPart(B₁₀^(seq(⁻X-1,X,0,log(B  ;generate a list of B's digits reversed.  leave it in Ans
End
B-A                                  ;calculate the rep needed.  leave the result in Ans
                                     ;implicit print of Ans

Note: TI-BASIC is a tokenized language. Character count does not equal byte count.

Tau

Posted 2016-08-24T06:25:33.790

Reputation: 1 935

0

Forth (gforth), 54 bytes

: f 0 over s>f flog f>s 1+ 0 do 10 * 1- loop mod abs ;

Try it online!

Explanation

  • Gets the smallest repdigit of the same length as the input.
  • Negates the result and gets the remainder of dividing the input by that number.
  • Returns the absolute value of the result (since positive modulo negative is negative)

Code Explanation

: f                \ start a new word definition
  0 over           \ place 0 on stack and copy input back to top
  s>f flog f>s     \ move number to floating point stack, get log10, move back to stack (truncate)
  1+               \ add 1 to get number of digits
  0 do             \ start a loop from 0 to number of digits - 1
    10 * 1-        \ repeatedly multiply by 10 and subtract 1 to get smallest repdigit of that size
  loop             \ end loop
  mod abs          \ get that absolute value of input modulo result
;                  \ end the word definition

reffu

Posted 2016-08-24T06:25:33.790

Reputation: 1 361

0

Java, 59 bytes

int c(int i){return(i+"").matches("^(.)\\1*$")?0:c(i+1)+1;}

(I'm still not sure how to count Java entries, but according to the standard set by the first Java entry, this entry is 59 bytes, since it's 17 bytes shorter).

Anyway, if we have a repdigit, return 0, else add 1 to the input, call itself and add 1 to the result.


Ungolfed & test cases:

Try it here.

class Main{
  static int c(int i) {
    return
      (i+"").matches("^(.)\\1*$")
      ? 0
      : c(i+1) + 1;
  }

  public static void main(String[] a){
    System.out.println(c(8));
    System.out.println(c(100));
    System.out.println(c(113));
    System.out.println(c(42));
    System.out.println(c(20000));
    System.out.println(c(19122));
    // Entry below will run out of memory
    System.out.println(c(19121));
  }
}

Output:

Runtime error   time: 0.09 memory: 321152 signal:-1
0
11
109
2
2222
3100

As you can see, the last entry runs out of memory before it can finish. The (very appropriate) StackOverflowError is thrown from java.util.regex.Pattern.sequence(Pattern.java:2134), but I'm pretty confident there's nothing wrong with the regex itself, since it's the same one I used in my previous entry.

SQB

Posted 2016-08-24T06:25:33.790

Reputation: 681

0

C#, 82 bytes

using System.Linq;n=>{int i=n;while((i+"").Distinct().Count()!=1)++i;return i-n;};

TheLethalCoder

Posted 2016-08-24T06:25:33.790

Reputation: 6 930

0

C, 84 bytes

d,n,l,f;F(i){for(n=0;1;){l=i+n++;d=l%10;f=0;while(l/=10)f|=l%10-d;if(!f)return--n;}}

Test main:

int main() {
  printf("%d\n", F(8));
  printf("%d\n", F(100));
  printf("%d\n", F(113));
  printf("%d\n", F(87654321));
  printf("%d\n", F(47));
  printf("%d\n", F(20000));
  printf("%d\n", F(11132));
}

Stefano Sanfilippo

Posted 2016-08-24T06:25:33.790

Reputation: 1 059

0

Prolog, 120 bytes

r([H|T]):-r(H,[H|T]).
r(H,[H|T]):-r(H,T).
r(_,[]).
g(N,0):-number_chars(N,L),r(L).
g(N,X):-N1 is N+1,g(N1,X1),X is X1+1.

Try it online!

SQB

Posted 2016-08-24T06:25:33.790

Reputation: 681