Round Me, Help Me


23

Dato un input n, il tuo programma o funzione deve generare il numero intero positivo più piccolo in modo ktale che narrotondato al multiplo più vicino di ksia maggiore di n.

Esempio.

Dato un input 20, il valore di output dovrebbe essere 3:

  • Il multiplo più vicino di 1è 20, che non è maggiore di 20.

  • Il multiplo più vicino di 2è 20, che non è maggiore di 20.

  • Il multiplo più vicino di 3è 21, che è maggiore di 20, quindi viene emesso.

Casi test

#Input  #Output
2       3
4       5
6       4
8       3
10      4
12      7
14      3
16      6
18      4
20      3
22      4
24      5
26      3
28      5
30      4
32      3
34      4
36      8
38      3
40      6
42      4
44      3
46      4
48      5
50      3
52      6
54      4
56      3
58      4
60      7
62      3
64      5
66      4
68      3
70      4
72      11
74      3
76      6
78      4
80      3
82      4
84      5
86      3
88      5
90      4
92      3
94      4
96      7
98      3
1000    6

L'output dato qualsiasi input dispari dovrebbe essere 2.

Regole

  • n è un numero intero positivo inferiore a 2^32
  • l'arrotondamento viene eseguito in modo tale che se due multipli di ksono ugualmente distanti da n, viene scelto quello più grande ( "metà arrotondata verso l'alto" ). In questo modo, ogni dispari nproduce un output di 2.
  • Questo è , quindi vince il codice più corto in ogni lingua .

Ho modificato il formato dei casi di test per renderlo più facile da leggere e più conciso. Fammi sapere se hai problemi con questo, o se qualcuno dei nuovi esempi è spento. :)
DJMcMayhem

@Shaggy Done! Ho rimosso 500 probabilità e 450 pari dall'elenco.
fireflame241

Esiste un link oeis per questa sequenza?
James K,

@JamesK Non ne ho trovato uno quando ho cercato prima. Forse qualcuno con un account OEIS potrebbe crearne uno?
fireflame241

Risposte:



9

Japt , 6 byte

@<rX}a

Provalo online!

Spiegazione:

@    <r X}a
XYZ{U<UrX}a
X              // X = 0; Increments when the condition in between {...} fails
   {     }a    // Return the first integer X where:
    U          //   The input
     <U        //   is less than the input
       rX      //     rounded to the nearest multiple of X

2
rè un builtin? o_o
Erik the Outgolfer

@EriktheOutgolfer: Japt ha anche dei built-in per arrotondare su o giù :)
Shaggy

5
Ho saputo che questa funzione sarebbe venuto in aiuto un giorno: D
ETHproductions

@Shaggy che è fuori di testa! o_o_o
Erik the Outgolfer

@Oliver: questo mi ha più convinto a fare i conti con i metodi di funzione, ora - la mia versione di questo era di 7 byte:o æ@<rX
Shaggy

7

MATL , 13 byte

tQ:yy/Yo*<fX<

Provalo online! Oppure verifica tutti gli input da 1a1000 .

Spiegazione

Considera l'input 6.

t      % Implicit input. Duplicate
       % STACK: 6, 6
Q:     % Add 1, range
       % STACK: 6, [1 2 3 4 5 6 7]
yy     % Duplicate top two elements
       % STACK: 6, [1 2 3 4 5 6 7], 6, [1 2 3 4 5 6 7]
/      % Divide, element-wise
       % STACK: 6, [1 2 3 4 5 6 7], [6 3 2 1.5 1.2 1 0.8571]
Yo     % Round to closest integer. Halves are rounded up
       % STACK: 6, [1 2 3 4 5 6 7], [6 3 2 2 1 1 1]
*      % Multiply, element-wise
       % STACK: 6, [6 6 6 8 5 6 7]
<      % Less than, element-wise
       % STACK: [0 0 0 1 0 0 1]
f      % Find: indices of nonzeros (1-based)
       % STACK: [4 7]
X<     % Minimum of vector. Implicit display
       % STACK: 4


5

JavaScript (ES6), 28 25 byte

n=>g=x=>n%x>=x/2?x:g(-~x)
  • 3 byte salvati grazie ad Arnauld.

Provalo

