Dividi come numero, unisci come stringa, ripeti


14

Considera il processo di:

  1. Prendendo un numero intero non negativo N.
    es 27.

  2. Dividendolo in numeri interi N - floor(N/2)e floor(N/2)(una metà "più grande" e "più piccola") e scrivendoli in quell'ordine.
    ad esempio 27diventa 14 13.

  3. Rimozione dello spazio per unire gli interi in un nuovo intero molto più grande.
    ad esempio 14 13diventa 1413.

  4. Ripetendo i passaggi 2 e 3 il numero desiderato di volte.
    ad es. 1413707 706707706353853 353853353853353853→ ...

Questa sfida consiste nel fare esattamente questo, ma non sempre nella base 10.

Sfida

Scrivi un programma che comprende tre numeri, B, N e S:

  • B è un numero intero compreso tra 2 e 10 che è la base di N (da binario a decimale).

  • N è il numero intero non negativo a cui applicare il processo di divisione-ricongiungimento. Per facilitare l'input dell'utente, viene fornito come una stringa nella base B, non come un numero intero.

  • S è un numero intero non negativo che è il numero di volte in cui ripetere il processo di divisione-ricongiungimento.

L'output del programma è la rappresentazione in forma di stringa di N nella base B dopo S procedure di split-join.

Quando S lo è 0, non viene eseguita alcuna divisione, quindi l'output è sempre N.

Quando N è 0, tutte le divisioni hanno la forma 0 0e si riducono di 0nuovo, quindi l'output è sempre 0.

Esempi

  • B = 10, N = 27, S = 11413
  • B = 10, N = 27, S = 2707706
  • B = 9, N = 27, S = 11413
  • B = 9, N = 27, S = 2652651
  • B = anything, N = anything, S = 0N
  • B = anything, N = 0, S = anything0

Tabella per tutti B con N = 1per S = 0a 7:

B       S=0     S=1     S=2     S=3         S=4             S=5                 S=6                                 S=7
2       1       10      11      101         1110            111111              10000011111                         10000100001000001111
3       1       10      21      1110        202201          101101101100        1201201201212012012011              212100212102121002121212100212102121002120
4       1       10      22      1111        223222          111311111311        2232222232322322222322              11131111131311311111311113111113131131111131
5       1       10      32      1413        432431          213441213440        104220331443104220331442            2433241322130211014044424332413221302110140443
6       1       10      33      1514        535535          245550245545        122553122553122553122552            4125434125434125434125441254341254341254341254
7       1       10      43      2221        11111110        40404044040403      2020202202020220202022020201        10101011010101101010110101011010101101010110101011010100
8       1       10      44      2222        11111111        44444454444444      2222222622222222222226222222        11111113111111111111131111111111111311111111111113111111
9       1       10      54      2726        13581357        62851746285173      3142536758708231425367587081        15212633743485606571782880411521263374348560657178288040
10      1       10      55      2827        14141413        70707077070706      3535353853535335353538535353        17676769267676676767692676771767676926767667676769267676

Tabella per tutte le B con N casuale per S = 0a 3:

B       S=0     S=1         S=2                 S=3
2       11011   11101101    11101111110110      11101111110111110111111011
3       2210    11021101    20102012010200      1001212100121210012121001211
4       1113    230223      112112112111        2302302302323023023022
5       101     2323        11341134            31430423143042
6       120     4040        20202020            1010101010101010
7       134     5252        24612461            1230456412304564
8       22      1111        445444              222622222622
9       4       22          1111                505505
10      92      4646        23232323            1161616211616161

Dettagli

  • Prendi input tramite stdin o dalla riga di comando. Uscita su stdout.
  • Invece di un programma, è possibile scrivere una funzione che accetta B, N e S e stampa il risultato normalmente o lo restituisce (come una stringa).
  • B, N e S possono essere presi in qualsiasi ordine.
  • Tutti gli input che producono output i cui valori decimali sono inferiori a 2 32 dovrebbero funzionare.
  • N è rappresentato nel solito modo. cioè la cifra più significativa per prima e nessuno zero iniziale tranne lo zero stesso che è scritto 0. (L'output 00invece di 0non è valido.)
  • Vince il codice più breve in byte.

Se ti piacciono le mie sfide, prendi in considerazione di dare Block Building Bot Flocks! un po 'di amore :)


Non so se una classifica per le risposte sia davvero necessaria.
orlp

5
@orlp Probabilmente no. Lo rimuoverò e lo rimetterò se ci sono un sacco di risposte. Volevo solo sfoggiare i miei shenanigans con frammenti di stack ottimizzatori .
Calvin's Hobbies,

Risposte:


5

Pyth, 21 19 byte

vujksmjldQc2UiGQvwz

Accetta input nel formato N\nB\nS. Provalo online: cablaggio dimostrativo o di prova

Spiegazione

                      implicit: z = 1st input (N)
                                Q = 2nd input evaluated (B)
 u              vwz   reduce z (evaluated 3rd input) times by:
             iGQ         convert string from base Q to base 10
            U            create a range [0, 1, ..., ^-1]
          c2             split into 2 lists (lengths are N-[N/2] and [N/2])
     m                   map each list d to:
       ld                   their length
      j  Q                  in base Q
    s                    join both lists
  jk                     join the numbers by ""
v                     convert string to int (getting rid of leading zeros)

5

Pyth, 29 21 byte

jku+j-JiGQK/J2QjKQvwz

Implementazione davvero semplice.

Accetta input su stdin nel seguente formato:

N
B
S

Questo dà un output sbagliato 00per N=0.
Jakube,

5

Mathematica, 101 byte

Nest[a~Function~(b=FromDigits)[Through@((c=IntegerString)@*Ceiling<>c@*Floor)[a/2],#],#2~b~#,#3]~c~#&

Usa alcuni Throughtrucchi per applicare le funzioni del soffitto e del pavimento. Ignora gli errori.


5

CJam, 24 byte

q~:B;{:~Bb_)\]2f/Bfbs}*i

Provalo qui. Accetta input come "N" S B.

Spiegazione

q~                       e# Read an eval input.
  :B;                    e# Store the base in B and discard it.
     {               }*  e# Repeat S times.
      :~                 e# Turn the string N into an array of digits.
        Bb               e# Interpret as base B.
          _)\            e# Duplicate and increment. Swap order.
             ]2f/        e# Wrap them in an array and (integer-)divide both by 2.
                 Bfb     e# Convert both to base B.
                    s    e# Flatten into a single string.
                       i e# Convert to an integer to fix the N = 0 case.

"0" 1 9emesso 00. Ho provato a giocare a golf q~:B;{:~Bb,2/z:,Bfbs}*:, ma non è valido perché ha invece emesso una stringa vuota.
jimmy23013,

Un ialla fine se ne occuperebbe 00. È possibile recuperare il byte sostituendolo 2/:I-I]con )\]2f/.
Dennis,

3

JavaScript ( ES6 ) 78 79

Funzione ricorsiva. Esegui snippet per testare (solo Firefox)

Modifica 1 byte salvato grazie a @DocMax

F=(b,n,s,S=x=>x.toString(b),m=parseInt(n,b))=>m*s?F(b,S(-~m>>1)+S(m>>1),s-1):n

// Ungolfed

U=(b,n,s)=>
{
  var S=x=>x.toString(b) // function to convert in base b
  var m=parseInt(n,b) // string in base b to integer
  if (m==0 || s==0)
    return n
  else  
    return F(b,S((m+1)>>1) + S( m>>1 ),s-1)
}

// Test
test=[
  {B: 10, N: '0', S:3, K: '0' }, {B: 10, N: '27', S: 1, K: '1413' }, {B: 10, N: '27', S: 2, K: '707706' }, {B: 9, N: '27', S: 1, K: '1413' }, {B: 9, N: '27', S: 2, K: '652651' }
];

test2=[[2, '11011', '11101101', '11101111110110', '11101111110111110111111011'],[3, '2210', '11021101', '20102012010200', '1001212100121210012121001211'],[4, '1113', '230223', '112112112111', '2302302302323023023022'],[5, '101', '2323', '11341134', '31430423143042' ]  ,[6, '120', '4040', '20202020', '1010101010101010'],[7, '134', '5252', '24612461', '1230456412304564'],[8, '22', '1111', '445444', '222622222622'],[9, '4', '22', '1111', '505505'],[10, '92', '4646', '23232323', '1161616211616161' ]
]
test2.forEach(r=>test.push(
  {B:r[0],N:r[1],S:1,K:r[2]}, {B:r[0],N:r[1],S:2,K:r[3]}, {B:r[0],N:r[1],S:3,K:r[4]}
))  

test.forEach(t => (
  r=F(t.B, t.N, t.S), 
  B.innerHTML += '<tr><th>'+(r==t.K?'Ok':'Failed')
      +'</th><td>'+t.B +'</td><td>'+t.N
      +'</td><td>'+t.S +'</td><td>'+r +'</td><td>'+t.K +'</td></tr>'
))
th,td { font-size: 12px; padding: 4px; font-family: helvetica }
<table><thead><tr>
  <th>Test<th>B<th>N<th>S<th>Result<th>Check
  </tr></thead>
  <tbody id=B></tbody>
</table>


Adoro quanto siano elaborate le tue prove di successo. Inoltre, è possibile salvare 1 sostituendolo m&&scon m*s.
DocMax,

1
@DocMax è un test unitario reale e utile. È troppo facile rompere tutto mentre si gioca a golf.
edc65,

1

ECMAScript 6, 90 byte

var f=(B,N,S)=>((n,s)=>S?f(B,s(n+1>>1)+s(n>>1),S-1):s(n))(parseInt(N,B),x=>x.toString(B))

Definire una funzione ricorsiva usando una variabile non è davvero un buon stile, ma è il codice più breve che potrei trovare in ECMAScript 6.

Ottenere il caso d'angolo "00" => "0"corretto spreca tre byte ( s(n)anziché semplicemente N).

Per provarlo, è possibile utilizzare REPL di Babel : copia / incolla il codice e stampare i risultati esempio di invocazione in questo modo: console.log(f(9, "27", 2)).


1

Lisp comune - 113 caratteri

(lambda(b n s)(dotimes(i s)(setf n(format ()"~vR~vR"b (- #1=(parse-integer n :radix b)#2=(floor #1# 2))b #2#)))n)

Ungolfed

(lambda(b n s)
  (dotimes(i s)
    (setf n (format () "~vR~vR" b (- #1=(parse-integer n :radix b)
                                     #2=(floor #1# 2))
                                b #2#)))
  n)
  • La ~vRdirettiva di formato restituisce un numero intero in base v, dove vviene fornito come argomento a format.
  • parse-integeraccetta un :radixargomento per la conversione da una base specificata.
  • #1=e #1#(rispettivamente assegnare e utilizzare) sono variabili del lettore che consentono di condividere sottoespressioni comuni. Quando espansi, danno il seguente codice:

    (lambda (b n s)
      (dotimes (i s)
        (setf n
                (format nil "~vr~vr" b
                        (- (parse-integer n :radix b)
                           (floor (parse-integer n :radix b) 2))
                        b (floor (parse-integer n :radix b) 2))))
      n)

0

Pip , 27 byte

Lcb:+J[(bFB:a)%2i]+b//2TBab

Accetta base, numero intero e numero di ripetizioni come argomenti della riga di comando. L'algoritmo è semplice, ma utilizza un paio di interessanti funzionalità linguistiche:

                             a, b, c initialized from cmdline args, and i = 0 (implicit)
Lc                           Do c times:
        bFB:a                Convert b from base a to decimal and assign back to b
      [(     )%2i]           Construct a list containing b%2 and 0 (using i to avoid
                               scanning difficulties)
                  +b//2      Add floor(b/2) to both elements of list; the list now contains
                               b-b//2 and b//2
                       TBa   Convert elements of list back to base a
     J                       Join list
    +                        Coerce to number (necessary to turn 00 into plain 0)
  b:                         Assign back to b
                          b  Print b at the end

Il tipo scalare di Pip, che rappresenta sia i numeri che le stringhe, è utile qui, così come le operazioni a livello di elemento sugli elenchi; purtroppo, parentesi e gli operatori di due caratteri FB, TBe //negate alcun vantaggio.

Soluzione alternativa, senza assegnazione intermedia ma comunque 27 byte:

Lcb:+J[bFBa%2i]+bFBa//2TBab

0

C, 245 byte

int b,z,n,f,r;c(char*t,n){return n?((z=c(t,n/b)),z+sprintf(t+z,"%d",n%b)):0;}main(){char t[99],*p;gets(t);b=atoi(t);f=n=strtol(p=strchr(t,32)+1,0,b);if(!(r=atoi(strchr(p,32)+1)))f=0;while(r--)n=strtol(t+c(t+c(t,n-n/2),n/2)*0,0,b);puts(f?t:"0");}

Questo non vincerà nulla , ma è stato divertente da fare!


0

PHP ,115 112 byte

function($b,$n,$s){while($s--)$n=($c=base_convert)(ceil($n=$c($n,$b,10)/2),10,$b).$c(floor($n),10,$b);return$n;}

Provalo online!

Ungolfed:

function split_join_repeat( $b, $n, $s ) {
    // repeat S times
    for( $x=0; $x < $s; $x++ ) {
        // convert N from base B to base 10 for arithmetic
        $n = base_convert( $n, $b, 10 );
        // divide and split in base 10, convert back to base B and join
        $n = base_convert( ceil( $n / 2 ), 10, $b ) .
            base_convert( floor( $n / 2 ), 10, $b );
    }
    return $n;
}

Produzione

B = 10, N = 27, S = 1   1413
B = 10, N = 27, S = 2   707706
B = 9, N = 27, S = 1    1413
B = 9, N = 27, S = 2    652651

2   1   10  11  101 1110    111111  10000011111 10000100001000001111    
3   1   10  21  1110    202201  101101101100    1201201201212012012011  212100212102121002121212100212102121002120  
4   1   10  22  1111    223222  111311111311    2232222232322322222322  11131111131311311111311113111113131131111131    
5   1   10  32  1413    432431  213441213440    104220331443104220331442    12141204110401030043301214120411040103004330    
6   1   10  33  1514    535535  245550245545    122553122553122553122552    131022143412311313533131022143412311313533  
7   1   10  43  2221    11111110    40404044040403  2020202202020220202022020201    40556522600645213204055652260064521320  
8   1   10  44  2222    11111111    44444454444444  2222222622222222222226222222    76650460747555347665046074755534    
9   1   10  54  2726    13581357    62851746285173  3142536758708231425367587081    4861155667688600048611556676886000  
10  1   10  55  2827    14141413    70707077070706  3535353853535335353538535353    17676769267677271767676926767727

0

Japt , 17 byte

_nW o ó ®ÊsWÃq}gV

Provalo online!

Accetta input nell'ordine S, N, B con N come elenco singleton . Accettare N senza un elenco singleton costa 2 byte .

Spiegazione:

_             }g     #Get the Sth item generated by this function...
                V    #...Starting with N as the 0th item:
 nW                  # Evaluate the previous item as a base B number
    o                # Create a list with that length
      ó              # Divide it into two lists as evenly as possible
        ®   Ã        # For each of those lists:
         Ê           #  Get the length
          sW         #  Convert it to base B
             q       # Join the two strings together

0

Forth (gforth) , 105 byte

: f base ! 0 ?do 0. 2swap >number nip 2drop 2 /mod >r i + r> 0 tuck <# #s 2drop #s #> loop type decimal ;

Provalo online!

Spiegazione

Cambia la base in B, quindi in un ciclo che esegue S volte:

  • Converte la stringa in un numero
  • Dividi il numero in 2 metà (uno più grande dell'altro se dispari)
  • Combina i due numeri in una stringa

Stampa la stringa al termine e riporta la base su 10 (in modo da poter eseguire più volte di seguito)

Spiegazione del codice

:f                    \ start a new word definition
  base !              \ set the base to B
  0 ?do               \ loop from 0 to S-1 (runs S times)
    0. 2swap          \ places a double-length 0 on the stack behind the string
    >number           \ converts the string to a number in the current base
    nip 2drop         \ get rid of string remainder and second part of double
    2 /mod            \ get the quotient and remainder of dividing by 2
    >r                \ throw the quotient on the return stack
    i                 \ get a copy of the quotient from the return stack
    +                 \ add quotient and remainder
    r>                \ move quotient from return stack to stack
    0 tuck            \ convert both to double-length numbers
    <#                \ start a pictured numeric output
      #s              \ add entire number to output
      2drop           \ drop empty number
      #s              \ add second number to output
    #>                \ convert output to a string and drop number from stack
  loop                \ end loop
  type                \ print output string
  decimal             \ set base back to 10
;                     \ end word definition
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.