-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecretCode.java
More file actions
42 lines (34 loc) · 923 Bytes
/
Copy pathSecretCode.java
File metadata and controls
42 lines (34 loc) · 923 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package io;
import java.util.HashMap;
import java.util.Random;
public class SecretCode {
HashMap<String, Integer> keyMap = new HashMap<>();
void addKey(String user) {
if (!containsUser(user)) {
Integer key = new Random().nextInt();
keyMap.put(user, key);
}
}
boolean containsUser(String user) {
return keyMap.containsKey(user);
}
public Integer encode(String user, Integer code) {
Integer key = null;
if (!containsUser(user)) {
addKey(user);
}
key = keyMap.get(user);
return code ^ key;
}
public Integer decode(String user, Integer code) {
return encode(user, code);
}
public static void main(String[] args) {
SecretCode coder = new SecretCode();
Integer code = 23334;
Integer encode = coder.encode("John", code);
System.out.println(encode);
Integer decode = coder.encode("John", encode);
System.out.println(decode);
}
}