o.innerText=(f=

n=>g=x=>n%x>=x/2?x:g(-~x)

)(i.value=64)();oninput=_=>o.innerText=f(+i.value)()
<input id=i type=number><pre id=o>

Oppure prova tutti i numeri da 1-1000 (Concedi un minuto per l'esecuzione):


5

Proton , 33 byte

n=>[x for x:2..n+2if n%x>=x/2][0]

Provalo online!


Non so nulla di Proton, ma sembra che tu possa risparmiare 3 byte: provalo online!
jferard,

Forse una coincidenza, ma è esattamente la stessa della soluzione totalmente umana ...: p
Erik the Outgolfer

@EriktheOutgolfer L'abbiamo pubblicato contemporaneamente (in effetti l'ho ninja di qualche secondo) con 37 byter, perché Hyper ha eliminato gli operatori e quando li ha riparati ci siamo aggiornati entrambi.
Mr. Xcoder,

Uh, ti ho fatto diventare IIRC. : P
totalmente umano il

@totallyhuman Mi hai fatto ninja con un 41-byter. Ho pubblicato prima il 37-byter e te l'ho ninja con quello di pochi secondi.
Mr. Xcoder,



3

Gelatina , 11 byte

÷R%1<.¬;1TṂ

Un collegamento monadico che prende e restituisce numeri interi positivi.

Provalo online! o vedere una suite di test .

Come?

÷R%1<.¬;1TṂ - Link: number, n       e.g. 10
 R          - range(n)               [ 1,2,3     ,4  ,5,6     ,7     ,8   ,9     ,10]
÷           - n divided by           [10,5,3.33..,2.5,2,1.66..,1.42..,1.25,1.11..,1 ]
  %1        - modulo by 1            [ 0,0,0.33..,0.5,0,0.66..,0.42..,0.25,0.11..,0 ]
    <.      - less than 0.5?         [ 1,1,1     ,0  ,1,0     ,1     ,1   ,1     ,1 ]
      ¬     - not                    [ 0,0,0     ,1  ,0,1     ,0     ,0   ,0     ,0 ]
       ;1   - concatenate a 1        [ 0,0,0     ,1  ,0,1     ,0     ,0   ,0     ,0 , 1]
         T  - truthy indices         [            4    ,6                           ,11]
          Ṃ - minimum                4

Nota: La concatenazione di 1è solo per gestire i casi in cui nè uno dei 1, 2o 4quando il risultato deve essere n+1( ‘R÷@%1<.¬TṂsarebbe anche di lavoro).




2

Pyth, 5 byte

fgy%Q

Suite di test

Nessun builtin di arrotondamento, solo verificando il primo intero positivo T, dove il doppio dell'ingresso mod T è maggiore o uguale a T.

Spiegazione:

fgy%Q
fgy%QTT    Implicit variable introduction.
f          Find the first positive integer T such that the following is truthy:
   %QT     Input % T
  y        Doubled
 g    T    Is greater than or equal to T

2

Codice macchina x86, 17 byte

Questo codice implementa una soluzione iterativa di base sotto forma di una funzione riutilizzabile:

31 F6                   xor    esi, esi
46                      inc    esi         ; set ESI (our temp register) to 1

                     Loop:
89 C8                   mov    eax, ecx    ; copy 'n' to EAX for division
46                      inc    esi         ; eagerly increment temp
99                      cdq                ; extend EAX into EDX:EAX
F7 F6                   div    esi         ; divide EDX:EAX by ESI
01 D2                   add    edx, edx    ; multiply remainder by 2
39 F2                   cmp    edx, esi    ; compare remainder*2 to temp
7C F4                   jb     Loop        ; keep looping if remainder*2 < temp

96                      xchg   eax, esi    ; put result into EAX (1 byte shorter than MOV)
C3                      ret

La funzione segue la convenzione di chiamata di chiamata rapida , in modo che il singolo parametro ( n) venga passato nel ECXregistro. Il valore restituito ( k) viene, come al solito, restituito nel EAXregistro.

Provalo online!


2

Java 8, 42 byte

Lambda da Integera Integer.

n->{for(int f=1;;)if(n%++f*2>=f)return f;}

Provalo online

