Solution: Google code jam 2008, Round 1A: A. Minimum Scalar Product
1 private static int getMinimumScalarProduct(List<Integer> vector1,
2 List<Integer> vector2) throws Exception {
3 Collections.sort(vector1);
4 Collections.sort(vector2);
5 Collections.reverse(vector2);
6 return getScalarProduct(vector1, vector2);
7 }
8
9 /**
10 * 2 vectors must have same length
11 * @param vector1
12 * @param vector2
13 * @return the scalar product of 2 vectors
14 * @throws Exception
15 */
16 private static int getScalarProduct(List<Integer> vector1,
17 List<Integer> vector2) throws Exception {
18 if(vector1.size() != vector2.size()) {
19 throw new Exception("The vectors' length are not same!");
20 }
21 int product = 0;
22 for(int i = 0, length = vector1.size(); i < length; i++) {
23 product += vector1.get(i) * vector2.get(i);
24 }
25 return product;
26 }
2 List<Integer> vector2) throws Exception {
3 Collections.sort(vector1);
4 Collections.sort(vector2);
5 Collections.reverse(vector2);
6 return getScalarProduct(vector1, vector2);
7 }
8
9 /**
10 * 2 vectors must have same length
11 * @param vector1
12 * @param vector2
13 * @return the scalar product of 2 vectors
14 * @throws Exception
15 */
16 private static int getScalarProduct(List<Integer> vector1,
17 List<Integer> vector2) throws Exception {
18 if(vector1.size() != vector2.size()) {
19 throw new Exception("The vectors' length are not same!");
20 }
21 int product = 0;
22 for(int i = 0, length = vector1.size(); i < length; i++) {
23 product += vector1.get(i) * vector2.get(i);
24 }
25 return product;
26 }