Link to Complete problem:
https://www.hackerrank.com/challenges/botclean
Not the perfect AI Bot wrt score [17.73 (max 17.82)]
Algorithm:
1. make a list of spots.
2. find the closest spot [greedy approach]
3. move in that direction.
To Improve:
1. find closest cluster of points.
2. or find a path that covers more than 1 point [not exactly close to TSP but path containing 2 points should be attainable]
3. or http://www.geeksforgeeks.org/travelling-salesman-problem-set-2-approximate-using-mst/
Source Code is below:
/** * */ package com.kant.hackerrank.ai.challenge; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Scanner; /** * @author shaskant * */ public class BotCleaner { /** * * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] pos = new int[2]; String board[] = new String[5]; for (int i = 0; i < 2; i++) pos[i] = in.nextInt(); for (int i = 0; i < 5; i++) board[i] = in.next(); next_move(pos[0], pos[1], board); } private static List<Point> spots = new ArrayList<BotCleaner.Point>(); /** * * @param posr * @param posc * @param board */ private static void next_move(int posr, int posc, String[] board) { for (int row = 0; row < board.length; row++) { String[] cols = board[row].split("(?!^)"); for (int col = 0; col < cols.length; col++) { switch (cols[col]) { case "d": spots.add(new Point(row, col)); break; } } } Point neighbor = findNextClosestNeighbour(new Point(posr, posc)); if (neighbor.c > posc) { if (neighbor.r > posr) { if (diff(neighbor.r, posr) > diff(neighbor.c, posc)) { System.out.println("DOWN"); } else System.out.println("RIGHT"); } else { if (diff(neighbor.r, posr) > diff(neighbor.c, posc)) { System.out.println("UP"); } else System.out.println("RIGHT"); } } else if (neighbor.c < posc) { if (neighbor.r > posr) { if (diff(neighbor.r, posr) > diff(neighbor.c, posc)) { System.out.println("DOWN"); } else System.out.println("LEFT"); } else { if (diff(neighbor.r, posr) > diff(neighbor.c, posc)) { System.out.println("UP"); } else System.out.println("LEFT"); } } else if (neighbor.r == posr && neighbor.c == posc) { System.out.println("CLEAN"); }else{ if (neighbor.r > posr){ System.out.println("DOWN"); } else System.out.println("UP"); } } private static Point findNextClosestNeighbour(Point start) { Point neigh = new Point(1000, 1000); Iterator<Point> points = spots.iterator(); while (points.hasNext()) { Point next = points.next(); if (dist(start, neigh) >= dist(next, start)) { neigh = next; } } System.out.println(neigh.r+" "+neigh.c); return neigh; } private static int dist(Point start, Point neigh) { return Math.abs(neigh.r - start.r) + Math.abs(neigh.c - start.c); } private static int diff(int x1, int x2) { return Math.abs(x1 - x2); } static class Point { int r; int c; public Point(int s, int p) { r = s; c = p; } } }
Comments
Post a Comment