Espandi un numero


11

Espandi un numero

Il tuo compito è espandere un numero intero maggiore di 0 nel modo seguente:

Dividi il numero in cifre decimali e per ogni cifra genera un elenco secondo queste regole:

  • se la cifra è dispari, l'elenco inizia con la cifra e scende a 1;
  • se la cifra è pari, l'elenco inizia con la cifra e sale fino a 9.
  • se la cifra è 0, l'elenco è vuoto.

Annota gli elenchi per i numeri dispari sotto le cifre e sopra per quelli pari. Quindi allinea le colonne in alto e raccogli le cifre in ogni riga per creare numeri interi. Come ultimo passo sommare i numeri per trovare l'espansione del numero.

Ecco un esempio delle regole precedenti applicate a 34607:

 9          
 8          
 79         
 68         
 57         
346 7 ->  399 7 -> 3997 -> 9418
2   6     288 6    2886
1   5     177 5    1775
    4      66 4     664
    3      5  3      53
    2      4  2      42 
    1         1       1

Ecco i casi di test:

1: 1
2: 44
3: 6
44: 429
217: 1270
911: 947
2345: 26114
20067: 3450
34875632: 70664504
9348765347634763: 18406119382875401

Questo è , quindi vincono le risposte più brevi in ​​byte in ogni lingua.


1
Possiamo prendere l'input come una stringa? O come una matrice di cifre?
Arnauld,

@Arnauld Deve essere un numero intero e per dividerlo in cifre con il tuo programma / funzione
Galen Ivanov

@GalenIvanov Ma se l'input proviene da stdin, suppongo che sia ok (anche se tecnicamente una stringa), giusto?
Adám,

@Adám Sì, tecnicamente è una stringa, quindi va bene.
Galen Ivanov,

E qui ho pensato che sarebbe stata un'espansione come questa .
Ingegnere Toast,

Risposte:


8

Gelatina , 13 byte

Dḟ0RrḂ?€9UZḌS

Un collegamento monadico che prende e restituisce numeri interi positivi.

Provalo online! o vedi la suite di test .

Come?

Dḟ0RrḂ?€9UZḌS - Link: positive integer           e.g. 702
D             - cast to a decimal list                [7,0,2]
  0           - literal zero                          0
 ḟ            - filter discard                        [7,2]
        9     - literal nine
       €      - for each:
      ?       -   if:
     Ḃ        -   ...condition: bit (modulo by 2)      1              ,0
   R          -   ...then: range ([1,...n])            [1,2,3,4,5,6,7],n/a
    r         -   ...else: inclusive range ([n,...9])  n/a            ,[2,3,4,5,6,7,8,9]
         U    - upend                                 [[7,6,5,4,3,2,1],[9,8,7,6,5,4,3,2]]
          Z   - transpose                             [[7,9],[6,8],[5,7],[4,6],[3,5],[2,4],[1,3],2]
           Ḍ  - cast from decimal lists               [79,68,57,46,35,24,13,2]
            S - sum                                   324

4

Perl 6 ,  68  66 byte

{sum roundrobin(.comb».&{$_%2??($_...1)!!(9...+$_) if +$_})».join}

Provalo

{sum roundrobin(.comb».&{[R,] $_%2??1..$_!!$_..9 if +$_})».join}

Provalo

Allargato:

{  # bare block lambda with implicit parameter 「$_」

  sum

    roundrobin( # grab from the sub lists in a round robin fashion

      .comb\             # split the input into digits
      ».&{               # for each digit do this

        [R,]             # reduce with reversed &infix:«,» (shorter than reverse)

              $_ % 2     # is the digit not divisible by 2?
          ??  1  .. $_   # from 1 to the digit
          !!  $_ ..  9   # from the digit to 9

        if +$_           # only do the above if the current digit isn't 0
                         # (has the effect of removing 0 from the list)
     }

    )».join     # join each of the sub-lists from roundrobin
}

3

APL (Dyalog) , 39 byte

Corpo del programma completo. Richiede input da STDIN. Stampa il risultato su STDOUT.

+/10⊥¨0~⍨¨↓⍉↑{2|⍵:⌽⍳⍵⋄×⍵:⌽⍵,⍵↓⍳9⋄⍬}¨⍎¨⍞

Provalo online!

Per visualizzare l'ultimo caso di test correttamente, ⎕FR( F loating punto R ePresentation) è stato impostato a 128 bit decimale e ⎕PP( P tampa P recision) è stato impostato a 34 cifre.

 richiedere l'immissione di testo da STDIN

⍎¨ esegui ciascuno (ottiene ogni cifra come un numero)

{...  per ogni elemento, applica la seguente funzione in cui l'argomento è rappresentato da :

2|⍵: if dispari (lett. "if" resto della divisione quando diviso per 2), quindi:

   inverso

   i tenteger da 1 a

   l'argomento

 altro

×⍵: se l'argomento è positivo (lett. "if" signum), allora:

   inverso

   l'argomento

  , seguito da

   discussione

   elementi caduti da

  ⍳9 the ɩ ntegers da 1 a 9

 altro

   elenco vuoto

 mescola (combina) questo elenco di liste in un'unica matrice, riempiendo gli zeri a destra

 trasporre

 dividere questa matrice in un elenco di elenchi

0~⍨¨ rimuove tutti gli zeri da ciascun elenco

10⊥¨ converti ciascuno da base 10 a numeri normali (questo raccoglie le cifre)

+/ sommare i numeri


2
Grazie per la tua spiegazione. Solo per farti sapere che ho scoperto il golf del codice dopo averti visto nel video del golf del codice APL.
Galen Ivanov,

3

JavaScript (ES6), 88 83 82 byte

f=(n,k=0)=>k<9&&+[...n+''].map(x=>+x&&(x=x&1?x:9-k<x||9)>k?x-k:'').join``+f(n,k+1)

Nota

9 - k < x || 9salva un byte 9 - k >= x && 9ma genera 1invece che 0se la disuguaglianza è verificata. Sarebbe un problema se ciò causasse 1 > k, innescando la strada sbagliata nel ternario esterno. Ma significherebbe questo k = 0e quindi 9 - k = 9, quindi non possiamo averlo 9 - k < xallo stesso tempo.

Casi test

NB: rimosso l'ultimo caso di test che supera la precisione del numero JS.



3

Java 11, 210 209 191 181 byte

n->{long r=0;var a="0".repeat(9).split("");for(int d:(n+"").getBytes())for(int k=0,x=d-48,y=9;x>0&(k<1||(d%2<1?y-->x:x-->1));a[k++]+=d%2<1?y:x);for(var q:a)r+=new Long(q);return r;}

Ok, ci è voluto un po 'di tempo (principalmente perché all'inizio ho fatto un errore, quindi ho dovuto scrivere ogni passaggio per capire meglio cosa ho fatto di sbagliato). Molto probabilmente si può giocare a golf un po 'di più.

-18 byte grazie a @ceilingcat .

Spiegazione:

Provalo qui.

n->{                             // Method with long as both parameter and return-type
  long r=0;                      //  Result-long `r`, starting at 0
  var a="0".repeat(9).split(""); //  String array `a`, filled with nine String zeroes
  for(int d:(n+"").getBytes())   //  Cast the input to a String,
                                 //   and loop over its codepoints as integers:
    for(int k=0,                 //   Row-index `k`, starting at
        x=d-48,                  //   Temp integer `x`, set to the current digit
        y=9                      //   Temp integer `y`, set to 9
        ;                        //   Inner loop, if:
         x>0                     //     The current digit is not a 0,
          &(k<1                  //     and if this is the first iteration,
             ||(d%2<1?           //     or if the digit is even:
                 y-->x           //      And `y` is larger than the digit
                                 //      (and afterwards decrease `y` by 1 with `y--`)
                :                //     or if the digit is odd:
                 x-->1));        //      And `x` is larger than 1
                                 //      (and afterwards decrease `x` by 1 with `x--`)
      a[k++]+=                   //    Append the current row with:
                                 //    (and afterwards increase `k` by 1 with `k++`)
       d%2<1?                    //     If the digit is even:
        y                        //      Append the row with `y`
       :                         //     Else (the digit is odd):
        x);                      //      Append the row with `x`
  for(var q:a)                   //  Loop over the String rows in the array:
    r+=new Long(q);              //   Convert it to a long, and add it to the result-sum
  return r;}                     //  Return the result

2

Pip , 28 byte

J_MS(RV{a?a%2?\,aa,tl}Ma)ZDx

Provalo online!

Spiegazione

                      Ma      Map this function to the digits of the 1st cmdline arg:
        a?                     If digit != 0:
          a%2?                  If digit is odd:
              \,a                Inclusive-range(digit)
                 a,t            Else (digit is even), range from digit to 10 (exclusive)
                    l          Else (digit is 0), empty list
     RV{             }         Apply reverse to the result before returning it
                              This gives us a list of lists like [9 8 7 6] or [3 2 1]
    (                   )ZDx  Zip, with a default value of empty string
J_MS                          Use map-sum to join each sublist and sum the results
                              Autoprint (implicit)

Come procedono i passaggi 34607come argomento:

34607
[[1 2 3] [4 5 6 7 8 9] [6 7 8 9] [] [1 2 3 4 5 6 7]]
[[3 2 1] [9 8 7 6 5 4] [9 8 7 6] [] [7 6 5 4 3 2 1]]
[[3 9 9 "" 7] [2 8 8 "" 6] [1 7 7 "" 5] ["" 6 6 "" 4] ["" 5 "" "" 3] ["" 4 "" "" 2] ["" "" "" "" 1]]
[3997 2886 1775 664 53 42 1]
9418



2

R , 153 146 byte

function(n,m=n%/%10^(nchar(n):0)%%10)sum(strtoi(apply(sapply(m[m>0],function(x)c(r<-"if"(x%%2,x:1,9:x),rep("",9-sum(r|1)))),1,paste,collapse="")))

Provalo online!

A volte, non riesco a dire se sono solo spazzatura a golf, o se R lo è ... Sono decisamente io, risparmiato 7 byte grazie all'utente2390246, che mi ha ricordato un altro modo per estrarre le cifre (che ho suggerito a me stesso) .

È possibile sostituire strtoicon as.doubleper ottenere 18406718084351604l'ultimo caso di test (che è sbagliato); R ha solo numeri interi a 32 bit.


Puoi salvare un po 'prendendo n come numero intero e convertendolo in cifre usando uno dei tuoi trucchi! 146 byte
user2390246

@ user2390246 sai, l'ho provato, ma penso di essere stato fissato sull'uso della conversione implicita a character->intquando ho chiamato :e poi usato strtoicomunque!
Giuseppe,

1

Perl 5 , 120 + 1 ( -a) = 121 byte

$p=y/01357/ /r;$n=y/02468/ /r;map{$p=~s/9/ /g;$p=~s/\d/$&+1/ge;$n=~s/\d/$&-1/ge;$n=~s/0/ /g;@F=($p,@F,$n)}0..7;say for@F

Provalo online!


1

Python 2 , 131 byte

lambda n:sum(int(''.join(`n`for n in l if n))for l in map(None,*[range(n and(n%2*n or 9),(n%2<1)*~-n,-1)for n in map(int,`n*10`)]))

Provalo online!


1

05AB1E , 16 byte

0KεDÈi9ŸëL]íõζJO

Provalo online o verifica tutti i casi di test .

O in alternativa:

0KεDÈ8*>Ÿ{R}õζJO
0Kε9Ÿ¬L‚yèR}õζJO

Spiegazione:

0K        # Remove all 0s from the (implicit) input-integer
  ε       #  Map each digit to:
   D      #   Duplicate the digit
    Èi    #   If it's even:
      9Ÿ  #    Pop and push a list in the range [digit, 9]
     ë    #   Else (the digit is odd):
      L   #    Pop and push a list in the range [1, digit]
  ]       # Close both the if-else statement and map
   í      # Reverse each inner ranged list
     ζ    # Zip/transpose, swapping rows and columns,
    õ     # with an empty string as filler
      J   # Join each inner list together
       O  # And sum that list
          # (after which the result is output implicitly)

1

Burlesque , 39 byte

riXX:nz{J2dv{{9r@}{ro}}che!<-}m[tp)im++

Provalo online!

ri      #Read as int
XX      #Return list of digits
:nz     #Filter for non-zero
{
 J2dv   #Divisible by 2?
 {
  {9r@} #Range a, 9
  {ro}  #Range 1, a
 }che!  #Run based on if divisible
 <-     #Reverse the range
}m[     #Apply to each digit
tp      #Transpose digits
)im     #Join each list into single int
++      #Sum each int
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.