Generieren Sie faule Werte


25

Verwandte: Programmieren Sie meine Mikrowelle . Inspiriert von Faulen Mikrowelleneingang erzeugen .

Der Lazy-Wert der nicht-negativen Ganzzahl N ist die kleinste der Ganzzahlen, die N am nächsten sind, während alle ihre Ziffern identisch sind.

Geben Sie (mit allen Mitteln) den Lazy-Wert eines gegebenen (mit allen Mitteln) N zurück .

Ndie größte Ganzzahl, die Ihre Sprache standardmäßig in Nicht-Exponenten-Form darstellt. 1000000 (Durch diese zu hohe Anforderung gehen viele interessante Lösungen verloren.)

Testfälle:

   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 

Der fragliche Kollege hat bewiesen, dass es keine Bindungen geben wird: Abgesehen von 9/11, 99/111 usw., für die eine kürzer als die andere ist, sind zwei aufeinanderfolgende gültige Antworten immer ungerade voneinander entfernt, sodass keine ganze Zahl genau sein kann gleich weit von ihnen entfernt.

Antworten:


15

JavaScript (ES6), 31 Byte

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

Berechnet direkt den Lazy-Wert für jeden n.

Bearbeiten: Funktioniert aufgrund der Einschränkungen des Integer-Typs von JavaScript nur bis 277777778. Alternative Versionen:

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

35 Bytes, arbeitet bis zu 16666666667.

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

38 Bytes, arbeitet bis zu 944444444444443. Aber das ist immer noch viel zu wenig als 2 53, das ist 9007199254740992.


@ user81655 Ich habe einige alternative Versionen mit ihren numerischen Einschränkungen hinzugefügt.
Neil

1
Ich konnte diesen Algorithmus auch nicht zum Number.MAX_SAFE_INTEGERLaufen bringen, weil er 8e16 - 1als ausgedrückt wird 8e16. Leider sieht es so aus, als ob der einzige Weg darin besteht, das maximale Ergebnis hart zu codieren. +1 trotzdem.
user81655

@ user81655 Ich habe die Obergrenze gesenkt, um die Lösung zu ermöglichen.
Adám

Hast du 10k @Neil, liebe die Golfplätze!
NiCk Newman

1
@NiCkNewman Woohoo! Vielen Dank!
Neil

5

Gelee, 16 Bytes

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

Probieren Sie es online!

Wie es funktioniert

Ḥ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.

4

Oracle SQL 11.2, 200 Byte

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;

Nicht golfen

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;

3

Pyth - 26 Bytes

Diese Antwort gibt nicht immer den kleinsten Wert in einem Unentschieden zurück, aber das ist nicht in den Spezifikationen, so dass auf eine Klärung von 3 Bytes gewartet wird.

hSh.g.a-kQsmsM*RdjkUTtBl`Q

Test Suite .


3

Pyth, 16 Bytes

haDQsM*M*`MTSl`Q

Probieren Sie es online aus: Demo oder Test Suite

Erläuterung:

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

3

MATL , 25 Bytes

2*:"@Vt!=?@]]N$vtG-|4#X<)

Wendet rohe Gewalt an, daher kann es bei großen Zahlen eine Weile dauern.

Probieren Sie es 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

3

Perl, 32

Basierend auf der schönen JavaScript-Lösung von Neil.

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

Fängt an zu scheitern 5e15


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]&]

Funktion mit dem Namen x.


2

JavaScript (ES6), 59 Byte

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

Rekursive Lösung (56 Bytes)

Dies ist ein bisschen kürzer, funktioniert aber nicht, n > 1111111110da die maximale Call-Stack-Größe überschritten wird und daher technisch ungültig ist.

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

Erläuterung

Durchläuft jede faule Zahl, bis die erste erreicht ist, die größer als ist n, und vergleicht nsie dann mit dieser und der vorherigen Zahl, um das Ergebnis zu bestimmen.

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>


Ich habe die Obergrenze gesenkt, um Ihre Lösung zu ermöglichen.
Adám


1

05AB1E , 20 Bytes

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

Probieren Sie es 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 ist sicherlich fauler als 111, da nur zwei Tastendrücke erforderlich sind.
Adám

@Adám fair genug, fügte head command hinzu.
Magic Octopus Urn

1

Mathematica, 56 Bytes

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

Reine Funktion mit erstem Argument #, funktioniert für Eingaben bis 10^6.

Für eine nicht - negative ganze Zahl ist, nund eine Ziffer d, 10^n-1 = 99...9( 9wiederholt nmal), so d(10^n-1)/9 = dd...d( dwiederholtes nMal). Erstellt eine Tablevon Werten für 0 <= n <= 6und 0 <= d <= 9dann die Tabelle abflacht, findet die Liste der Elemente Nearestzu #und nimmt die Min.

Ich glaube, diese Version wird für beliebig große ganze Zahlen funktionieren:

Min@Nearest[##&@@@Table[d(10^n-1)/9,{n,0,IntegerLength@#},{d,0,9}],#]&
Durch die Nutzung unserer Website bestätigen Sie, dass Sie unsere Cookie-Richtlinie und Datenschutzrichtlinie gelesen und verstanden haben.
Licensed under cc by-sa 3.0 with attribution required.