부분 제품 출력


17

긴 곱셈 에서는 숫자를 곱한 후 부분 곱이 남습니다.이 도전에서는 해당 부분 곱을 출력합니다.

곱셈이 길기 때문에 코드를 보상하려면 가능한 한 짧아야합니다.

34, 53
102, 1700

48, 38 
384, 1440

361, 674
1444, 25270, 216600

0, 0
0

1, 8
8

명세서

  • 입력 / 출력은 배열, 쉼표로 구분 된 문자열 (또는 숫자가 아닌 다른 구분 기호), 목록, 함수 인수 등과 같은 합리적인 형식 일 수 있습니다.
  • 부분 제품의 순서가 증가해야합니다.
  • 부분 제품이 0인 경우 출력 여부를 선택할 수 있습니다.

이것은 이므로 바이트 단위의 가장 짧은 코드가 승리합니다!


숫자가 문자열 일 수 있다고 가정합니다.
Mama Fun Roll

이 0,0 테스트 사례는 훨씬 더 어려워지고 있습니다.
xnor

예상되는 결과는 무엇입니까 12, 102? 대부분의 답변이 돌아 오는 것 같습니다 24, 0, 1200.
Dennis

@Dennis 24, 0, 1200는 괜찮습니다. 나는 포스트에서 지정할 것이다
Downgoat

답변:


4

젤리, 10 바이트

DU×µLR’⁵*×

온라인으로 사용해보십시오!

작동 원리

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
나는이 언어의 이름이 모든 사람들이 젤리를 느끼게한다는 사실에서 비롯된 것 같아요.
geokavel

7

Pyth, 12 바이트

.e**Qsb^Tk_w

테스트 스위트

예를 들어 입력 줄 바꿈을 분리합니다.

361
674

설명:

.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

자바 스크립트 (ES7), 48 바이트

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

ES6 (56 바이트)

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

설명

부분 제품 배열을 숫자로 반환합니다.

(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
  )

테스트

표준 브라우저에서 작동하도록 테스트 Math.pow대신 사용 **합니다.


3

루아, 72 68 바이트

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

3

APL, 21 바이트

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

이것은 왼쪽과 오른쪽의 정수를 받아들이고 배열을 반환하는 2 차원 함수입니다. 호출하려면 변수에 지정하십시오.

설명:

             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
⍎¨⍕꽤 영리합니다.
Dennis

2

05AB1E , 15 바이트

암호:

VDgUSXFTNmY**=\

설명:

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 바이트

DcGHKjHTFNJlK*G*@Kt-JN^TN

인수를 c허용 하도록 함수를 정의하고 함수 2는 부분 곱을 인쇄합니다.

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 바이트

ij48-tn:1-P10w^**P

컴파일러 (5.1.0)는 매트랩과 옥타브에서 작동합니다.

각 번호는 별도의 줄에 입력됩니다.

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

설명

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

하스켈, 60 57 54 바이트

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

.show두 번째 숫자를 문자열로 사용할 수 있으면 5 바이트가 적습니다 (을 삭제하십시오 ).

사용 예 : g 361 674-> [1444,25270,216600].

곱의 역의 모든 자리 yx와 규모 .10^ii = 0,1,2,...

편집 : 3 바이트 동안 @Mauris에 감사드립니다!


당신은 할 수 있습니다 (\b->(x*10^b*).read.pure).
Lynn

@Mauris : 좋습니다. 고마워요!
nimi

1

줄리아, 50 49 바이트

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

두 개의 정수를 허용하고 정수 배열을 리턴하는 함수입니다.

digits함수는 입력 정수의 자릿수 배열을 역순으로 반환합니다. 우리 enumerate는 첫 번째 입력 시간에 숫자 곱하기 10을 자릿수의 거듭 제곱으로 올림으로써 부분 곱을 사용하여 인덱스, 값 쌍을 얻 습니다-1.

Dennis 덕분에 바이트를 절약했습니다!


1

파이썬 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 바이트

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

첫 번째 항목은 정수이고 두 번째 항목은 문자열 (예 :)로 입력을 34 "53"받습니다. 더 짧을 수 있으므로 제안을 환영합니다. 2 바이트를 절약 해 준 Dennis에게 감사합니다.

온라인으로 사용해보십시오.

설명

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@#**몇 바이트를 절약합니다.
Dennis

1

하스켈, 37 바이트

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

엄격하지 않고 단지 산술입니다. 가장 작은 부분 곱을 나머지에 재귀 적으로 추가합니다. 여기서 마지막 숫자 b는 잘리고 10의 배수가 적용됩니다. 연산자 우선 순위는 훌륭하게 작동합니다.


0

𝔼𝕊𝕄𝕚𝕟, 11 자 / 23 바이트 (비경쟁)

ᴙíⓢⓜî*$*Ⅹⁿ_

Try it here (Firefox only).

이 문제에 대한 솔루션을 코딩하는 동안 버그를 발견했습니다 ...

설명

          // 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

apt , 28 바이트

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

설명:

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

때문에 인터프리터의 버그로 사용할 필요가 ApY+1 /10대신 ApY하기 때문에, Ap0(10 ^ 0이다) 나는 이유는 고속으로 제곱 수 있도록하는 것이 같아요 (100)을 제공 Ap하지만, 0하지 의미 "인수를"하지 않습니다. PLZ 수정, Eth.
nicael

0

파이썬 2, 42 바이트

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

엄격하지 않고 단지 산술입니다. 가장 작은 부분 곱을 나머지에 재귀 적으로 추가합니다. 마지막 자리 b는 잘리고 10의 배수가 적용됩니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.