Skip to content

Instantly share code, notes, and snippets.

@NicholasAStuart
Created January 1, 2016 06:28
Show Gist options
  • Save NicholasAStuart/8b0e7ba89d0436a4fe7a to your computer and use it in GitHub Desktop.
Save NicholasAStuart/8b0e7ba89d0436a4fe7a to your computer and use it in GitHub Desktop.
[2015-12-30] Challenge #247 [Intermediate] Moving (diagonally) Up in Life
package com.sandbox;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class DelannoyMain {
public static class Pair implements Comparable<Pair> {
public int x;
public int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
int xDiff = x - o.x;
if (xDiff == 0) {
return y - o.y;
} else {
return xDiff;
}
}
}
public static void main(String... args) throws IOException {
File file = new File("/temp/delannoy.txt");
List<String> lines = Files.readAllLines(file.toPath());
String[] firstLine = lines.remove(0).split(",[\\s]*");
int width = Integer.parseInt(firstLine[0]);
int height = Integer.parseInt(firstLine[1]);
Set<Pair> pairs = new TreeSet<>();
for (int i = 0; i < height; i++) {
String line = lines.remove(0);
String[] split = line.split("");
for (int j = 0; j < width; j++) {
if ("X".equals(split[j])) {
pairs.add(new Pair(j, (height - 1) - i));
}
}
}
long totalPermutations = countPermutations(pairs);
if (totalPermutations == -1) {
System.out.println("<invalid input>");
} else {
System.out.println(totalPermutations);
}
}
public static long countPermutations(Set<Pair> pairs) {
Pair[] iHateJavaSets = pairs.toArray(new Pair[0]);
long total = 1;
for (int i = 0; i < pairs.size() - 1; i++) {
Pair firstPair = iHateJavaSets[i];
Pair secondPair = iHateJavaSets[i + 1];
if ((secondPair.x - firstPair.x) < 0 || (secondPair.y - firstPair.y) < 0) {
return -1;
}
total *= recursiveDelannoy(secondPair.x - firstPair.x, secondPair.y - firstPair.y);
}
return total;
}
public static int recursiveDelannoy(int x, int y) {
if (x == 0 || y == 0) {
return 1;
} else {
return recursiveDelannoy(x - 1, y) + recursiveDelannoy(x, y - 1) + recursiveDelannoy(x - 1, y - 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment