Last active
August 29, 2015 14:04
-
-
Save antoniobg/a9942162c088114c1632 to your computer and use it in GitHub Desktop.
Task1 - Cognima
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class Task1 { | |
public static long hash(String s) { | |
long h = 7; | |
String letters = "acdegilmnoprstuw"; | |
for(int i = 0; i < s.length(); i++) | |
h = (h * 37 + letters.indexOf(s.charAt(i))); | |
return h; | |
} | |
public static String decode(long n) { | |
char[] letters = "acdegilmnoprstuw".toCharArray(); | |
StringBuilder sb = new StringBuilder(); | |
while (n != 7) { | |
long x = n; | |
for (int i = 0; i < 16; i++) { | |
if ((x-i) % 37 == 0) { | |
sb.append(letters[i]); | |
n = (n-i)/37; | |
break; | |
} | |
} | |
} | |
return sb.reverse().toString(); | |
} | |
public static void main (String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
String s = ""; | |
while(!s.equals("exit")) { | |
System.out.println("Enter 1 for hashing or 2 for decoding"); | |
s = scanner.nextLine(); | |
int opt = Integer.parseInt(s); | |
long h; | |
switch (opt) { | |
case 1: | |
System.out.println("Enter a word"); | |
s = scanner.nextLine(); | |
h = hash(s); | |
System.out.println("Word: " + s); | |
System.out.println("Hash:" + h + "\n"); | |
break; | |
case 2: | |
s = scanner.nextLine(); | |
h = Long.parseLong(s); | |
System.out.println("Hash: "+ h); | |
System.out.println("Word:" + decode(h)); | |
break; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment