Here is the scenario, I was asked the following question at an interview and I managed to solve part of it, but I had some trouble with the second part of the question (and I don't even know if I solved the first part correctly, I just came up with what I could code best under the circumstances). So let me introduce the problem:
Consider the following 2-player game played on a string of dashes and plusses. If, at the beginning of your turn, the string doesn't contain a pair of adjacent dashes, you win! Otherwise, choose any pair of adjacent dashes “--
” in the string and replace it with “++
”. We take turns until someone wins.
Example game: -+-----+
--> -+-++--+
--> -+-+++++
(game is over).
Write a function listMoves()
which takes a position string as an argument and returns a list of all the valid moves.
Examples:
listMoves("") == []
listMoves("--+---+") == ["+++---+", "--+++-+", "--+-+++"]
My solution to this (in JavaScript) was:
var listMoves = function(arg) {
if (arg === null) return;
if (arg === "") {
return [];
}
var result = [];
var temp = '';
var string = [];
for (var i=0; i<arg.length; i++) {
if (temp == '-' && arg[i] == '-') {
string = arg.split('');
string[i-1] = '+';
string[i] = '+';
console.log(string);
result.push(string);
} else if (arg[i] == '-') {
temp = arg[i];
} else if (arg[i] == '+' && temp == '-') {
temp = '';
}
}
return result;
}
The second part of the question was:
In best play, each position is either a win or a loss for the player to move. Write a function isWin(position)
that returns true just when the position is a win for the player to move.
Examples:
isWin("") == true
isWin("---+") == false
isWin("----") == true
isWin("--+----+--+---++--") == ???
I managed to fathom that I needed a recursive algorithm for this, and that I could use the function I created for question #1 (hence why I included it).
I couldn't, however, put my thoughts into code.
For future reference, could someone show me how they would go about solving a problem like this?
edit#1 (added my attempt during the interview):
var isWin = function (position) {
if (position === null) return;
if (position === "") return true;
var possibleMoves = listMoves(position);
var win;
if (possibleMoves.length < 1) {
win = true;
} else if (possibleMoves.length == 1) {
win = false;
} else {
for (move in possibleMoves) {
isWin(move);
}
}
return win;
}