Skip to content

Instantly share code, notes, and snippets.

@MmmarinaMarinova
Forked from anonymous/Collect the coins
Created January 23, 2017 15:55
Show Gist options
  • Save MmmarinaMarinova/e2198540258e6cebb0df5443436e48bf to your computer and use it in GitHub Desktop.
Save MmmarinaMarinova/e2198540258e6cebb0df5443436e48bf to your computer and use it in GitHub Desktop.
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Created by Marina on 23.01.2017 г..
*/
public class CollectTheCoins {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> board = new ArrayList<>();
//get the matrix
for (int row = 0; row < 4; row++) {
String[] input = scanner.nextLine().split("");
for (int col = 0; col < input.length; col++) {
String nextLine = input[col];
board.add(row, nextLine);
}
}
String[] command = scanner.nextLine().split("");
//some variables for moving on the board
int currRow = 0;
int currCol = 0;
//int pos=0;
int wallsHit = 0;
int coinsCollected = 0;
//try to catch the exception, otherwise move around board
for (int pos = 0; pos < command.length; pos++) {
try {
if (command[pos].equals("V")) {
currRow++;
} else if (command[pos].equals(">")) {
currCol++;
} else if (command[pos].equals("^")) {
currRow--;
} else if (command[pos].equals("<")) {
currCol--;
}
} catch (ArrayIndexOutOfBoundsException e) {
wallsHit++;
}
//check if there is a coin to collect
char[] nextLine = board.get(currRow).toCharArray();
if (nextLine[currCol] == '$') {
coinsCollected++;
}
}
//print result
System.out.printf("Coins collected: %d", coinsCollected);
System.out.printf("Walls hit: %d", wallsHit);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment