Vector2D Class
Problem
A 2D vector has two whole numbers x and y. Commands: vec NAME X Y (store), add A B C (store A + B in C), scale A K C (store A times K in C), dot A B (print x1*x2 + y1*y2), len2 A (print x*x + y*y), show A (print (x, y), for example (3, -4)).
Constraints
- 1 <= commands <= 100
- numbers fit in 32 bits
Examples
Input
vec a 1 2 vec b 3 4 add a b c show c
Output
(4, 6)
Solutions
The vector is a small immutable value object: its operations return new vectors and never change the old ones. The command loop only calls methods.
/*
* Problem : Run the commands.
* Input : Command lines.
* Output : One line per answer.
* Approach: Vec2 class
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// Step 1: An immutable vector. Every operation returns a new vector and keeps the old ones as they were.
static class Vec2 {
final long x;
final long y;
Vec2(long x, long y) {
this.x = x;
this.y = y;
}
Vec2 plus(Vec2 other) {
return new Vec2(x + other.x, y + other.y);
}
Vec2 times(long k) {
return new Vec2(x * k, y * k);
}
// Step 2: The dot product and the squared length are methods of the vector itself.
long dot(Vec2 other) {
return x * other.x + y * other.y;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
// This method solves the task. It receives the input and returns the answer.
static String[] solve(String[] lines) {
java.util.Map<String, Vec2> vectors = new java.util.HashMap<String, Vec2>();
java.util.List<String> out = new java.util.ArrayList<String>();
for (String line : lines) {
String[] part = line.split(" ");
if (part[0].equals("vec")) {
vectors.put(part[1], new Vec2(Long.parseLong(part[2]), Long.parseLong(part[3])));
} else if (part[0].equals("add")) {
vectors.put(part[3], vectors.get(part[1]).plus(vectors.get(part[2])));
} else if (part[0].equals("scale")) {
vectors.put(part[3], vectors.get(part[1]).times(Long.parseLong(part[2])));
} else if (part[0].equals("dot")) {
out.add(String.valueOf(vectors.get(part[1]).dot(vectors.get(part[2]))));
} else if (part[0].equals("len2")) {
out.add(String.valueOf(vectors.get(part[1]).dot(vectors.get(part[1]))));
} else {
out.add(vectors.get(part[1]).toString());
}
}
return out.toArray(new String[0]);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
java.util.List<String> all = new java.util.ArrayList<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
if (!line.isEmpty()) {
all.add(line);
}
}
String[] lines = all.toArray(new String[0]);
System.out.println(String.join("\n", solve(lines)));
}
}
Hints (2)
- Why return a new vector from plus?
- How is the squared length written with dot?