1

I am working on one program, I have to find the position of a robot in a grid, it can move in forward direction and can change its facing towards north, south, east and west and have been provided with a given command sequence. So, what will be the final position of the robot. Use of any type of condition branching (e.g. if/else,switch/case) is prohibited.

Example-
Grid-(100*500)
Robot's initial Position-(5,3)
Possible commands-
N-North,
E-East,
W-West,
S-South,
M-Move forward
Sample Input-{N,S,M.M,E,W,E,S,M,S,M}

I tried using Enum, but the problem I am facing is how to call Enum methods with dynamic values which I am getting using commands.

public class RobotMovesInGrid {
    Scanner input = new Scanner(System.in);
    String command=input.next();
    int commLength = command.length();

    static enum Command {
        N{@Override public void execute(String g, String r){ System.out.println("do the N move here"); }},
        E{@Override public void execute(String g, String r){ System.out.println("do the E move here"); }},
        S{@Override public void execute(String g, String r){ System.out.println("do the S move here"); }},
        W{@Override public void execute(String g, String r){ System.out.println("do the W move here"); }},
        M{@Override public void execute(String g, String r){ System.out.println("do the M move here"); }};
        public abstract void execute(String g, String r);

    }
    public void nextPosition() {
        Command c1;
        for(int i=0;i<commLength;i++) {
            if (command.charAt(i)=='N'||command.charAt(i)=='E'|| command.charAt(i)=='S'|| command.charAt(i)=='W'||command.charAt(i)=='M')

                c1= Command.M;// Here instead of M, I am trying to give dynamic commands but it is not taking it
            System.out.println("Current position is"+c1);
        }
    }
}

Could someone please suggest me how to call the Enum methods using commands given as input.

Developer52
  • 519
  • 1
  • 7
  • 29

4 Answers4

2

Here is another solution.

    static enum Command {
        N(-1,0),E(0,1),W(0,-1),S(1,0);
        private int rowIncrement;
        private int colIncrement;

        private Command(int rowIncrement, int colIncrement)
        {
            this.rowIncrement = rowIncrement;
            this.colIncrement = colIncrement;
        }

        public int getRowIncrement()
        {
            return rowIncrement;
        }

        public int getColIncrement()
        {
            return colIncrement;
        }
    }

and here is the code for command evaluation.

    //input
    String command = "NSMMEWESMSM";
    int[] pos = new int[]{5,3};
    int[] size = new int[]{100, 500};

    char[] chars = command.toCharArray();
    //replace M by the previous char, ie move in the same direction
    for (int i = 0; i < chars.length; i++)
    {
        char dir = chars[i];
        //this assumes that M cannot be the first char
        if (dir == 'M')
        {
            dir = chars[i-1];
            chars[i] = dir;
        }
    }


    for (char dir : chars)
    {
        Command cmd = Command.valueOf(String.valueOf(dir));
        pos[0] += cmd.rowIncrement;
        //row is within the region
        pos[0] = Math.min(Math.max(pos[0], 0), size[0] -1);

        pos[1] += cmd.colIncrement;
        //col is within the region
        pos[1] = Math.min(Math.max(pos[1], 0), size[1] -1);
    }
gagan singh
  • 1,521
  • 1
  • 4
  • 11
1

The simplest way would be converting the char input to a String and then invoke valueOf(String) method of the enum to retrieve the enum such as :

for(int i=0;i<commLength;i++) {
   Command command = Command.valueOf(String.valueOf(command.charAt(i))
                                           .toUpperCase());
   if (command != null){
       command.execute(...);
   }
}

It will work but I think that your enum values have really meaningless names.
You should rename them according to their meaning, enrich the enum class with a constructor that contains the mapping character and introduce a static method to retrieve the enum value associated to the input character :

static enum Command {
    NORTH('N'){@Override public void execute(String g, String r){ System.out.println("do the N move here"); }},
    EAST('E'){@Override public void execute(String g, String r){ System.out.println("do the E move here"); }},
    SOUTH('S'){@Override public void execute(String g, String r){ System.out.println("do the S move here"); }},
    WEST('W'){@Override public void execute(String g, String r){ System.out.println("do the W move here"); }},
    MOVE_FORWARD('M'){@Override public void execute(String g, String r){ System.out.println("do the M move here"); }};

    private char mappingChar;

    Command (char mappingChar){
        this.mappingChar = mappingChar;
    }

    public abstract void execute(String g, String r);

    public static Optional<Command> getFrom(char mappingChar) {
        for (Command command : values()) {
            if (Character.toUpperCase(mappingChar)==command.mappingChar) {
                return Optional.of(command);
            }
        }
        return Optional.empty();
    }
}

