В честь того, сколько повторений у меня было несколько часов назад, когда я впервые подумал об этом вызове:
Подобные числа, состоящие из повторяющихся однозначных чисел, называются репигитами . Repdigits это весело! Каждое тело было бы более счастливым , если сумма повторении они имели , было репдигиты ¹ , но я нетерпелив, так что вам нужно , чтобы помочь мне выяснить , самый быстрый способ добраться до репдигитов.
Вот ваш вызов:
С учетом положительных целых чисел, представляющих репутацию, выведите минимальное количество повторений, которое они должны получить, чтобы получить репутацию. Например, на момент написания этого задания у пользователя Мартина Эндера было 102 856 респ. Ближайшая цифра повторения - 111 111, поэтому ему нужно набрать 8255 повторений, чтобы быть на повторной цифре.
Поскольку людям не нравится терять репутацию, мы будем рассматривать только неотрицательные изменения. Это означает, что, например, если кто-то находится на 12 повторениях, а не теряет 1 повтор, решение состоит в том, чтобы получить 10 повторений. Это позволяет '0' быть допустимым выводом, так как любой, у кого есть 111 повторений, уже находится в повторном представлении.
Ввод и вывод могут быть в любом приемлемом формате , и поскольку на любом сайте Stack Exchange невозможно иметь менее 1 повторения, можно предположить, что входные данные не будут меньше 1.
Один уголок для заметки:
Если у пользователя менее 10 повторений, он уже набрал повторную цифру, и поэтому ему также нужно «0».
Тест IO:
#Input #Ouput
8 0
100 11
113 109
87654321 1234567
42 2
20000 2222
11132 11090
Применяются стандартные лазейки, и выигрывает самое короткое решение в байтах!
110
следует дать1
, хотя нет способа получить один повтор.Ответы:
Желе , 6 байт
Выход - одноэлементный массив.
Попробуйте онлайн! или проверьте большинство тестовых случаев . Тестовый случай 87654321 слишком медленный для TIO.
Как это работает
источник
Haskell, 39 bytes
Try it online
источник
Brachylog, 9 bytes
Try it online!
This is pretty efficent as it makes use of constraints arithmetic.
Explanation
источник
This is the answer you're looking for. Figure it out for me
:)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?Python 2,
4140 bytesNot 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.
источник
lambda n:10**len(`n`)/9*-~int(`n*9`[0])-n
. It almost works to dolambda 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.O(1)
.O(1)
, but I guess it makes sense.Python 2, 37 bytes
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.источник
L
on longs needs to be handled.-~
allows the function to count the number of calls it made.Perl 6, 23 bytes
A lambda that takes the input number as argument, and returns the result.
Explanation:
...
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).источник
/(.)$0*/
Java 7,
11676 bytesUsed @Dennis' amazing approach to lower the byte-count by a whopping 40 bytes.
Ungolfed & test cases:
Try it here.
Output:
источник
2222
and the fourth output be12345678
?2222
instead of222
. 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 be123467
(as you can also see at OP's question).Pyth,
987 bytes1 byte thanks to @FryAmTheEggman.
Try it online.
Very inefficient, loops through all numbers from the input to the next repdigit.
источник
Brain-Flak
690358 bytesHere'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
источник
Python 2, 52 bytes
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:
You may also try it online!
источник
GNU sed, 223 + 1(r flag) = 224 bytes
Run:
Output:
This is a pure sed solution, the arithmetic is simulated using regular expressions only. The algorithm works as follows:
^current_reputation:needed_reputation%$
a)
%:
applies the increment to needed_reputationb)
:%
applies the increment to current_reputationисточник
Java,
7472 bytes(If the other Java entry is 76 bytes, this one is
7472, since it'stwofour 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:
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.
}
Output:
источник
R,
1029891 bytesUngolfed :
Messing around with the format (
) adds some bytes, but R is not really flexible !as.numeric
andas.character
источник
Perl, 40 + 1 (
-n
) = 41 bytesIf printing nothing instead of
0
when the number is already a repdigit is acceptable, then 37 bytes are enough :Run with
-n
(1 byte) and-E
or-M5.010
(free) :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.источник
perl -pe '@x=sort/./g;//;$_=(($x[-1]>$&)+$&)x+@x-$_'
JavaScript (ES6), 42 bytes
Explanation: Recursively computes
p
as the next power of10
aftern
. The digit to be repeated is then computed as1+floor(9n/p)
, and the repunit is simply(p-1)/9
, from which the result follows.источник
05AB1E,
106 bytesTry it online!
Explanation
источник
§
and change¹-
toα
. And here a rather similar 8-byte alternative:∞+.ΔÙg}α
Pyke,
1311 bytesTry it here!
источник
Actually, 15 bytes
Try it online!
Explanation:
источник
Jellyfish, 20 bytes
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.&
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 gives1
for an empty string, and0
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
.<
decrements it. Finally,p
prints the result.источник
PowerShell v2+, 66 bytes
The usually-good-for-golf very loose casting of PowerShell is a major downfall here.
Takes input
$n
as a string, and enters afor
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 be111
, 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
equals222
, 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.источник
PHP 5.6,
59535150 bytesSaved
68 bytes thanks to @manatwork.Test with:
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.источник
count_chars()
. What about 3 as $mode parameter? So this would be thewhile
condition:count_chars($argv[1]+$b,3)[1]
.count
orstrlen
so it turned out to be the same length.echo$b?:0;
MATL, 10 bytes
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.источник
Ruby, 42 characters
Expects string input.
Sample run:
Ruby, 39 characters
Recursive call, runs into “SystemStackError: stack level too deep” on bigger results.
Sample run:
источник
Matlab,
6564 bytesBecause of the while loop it's rather slow...
Explanation
Saving one byte thanks to @Luis Mendo.
источник
+0
?diff
automatically casts chars to numbersdiff
treats the string as sym and tries to differentiate.Excel,
8579 bytesPut the following formula in any cell except cell
N
since it's a name for reference cell of input: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 valueLEN(N)
times and multiply it by 1 to convert text format to number format so we can use it for number comparison.источник
Num_chars
inLEFT
and save 4 bytes:LEFT(N)
IF
condition into a1
or0
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
=REPT(LEFT(N)+(1*(REPT(LEFT(N),LEN(N)))<N),LEN(N))-N
, saving 27 bytes to give a total of 52.Brachylog v2, 6 bytes
Try it online!
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.источник
Java, 59 bytes
(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.
Output:
As you can see, the last entry runs out of memory before it can finish. The (very appropriate)
StackOverflowError
is thrown fromjava.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.источник
C#, 82 bytes
источник
C, 84 bytes
Test main:
источник
Prolog, 120 bytes
Try it online!
источник