[Programmers / JAVA] Level 1 Dot Product (70128)
[Programmers / JAVA] Level 1 Dot Product (70128)
Two one-dimensional integer arrays a and b of equal length are given as parameters. Complete the solution function so that it returns the dot product of a and b. Here, the dot product of a and b is a[0] * b[0] + a[1] * b[1] + ... + a[n-1] * b[n-1]. (n is the length of a and b)
@RWBwritten at 2021-12-14 05:20:05
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
Two one-dimensional integer arrays a and b of equal length are given as parameters. Complete the solution function so that it returns the dot product of a and b.
Here, the dot product of a and b is a[0] * b[0] + a[1] * b[1] + ... + a[n-1] * b[n-1]. (n is the length of a and b)
- The length of a and b is between 1 and 1,000 inclusive.
- Every number in a and b is between -1,000 and 1,000 inclusive.
| a | b | result |
|---|---|---|
| { 1, 2, 3, 4 } | { -3, -1, 0, 2 } | 3 |
| { -1, 0, 1 } | { 1, 0, -1 } | -2 |
Input/Output Example #1
The dot product of a and b is 1 * (-3) + 2 * (-1) + 3 * 0 + 4 * 2 = 3.
Input/Output Example #2
The dot product of a and b is (-1) * 1 + 0 * 0 + 1 * (-1) = -2.
We just need to iterate over the index, multiply the corresponding elements of a and b, and accumulate the values. Since a and b are the same length, either array can be used for indexing.
JAVA
for (int i = 0; i < a.length; i++) { answer += a[i] * b[i]; }
As shown above, accumulate the product of each pair of elements into answer.
JAVA
/** * Dot Product class * * @author RWB * @since 2021.12.10 Fri 00:17:10 */ class Solution { /** * Method that returns the answer * * @param a: [int[]] Integer array * @param b: [int[]] Integer array * * @return [int] The answer */ public int solution(int[] a, int[] b) { int answer = 0; for (int i = 0; i < a.length; i++) { answer += a[i] * b[i]; } return answer; } }
# Programmers# Algorithm# JAVA# Level 1