Ringraziamenti

  • -1 byte grazie a Kevin Cruijssen

4
È possibile salvare un byte avviando f=1e utilizzando ++fil primo f, in questo modo:n->{for(int f=1;;)if(n%++f*2>=f)return f;}
Kevin Cruijssen,

1

Perl 5 , 24 + 1 (-p) = 25 byte

1while$_%++$k<$k/2;$_=$k

Provalo online!

Prova ogni numero intero a $kpartire da 1 finché non trova un resto che è almeno la metà di $k.


1

Forth (gforth) , 45 byte

: f 1 begin 1+ 2dup mod over 1+ 2/ >= until ;

Provalo online!

Spiegazione del codice

: f             \ start a new word definition
  1             \ start a counter at 1
  begin         \ start an indefinite loop
    1+          \ add 1 to counter
    2dup mod    \ duplicate input value and counter, get remainder of input/counter
    over 1+ 2/  \ get counter/2 (add 1 to force rounding up)
    >=          \ check if remainder is greater than counter/2
  until         \ end loop if true, otherwise go back to beginning
;               \ end word definition

1

05AB1E , 9 byte

∞.ΔIs/Dò‹

Provalo online!

Spiegazione

∞.ΔIs/Dò‹ Full code
∞.Δ       Returns the first number for which the following code returns true
             -> stack is [n]
   Is     Push the input and swap the stack -> stack is [input, n]
     /    Divide both of them -> stack is [input/n]
      Dò  Duplicate and round the second -> stack is [input/n, rounded(input/n)]
        ‹ Check if input/n got larger by rounding -> stack is [bool]
             -> if bool is true, abort and return the current number

1

Rockstar , 681 byte

Thought takes Patience and Control
While Patience is as high as Control
Let Patience be without Control

Give back Patience

Rock takes Art
Love is neverending
Sex is bottomless
Put Thought taking Art & Love into your head
If your head is Sex
Give back Art
Else
Limits are inspiration
Put Art with Limits without your head into the rubbish
Give back the rubbish


Listen to Chance
Questions are unstoppable
Until Questions is Chance
Build Questions up
Put Thought taking Chance, Questions into your mind
Answers are independence (but)
Put Questions over Answers into the world
Put Rock taking the world into the world
If your mind is as big as the world
Say Questions
Break it down

Puoi provare rockstar online , ma dovrai copiare e incollare il codice. Ti verrà richiesto un numero di input.

Non ho optato per il conteggio di byte più basso, perché Rockstar ovviamente non è fatto per il golf, quindi ho cercato di scegliere il testo di Rock 'n' Roll.

Spiegazione:

Questo si basa sulla stessa soluzione di altri (python, java):

Iterate up from 2:
if n % iterator >= ceil(n/2)
    return iterator

Per prima cosa devo definire le funzioni del modulo e del soffitto, che per amor di poesia sono chiamate Pensiero e Roccia.

Quella che segue è una versione meno poetica con nomi di variabili differenti e spiegazioni in cui la sintassi non è chiara. Le parentesi indicano commenti.

Modulus takes Number and Divisor
While Number is as high as Divisor
Put Number minus Divisor into Number
    (blank line ending While block)
Give back Number (return Number)
    (blank line ending function declaration)
Ceil takes Decimal
Put Modulus taking Decimal, 1 into Remainder
If Remainder is 0
Give back Decimal (return Decimal)
Else
Put Decimal with 1 minus Remainder into Result
Give back Result (return Result)
    (blank line ending if block)
    (blank line ending function declaration)
Listen to Input (Read from STDIN to Input)
Index is 1
Until Index is Input
Build Index up (Increment by 1)
Put Modulus taking Input, Index into LHS
Put Index over 2 into RHS
Put Ceil taking RHS into RHS
If LHS is as big as RHS
Say Index
Break it down (Break from loop)


0

Swift 3 , 51 byte

{n in(2..<n+2).filter{Float(n%$0)>=Float($0)/2}[0]}

Per alcuni motivi estremamente bizzarri, [0]non funziona online. Ecco la versione compatibile con il compilatore online (che utilizza .first!invece):

{n in(2..<n+2).filter{Float(n%$0)>=Float($0)/2}.first!}

Test Suite (compatibile online).



Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.