Generate lazy values

25

1

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.

Adám

Posted 2016-02-23T02:49:54.770

Reputation: 37 779

Answers

15

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[0])/9

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

Neil

Posted 2016-02-23T02:49:54.770

Reputation: 95 035

@user81655 I've added some alternative versions with their numeric limitations. – Neil – 2016-02-23T11:44:53.727

1I 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. – user81655 – 2016-02-23T11:54:41.137

@user81655 I lowered the upper bound to allow the solution. – Adám – 2016-02-23T19:17:24.547

Got you to 10k @Neil, love the golfs! – NiCk Newman – 2016-06-08T02:39:56.163

1@NiCkNewman Woohoo! Thanks! – Neil – 2016-06-08T07:36:22.280

Could you explain this for those of us unfamiliar with Javascript? – ngenisis – 2017-01-13T01:25:06.160

@ngenisis Because lazy values are of the form k((10^n)-1)/9, multiplying the original number by 9 should give you a number near to k10^n. Adding 4 and calling toPrecision achieves the necessary rounding. It then remains to regenerate the lazy value given k*10^n. – Neil – 2017-01-13T09:05:42.827

5

Jelly, 16 bytes

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

Try it online!

How it works

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

Ḥ                 Compute 2n.
 R                Yield [1, ..., 2n] or [0].
  µ               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.

Dennis

Posted 2016-02-23T02:49:54.770

Reputation: 196 637

4

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;

Jeto

Posted 2016-02-23T02:49:54.770

Reputation: 1 601

3

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*RdjkUTtBl`Q

Test Suite.

Maltysen

Posted 2016-02-23T02:49:54.770

Reputation: 25 023

3

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

Luis Mendo

Posted 2016-02-23T02:49:54.770

Reputation: 87 464

3

Pyth, 16 bytes

haDQsM*M*`MTSl`Q

Try it online: Demonstration or Test Suite

Explanation:

haDQsM*M*`MTSl`Q   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

Jakube

Posted 2016-02-23T02:49:54.770

Reputation: 21 462

3

Perl, 32

Based on the beautiful JavaScript solution by Neil.

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

Starts to fail at 5e15

Ton Hospel

Posted 2016-02-23T02:49:54.770

Reputation: 14 114

2

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

Oliver

Posted 2016-02-23T02:49:54.770

Reputation: 7 160

1And now you can do *9+4 h /9|0 :-) – ETHproductions – 2017-01-13T00:12:29.253

@ETHproductions Thanks! I'm having a lot of fun with Japt :) – Oliver – 2017-01-13T00:22:20.453

2

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.

CalculatorFeline

Posted 2016-02-23T02:49:54.770

Reputation: 2 608

2

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>

user81655

Posted 2016-02-23T02:49:54.770

Reputation: 10 181

I lowered the upper bound to allow your solution. – Adám – 2016-02-23T19:17:13.047

1

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.

Magic Octopus Urn

Posted 2016-02-23T02:49:54.770

Reputation: 19 422

99 is surely more lazy than 111, as it only requires two button presses. – Adám – 2017-01-12T16:02:35.310

@Adám fair enough, added head command. – Magic Octopus Urn – 2017-01-12T16:04:53.660

1

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}],#]&

ngenisis

Posted 2016-02-23T02:49:54.770

Reputation: 4 600