Skip to content

Instantly share code, notes, and snippets.

@karthik-ir
Created January 29, 2018 05:00
Show Gist options
  • Save karthik-ir/099aeaeba0544365581b8b03fa7e937d to your computer and use it in GitHub Desktop.
Save karthik-ir/099aeaeba0544365581b8b03fa7e937d to your computer and use it in GitHub Desktop.
package com.karthik.glosfer;
import java.security.NoSuchAlgorithmException;
import java.util.HashSet;
import java.util.Set;
public class Traverser {
static int totalPoints = 0;
static int rejectCount = 0;
static Set<String> hashes = new HashSet<String>();
public static void main(String[] args) throws NoSuchAlgorithmException {
int min = Integer.MIN_VALUE;
int max = Integer.MAX_VALUE;
move(0, 0, min, max);
System.out.println("Total number of points reached: " + totalPoints);
System.out.println("total number of rejected points:" + rejectCount);
}
private static void move(int x, int y, int min, int max) throws NoSuchAlgorithmException {
// Top
findPath(x, y - 1, min, max);
// RIGHT
findPath(x + 1, y, min, max);
// Down
findPath(x, y + 1, min, max);
// Left
findPath(x - 1, y, min, max);
}
private static boolean findPath(int x, int y, int min, int max) throws NoSuchAlgorithmException {
// mark x,y as a point to be reached
String key = x + "--" + y;
if (hashes.contains(key)) {
return false;
}
hashes.add(key);
if (sumOfSum(x, y) > 21) {
++rejectCount;
return false;
}
if (x < min || x > max || y < min || y > max) {
return false;
}
++totalPoints;
// Top
findPath(x, y - 1, min, max);
// RIGHT
findPath(x + 1, y, min, max);
// Down
findPath(x, y + 1, min, max);
// Left
findPath(x - 1, y, min, max);
return false;
}
private static int sumOfSum(int x, int y) {
return sumDigits(x) + sumDigits(y);
}
public static int sumDigits(int n) {
n = Math.abs(n);
int num = 0, sum = 0;
while (n != 0) {
num = n % 10;
sum = sum + num;
n = n / 10;
}
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment