# Generate lazy values

Related: Program my microwave oven. Inspired by Generate lazy microwave input.

The lazy value of the non-negative integer N is the smallest of the integers that are closest to N while all their digits are identical.

Return (by any means) the lazy value of a given (by any means) N.

Nthe largest integer that your language represents in non-exponent form by default. 1000000 (A lot of interesting solutions are lost because of this too-high requirement.)

## Test cases:

   0 →    0
8 →    8
9 →    9
10 →    9
16 →   11
17 →   22
27 →   22
28 →   33
100 →   99
105 →   99
106 →  111
610 →  555
611 →  666
7221 → 6666
7222 → 7777


The colleague in question proved that there will be no ties: Except for 9/11, 99/111, etc. for which one is shorter than the other, two consecutive valid answers are always an odd distance apart, so no integer can be exactly equidistant from them.

## JavaScript (ES6), 31 bytes

n=>~-(n*9+4).toPrecision(1)/9|0


Directly computes the lazy value for each n.

Edit: Only works up to 277777778 due to the limitations of JavaScript's integer type. Alternative versions:

n=>((n*9+4).toPrecision(1)-1)/9>>>0


35 bytes, works up to 16666666667.

n=>((n=(n*9+4).toPrecision(1))-n)/9


38 bytes, works up to 944444444444443. But that's still some way short of 253 which is 9007199254740992.

• @user81655 I've added some alternative versions with their numeric limitations.
– Neil
Feb 23, 2016 at 11:44
• I couldn't get this algorithm to work with Number.MAX_SAFE_INTEGER either because 8e16 - 1 is expressed as 8e16. Sadly, it looks like the only way would be hard-coding the maximum result. +1 nonetheless. Feb 23, 2016 at 11:54
• @user81655 I lowered the upper bound to allow the solution.
Feb 23, 2016 at 19:17
• Got you to 10k @Neil, love the golfs! Jun 8, 2016 at 2:39
• @NiCkNewman Woohoo! Thanks!
– Neil
Jun 8, 2016 at 7:36

# Jelly, 16 bytes

ḤRµDIASµÐḟµạ³ỤḢị


Try it online!

### How it works

ḤRµDIASµÐḟµạ³ỤḢị  Main link. Input: n

Ḥ                 Compute 2n.
R                Yield [1, ..., 2n] or .
µ               Begin a new, monadic chain. Argument: R (range)
D              Convert to base 10.
I             Compute all differences of consecutive decimal digits.
A            Take the absolute values of the differences.
S           Sum the absolute values.
µÐḟ        Filter-false by the chain to the left.
µ       Begin a new, monadic chain. Argument: L (lazy integers)
ạ³     Take the absolute difference of each lazy integer and n (input).
Ụ    Grade up; sort the indices of L by the absolute differences.
This is stable, so ties are broken by earlier occurrence and,
therefore, lower value.
Ḣ   Head; retrieve the first index, corresponding to the lowest
absolute difference.
ị  Retrieve the item of L at that index.


# Oracle SQL 11.2, 200 bytes

WITH v(i)AS(SELECT 0 FROM DUAL UNION ALL SELECT DECODE(SIGN(i),0,-1,-1,-i,-i-1)FROM v WHERE LENGTH(REGEXP_REPLACE(:1+i,'([0-9])\1+','\1'))>1)SELECT:1+MIN(i)KEEP(DENSE_RANK LAST ORDER BY rownum)FROM v;


Un-golfed

WITH v(i) AS
(
SELECT 0 FROM DUAL      -- Starts with 0
UNION ALL
SELECT DECODE(SIGN(i),0,-1,-1,-i,-i-1) -- Increments i, alternating between negatives and positives
FROM   v
WHERE  LENGTH(REGEXP_REPLACE(:1+i,'([0-9])\1+','\1'))>1  -- Stop when the numbers is composed of only one digit
)
SELECT :1+MIN(i)KEEP(DENSE_RANK LAST ORDER BY rownum) FROM v;


# Pyth - 26 bytes

This answer doesn't always return the smallest value in a tie, but that isn't in the specs, so awaiting clarification fixed for 3 bytes.

hSh.g.a-kQsmsM*RdjkUTtBlQ


# Pyth, 16 bytes

haDQsM*M*MTSlQ


Try it online: Demonstration or Test Suite

### Explanation:

haDQsM*M*MTSlQ   implicit: Q = input number
Q   convert Q to a string
l     take the length
S      create the list [1, 2, ..., len(str(Q))]
MT       create the list ["0", "1", "2", "3", ..., "9"]
*          create every combination of these two lists:
[[1, "0"], [1, "1"], [1, "2"], ..., [len(str(Q)), "9"]]
*M           repeat the second char of each pair according to the number:
["0", "1", "2", ..., "9...9"]
sM             convert each string to a number [0, 1, 2, ..., 9...9]
D                order these numbers by:
a Q                  their absolute difference with Q
h                  print the first one


# MATL, 25 bytes

2*:"@Vt!=?@]]N$vtG-|4#X<)  Uses brute force, so it may take a while for large numbers. Try it online! 2*: % range [1,2,...,2*N], where is input " % for each number in that range @V % push that number, convert to string t!= % test all pair-wise combinations of digits for equality ? % if they are all equal @ % push number: it's a valid candidate ] % end if ] % end for each N$v       % column array of all stack contents, that is, all candidate numbers
t         % duplicate
G-|       % absolute difference of each candidate with respect to input
4#X<      % arg min
)         % index into candidate array to obtain the minimizer. Implicitly display


# Perl, 32

Based on the beautiful JavaScript solution by Neil.

$_=0|1/9*~-sprintf"%.e",$_*9+4.1


Starts to fail at 5e15

# Mathematica, 122 bytes

f@x_:=Last@Sort[Flatten@Table[y*z,{y,1,9},{z,{FromDigits@Table[1,10~Log~x+1-Log[10,1055555]~Mod~1]}}],Abs[x-#]>Abs[x-#2]&]


Function named x.

# JavaScript (ES6), 59 bytes

n=>eval(for(i=a=0;i<=n;a=i%10?a:++i)p=i,i+=a;n-p>i-n?i:p)


### Recursive Solution (56 bytes)

This is a bit shorter but does not work for n > 1111111110 because the maximum call stack size is exceeded, so it is technically invalid.

f=(n,p,a,i=0)=>n<i?n-p>i-n?i:p:f(n,i,(i-=~a)%10?a:i++,i)


## Explanation

Iterates through every lazy number until it gets to the first which is greater than n, then compares n to this and the previous number to determine the result.

var solution =

n=>
eval(           // eval enables for loop without {} or return
for(
i=a=0;       // initialise i and a to 0
i<=n;        // loop until i > n, '<=' saves having to declare p above
a=i%10?a:++i // a = amount to increment i each iteration, if i % 10 == 0 (eg.
)              //     99 + 11 = 110), increment i and set a to i (both become 111)
p=i,         // set p before incrementing i
i+=a;        // add the increment amount to i
n-p>i-n?i:p    // return the closer value of i or p
)
N = <input type="number" oninput="R.textContent=solution(+this.value)"><pre id="R"></pre>

• I lowered the upper bound to allow your solution.
Feb 23, 2016 at 19:17

# Japt, 18 bytes

9*U+4 rApUs l¹/9|0


Try it online!

Based on Neil's technique

Non-competing solution:

*9+4 h /9|0

• And now you can do *9+4 h /9|0 :-) Jan 13, 2017 at 0:12
• @ETHproductions Thanks! I'm having a lot of fun with Japt :) Jan 13, 2017 at 0:22

# 05AB1E, 20 bytes

9Ývy7L×})˜ïD¹-ÄWQÏ{¬


Try it online!

9Ý                   # Push 0..9
vy7L×})˜           # For each digit, 0-9, push 1-7 copies of that number.
ïD         # Convert to integers, dupe the list.
¹        # Push original input (n).
-Ä      # Push absolute differences.
WQ    # Get min, push 1 for min indices.
Ï{¬ # Push indices from original array that are the min, sort, take first.

• 99 is surely more lazy than 111, as it only requires two button presses.
Jan 12, 2017 at 16:02

## Mathematica, 56 bytes

Min@Nearest[##&@@@Table[d(10^n-1)/9,{n,0,6},{d,0,9}],#]&


Pure function with first argument #, works for inputs up to 10^6.

For a nonnegative integer n and a digit d, 10^n-1 = 99...9 (9 repeated n times), so d(10^n-1)/9 = dd...d (d repeated n times). Creates a Table of values for 0 <= n <= 6 and 0 <= d <= 9, then flattens the table, finds the list of elements Nearest to # and takes the Min.

I believe this version will work for arbitrarily large integers:

Min@Nearest[##&@@@Table[d(10^n-1)/9,{n,0,IntegerLength@#},{d,0,9}],#]&
`