You can now retrieve the enum value dynamically and use it :

for(int i=0;i<commLength;i++) {
    Optional<Command> optCommand = Command.getFrom(command.charAt(i)); 
    if (optCommand.isPresent()){
        optCommand.get().execute(...)
    }

    // or alternatively 
    optCommand.ifPresent(c -> c.execute(...));        
}
davidxxx
  • 104,693
  • 13
  • 159
  • 179
  • Thank you for your solution, but I am getting 2 errors after using your code. One is The constructor RobotMoveInGrid.Command() is undefined and other is The method get(char) is undefined. – Developer52 Jun 30 '18 at 18:15
  • You are welcome ! Check that the `Command` constructor was added in the enum such as `Command (char mappingChar){ this.mappingChar = mappingChar; }` For the second error, sorry I didn't use an IDE. It is not `get()` but `getFrom()` that should be invoked. I update it. – davidxxx Jun 30 '18 at 18:18
1

One way to do it is with a constant, static Map inside the inner class enum Commands; it associates String to Commands. Command.parse looks up the command in the map.

import java.lang.String;
import java.util.Map;
import java.util.HashMap;
import java.util.Collections;
import java.util.function.Function;
import java.awt.Point;
import java.util.Scanner;

class Robot {

    public static void main(String args[]) {
        try(Scanner input = new Scanner(System.in)) {
            input.useDelimiter(",\\s*|\n");
            Robot r = new Robot();
            while(input.hasNext()) {
                try {
                    Command.parse(input.next().trim()).apply(r);
                } catch(NullPointerException e) {
                    System.out.printf("Syntax error.\n");
                } catch(RuntimeException e) {
                    System.out.printf("Can't go that way: %s.\n",
                        e.getMessage());
                }
            }
        } catch(Exception e) {
            System.err.printf("%s: %s.\n", e, e.getMessage());
        }
    }

    Point x;
    static Point dim;
    Command last;

    Robot() {
        dim = new Point(100, 500);
        x = new Point(5, 3);
    }

    enum Command {
        N("N", "north",  true,  (r) -> new Point(r.x.x, r.x.y - 1)),
        E("E", "east",   true,  (r) -> new Point(r.x.x + 1, r.x.y)),
        S("S", "south",  true,  (r) -> new Point(r.x.x, r.x.y + 1)),
        W("W", "west",   true,  (r) -> new Point(r.x.x - 1, r.x.y)),
        M("M", "farther",false, (r) -> r.last != null ?r.last.go.apply(r):null);

        private String command, name;
        private boolean isDir;
        private Function<Robot, Point> go;
        private static final Map<String, Command> map;

        /* Map for turning commands into Directions; mod->const map. */
        static {
            Map<String, Command> mod = new HashMap<>();
            for(Command c : values()) mod.put(c.command, c);
            map = Collections.unmodifiableMap(mod);
        }

        /** Called from definition of enum. */
        private Command(final String command, final String name, boolean isDir,
            final Function<Robot, Point> go) {
            this.command = command;
            this.name    = name;
            this.isDir   = isDir;
            this.go      = go;
        }

        /** @param str A string representing the direction.
         @return The command or null. */
        public static Command parse(final String str) { return map.get(str); }

        /** Applies this command to r. */
        public void apply(Robot r) {
            Point x = this.go.apply(r);
            if(x == null)
                throw new RuntimeException("don't have a direction");
            if(x.x < 0 || x.x >= dim.x || x.y < 0 || x.y >= dim.y)
                throw new RuntimeException("at the edge");
            r.x = x;
            if(this.isDir == true) r.last = this;
            System.out.printf("Went %s to (%d, %d).\n", r.last.name, x.x, x.y);
        }

        /** @return The name of the direction. */
        public String toString() { return name; }
    }

}

It ends on EOF. I have found these helpful,

Neil
  • 1,214
  • 12
  • 19
  • Only thing I feel is,I think on NEWS command robot will change its direction only, won't move. – Developer52 Jul 01 '18 at 04:37
  • That bears explaining: In the `Command` inner class, `go` is a `Function` that takes in a `Robot` and returns a `Point` that is off by one in the direction `N, E, W, S` from the robot's position. `Command.apply` takes this `Point`, checks if it's a valid point -- exception if it's not, and `r.x = x` updates the point. I did have a more complicated lambda, but that involved a lot of code reuse. – Neil Jul 01 '18 at 04:58
0

You could use Command.valueOf().

Like

c1 = Command.valueOf(command.toUpperCase());

This would set the c1 to an enum value of Command corresponding to the command entered.

toUpperCase() makes sure its the same as the enum's name.