The ‘I-Game’: Answer

Hey guys!
Hope you can remember my previous post ” The ‘I-Game’ “ . In this post I like to share an answer for that problem. There can be many solutions for the problem but I found this neat piece of code while surfing the internet. Anyone whose interested in other problems & answers they can visit http://www.migids.com/ .  I have tested the code for the sample input and worked fine.

Enjoj ! 🙂


import java.util.Scanner;

public class ProblemS {

    static char[][] grid = new char[10][10];

    public static void main(String[] args) {

        // "turn off lights"
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                grid[i][j] = '.';
            }
        }

        String line = "";
        Scanner console = new Scanner(System.in);

        try {
            while (console.hasNextLine()) {
                line = console.nextLine();
                if (line == null || line.isEmpty()) {
                    break;
                }
                int[] coords = new int[2];
                coords[0] = Integer.parseInt(line.split(" ")[0]);
                coords[1] = Integer.parseInt(line.split(" ")[1]);

                // invert the coords as in document
                push(coords[1], coords[0]);
            }
        } catch (Exception e) {
        }

        // output the grid
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j <= 8; j++) {
                System.out.print(grid[i][j] + " ");
            }
            System.out.println(grid[i][9]);
        }
    }
    /**
     * Pushes the screwdriver on the target coordinates
     *
     * @param x
     * @param y
     */

    private static void push(int x, int y) {

        sw(x, y);
        sw(x - 1, y - 1);
        sw(x - 1, y);
        sw(x - 1, y + 1);
        sw(x + 1, y - 1);
        sw(x + 1, y);
        sw(x + 1, y + 1);
    }
    /**
     * Switches the light
     */
    private static void sw(int x, int y) {

        // check bound
        if (x > 10 || x < 0 || y > 10 || y < 0) {
            return;
        }
        if (grid[x][y] == '.') {
            grid[x][y] = 'X';
        } else {
            grid[x][y] = '.';
        }
    }
}

Advertisements