Package progs

Source Code of progs.RobotMovement

package progs;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import progs.lib.Pair;
import progs.lib.Point;

import java.util.HashMap;

/**
* @author KRishna Atkuru
*/
@RunWith(JUnit4.class)
public class RobotMovement {

  @Test
  public void tests() {
    Solution solution = new Solution();
    Assert.assertEquals(6, solution.numPaths(new Point(0, 0), new Point(2, 2)));
    Assert.assertEquals(10, solution.numPaths(new Point(0, 0), new Point(2, 3)));
  }

  static class Solution {
    private final HashMap<Pair<Point, Point>, Integer> pointPathCount;

    Solution() {
      pointPathCount = new HashMap<>();
    }

    // Using memoization
    public int numPaths(Point x, Point y) {
      if (x.equals(y)) {
        return 1;
      }
      if (y.getX() < x.getX() || y.getY() < x.getY()) {
        return 0;
      }
      Point yXMinus1 = new Point(y.getX() - 1, y.getY());
      Point yYMinus1 = new Point(y.getX(), y.getY() - 1);
      int sum1, sum2;
      if (pointPathCount.containsKey(new Pair<>(x, yXMinus1))) {
        sum1 = pointPathCount.get(new Pair<>(x, yXMinus1));
      } else {
        sum1 = numPaths(x, yXMinus1);
        pointPathCount.put(new Pair<>(x, yXMinus1), sum1);
      }
      if (pointPathCount.containsKey(new Pair<>(x, yYMinus1))) {
        sum2 = pointPathCount.get(new Pair<>(x, yYMinus1));
      } else {
        sum2 = numPaths(x, yYMinus1);
        pointPathCount.put(new Pair<>(x, yYMinus1), sum2);
      }
      return sum1 + sum2;
    }
  }
}
TOP

Related Classes of progs.RobotMovement

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.