Output dei prodotti parziali


17

Nella lunga moltiplicazione , dopo aver moltiplicato i numeri, ti rimangono i prodotti parziali, in questa sfida otterrai quei prodotti parziali.

Poiché la moltiplicazione lunga è lunga, per compensare il codice dovrà essere il più breve possibile.

Esempi

34, 53
102, 1700

48, 38 
384, 1440

361, 674
1444, 25270, 216600

0, 0
0

1, 8
8

specificazioni

  • Input / Output può essere in qualsiasi formato ragionevole come array, stringa separata da virgola (o qualsiasi altro delimitatore che non è una cifra), elenco, argomenti di funzione, ecc.
  • I prodotti parziali devono essere in ordine crescente.
  • Se un prodotto parziale è 0, è possibile scegliere se produrlo o meno.

Questo è quindi vince il codice più breve in byte!


Suppongo che i numeri possano essere stringhe, giusto?
Mama Fun Roll

Questo 0,0 test case lo sta rendendo molto più difficile.
xnor

A cosa serve il risultato atteso 12, 102? La maggior parte delle risposte sembra tornare 24, 0, 1200.
Dennis,

@Dennis 24, 0, 1200sta bene. Lo specificherò nel post
Downgoat del

Risposte:


4

Gelatina, 10 byte

DU×µLR’⁵*×

Provalo online!

Come funziona

DU×µLR’⁵*×  Left argument: multiplier -- Right argument: multiplicant

D           Convert the multiplier to base 10 (array of digits).
 U          Reverse the array.
  ×         Multiply each digit by the multiplicant.
   µ        Begin a new, monadic chain. Argument: A(array of products)
    L       Get the length of A.
     R      Turn length l into [1, ..., l].
      ’     Decrement to yield [0, ..., l-1].
       ⁵*   Compute 10**i for each i in that range.
         ×  Hook; multiply the powers of ten by the corresponding elements of A.

3
Immagino che il nome di questa lingua derivi dal fatto che fa sentire tutti gelatina.
geokavel,

7

Pyth, 12 byte

.e**Qsb^Tk_w

Suite di test

Prende l'input newline separato, ad es

361
674

Spiegazione:

.e**Qsb^Tk_w
                Implicit: Q = eval(input()),T = 10
           w    Input the second number as a string.
          _     Reverse it.
.e              Enumerated map, where b is the character and k is the index.
     sb         Convert the character to an int.
   *Q           Multiply by Q.
  *    ^Tk      Multiply by T ^ k. (10 ^ index)

4

JavaScript (ES7), 48 byte

(a,b)=>[...b+""].reverse().map((d,i)=>10**i*a*d)

ES6 (56 byte)

(a,b)=>[...b+""].reverse().map((d,i)=>a*d+"0".repeat(i))

Spiegazione

Restituisce una matrice di prodotti parziali come numeri.

(a,b)=>
  [...b+""]    // convert the multiplier to an array of digits
  .reverse()   // reverse the digits of the multiplier so the output is in the right order
  .map((d,i)=> // for each digit d of the multiplier
    10**i      // get the power of ten of the digit
      *a*d     // raise the product of the digit to it
  )

Test

Test utilizza Math.powinvece di **farlo funzionare nei browser standard.


3

Lua, 72 68 byte

b=arg[2]:reverse()for i=1,#b do print(arg[1]*b:sub(i,i)*10^(i-1))end

3

APL, 21 byte

{⍺×x×10*1-⍨⍳≢x←⊖⍎¨⍕⍵}

Questa è una funzione diadica che accetta numeri interi a sinistra e a destra e restituisce un array. Per chiamarlo, assegnarlo a una variabile.

Spiegazione:

             x←⊖⍎¨⍕⍵} ⍝ Define x to be the reversed digits of the right input
     10*1-⍨⍳≢         ⍝ Generate all 10^(1-i) for i from 1 to the number of digits
{⍺×x×                 ⍝ Multiply the right input by the digits and the powers of 10

1
⍎¨⍕è abbastanza intelligente.
Dennis,

2

05AB1E , 15 byte

Codice:

VDgUSXFTNmY**=\

Spiegazione:

VDgUSXFTNmY**=\

V                 # Assign the input to Y
 D                # Duplicate of input, because the stack is empty
  g               # Pushes the length of the last item
   U              # Assign the length to X
    S             # Split the last item
     X            # Pushes X (length of the last item)
      F           # Creates a for loop: for N in range(0, X)
       TNm        # Pushes 10 ^ N
          Y       # Pushes Y (first input)
           *      # Multiplies the last two items
            *     # Multiplies the last two items
             =    # Output the last item
              \   # Discard the last item

2

Pyth, 26 byte

DcGHKjHTFNJlK*G*@Kt-JN^TN

Questo definisce una funzione ctale da accettare 2argomenti e la funzione stampa i prodotti parziali.

DcGHKjHTFNJlK*G*@Kt-JN^TN
DCGH                      Define function c(G, H)
    KjHT                  Set K to the list of digits converting H to base 10
        FNJlK             Set J to the length of K and loop with variable N
                          (Implicit: print)
             *G*@Kt-JN    Calculates the partial product
                      ^TN Raising it to the appropriate power of 10

1

MATL , 18 byte

ij48-tn:1-P10w^**P

Il compilatore (5.1.0) funziona in Matlab e in Octave.

Ogni numero viene inserito su una riga separata.

Esempio

>> matl ij48-tn:1-P10w^**P
> 361
> 674
1444  25270 216600

Spiegazione

i           % input first number (say 361)
j           % input second number, interpreted as a string (say '674')
48-         % subtract '0' to obtain vector of figures (gives [6 7 4])
tn:1-P      % vector [n-1, ... 1, 0] where n is the number of figures (gives [2 1 0])
10w^        % 10 raised to that, element-wise (gives [100 10 1])
*           % multiply, element-wise (gives [600 70 4])
*           % multiply (gives 361*[600 70 4], or [216600 25270 1444])
P           % flip vector ([1444 25270 216600]). Implicitly display

1

Haskell, 60 57 54 byte

g x=zipWith(\b->(x*10^b*).read.pure)[0..].reverse.show

5 byte in meno (rilasciare il .show) se posso prendere il secondo numero come stringa.

Esempio di utilizzo: g 361 674-> [1444,25270,216600].

Moltiplica ogni cifra del rovescio di ycon xe scala con10^i dovei = 0,1,2,... .

Modifica: grazie a @Mauris per 3 byte!


Puoi persino fare (\b->(x*10^b*).read.pure).
Lynn il

@Mauris: Nizza. Molte grazie!
nimi,

1

Julia, 50 49 byte

f(a,b)=[a*d*10^~-i for(i,d)=enumerate(digits(b))]

Questa è una funzione che accetta due numeri interi e restituisce un array di numeri interi.

La digitsfunzione restituisce una matrice delle cifre dell'intero input in ordine inverso. Otteniamo l'indice, usando coppie di valorienumerate e calcoliamo i prodotti parziali come il primo input moltiplicato per le cifre per 10 volte elevato alla potenza dell'indice della cifra - 1.

Salvataggio di un byte grazie a Dennis!


1

Python 2, 61

def p(a,b):
 j=0
 while b>0:
  print`b%10*a`+j*'0';b/=10;j+=1 

1

CJam, 19 17 byte

q~W%eef{~~A@#**}p

Prende input con il primo elemento che è un numero intero e il secondo una stringa (ad es 34 "53" .). I suggerimenti sono benvenuti, poiché sono sicuro che possono essere più brevi. Grazie a Dennis per aver salvato due byte.

Provalo online.

Spiegazione

q~    e# Get input and evaluate it, x and "y"
W%    e# Reverse y so it will be properly sorted
ee    e# Enumerate through y with each character and its index
f{    e# For each digit in y...
  ~~  e# Convert the digit to an integer on the stack
  A@# e# Take 10 to the power of y's index
  **  e# Multiply all three together to get the final result
}
p     e# Print the array

1
~~A@#**salva un paio di byte.
Dennis,

1

Haskell, 37 byte

a%0=[]
a%b=b`mod`10*a:(a*10)%div b 10

Nessun stringismo, solo aritmetica. Anticipa ricorsivamente il prodotto parziale più piccolo al resto, dove bviene troncata l'ultima cifra di e viene applicato un moltiplicatore di 10. La precedenza dell'operatore funziona bene.


0

𝔼𝕊𝕄𝕚𝕟, 11 caratteri / 23 byte (non competitivo)

ᴙíⓢⓜî*$*Ⅹⁿ_

Try it here (Firefox only).

Trovato un bug durante la codifica della soluzione a questo problema ...

Spiegazione

          // Implicit: î = input 1, í = input 2
ᴙíⓢ      // reverse í and split it into an array
ⓜî*$*Ⅹⁿ_ // multiply î by each individual digit in í and put in previous array
          // implicit output

0

Japt , 28 byte

I=[]Vs w m@IpApY+1 /A*U*X};I

Spiegazione:

I=[]Vs w m@IpApY+1 /A*U*X};I
I=[]                         //that's simple, init an array I
    Vs                       //take the second input and convert to string
       w                     //reverse it and...
         m@              }   //...map through the chars; X is a char, Y is counter
           Ip............    //push the following value into I...
             ApY+1 /A*U*X    //10^(Y+1)/10*U*X, U is the first input
                           I //output the resulting array

A causa del bug nell'interprete, devi usare ApY+1 /10invece di ApY, perché Ap0(che è 10 ^ 0) dà 100. Immagino sia per il motivo che consenta una quadratura veloce Ap, ma 0non significa "nessun argomento". Per favore, et.
nicael

0

Python 2, 42 byte

f=lambda a,b:b*[0]and[b%10*a]+f(a*10,b/10)

Nessun stringismo, solo aritmetica. Aggiunge ricorsivamente il prodotto parziale più piccolo al resto, dove bviene troncata l'ultima cifra di e viene applicato un moltiplicatore di 10.

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.