Reputation: 183
I'm currently learning PHP (beginner to programming) and am stuck trying to find a solution for the following basic problem...
It's a "bomb defuse" game with the following rules applying to only the next wire cut:
If you cut a white cable you can't cut white or black cable. If you cut a red cable you have to cut a green one If you cut a black cable it is not allowed to cut a white, green or orange one If you cut a orange cable you should cut a red or black one If you cut a green one you have to cut a orange or white one If you cut a purple cable you can't cut a purple, green, orange or white cable
An input would be as follows...
white, red, green, white
So I arranged this data into an associative array with valid next cuts. I turned the input string into an array. How can I use this associative array to check if the next wire cut in the input array is a valid cut?
function bombDefuseValidation($inputString) {
$input = $inputString;
$inputExplodedArray = explode(", ", $input);
//$inputExplodedArray = array('white', 'red', 'green', 'white');
$inputExplodedArrayLength = count($inputExplodedArray);
//Valid next cuts
$rules = array(
"white" => "red, green, orange, purple",
"red" => "green",
"black" => "red, purple, black",
"orange" => "red, black",
"green" => "orange, white",
"purple" => "red, black"
);
}
bombDefuseValidation('white, red, green, white');
I need a way to take the inputs, such as 'white', check if the following input ('red') exists as a value in the 'white' key of the associative array, if it does, move on to the next input and keep checking. If they all match up to a value in the corresponding key, the bomb is defused. If one doesnt, "BOOM".
Thanks for any help!
Upvotes: 0
Views: 76
Reputation: 177
If you use Array()
, it would be much easier!
function bombDefuseValidation($inputArray) {
$inputExplodedArrayLength = count($inputArray);
//Valid next cuts
$rules = array(
"white" => array("red", "green", "orange", "purple"),
"red" => array("green"),
"black" => array("red", "purple", "black"),
"orange" => array("red", "black"),
"green" => array("orange", "white"),
"purple" => array("red", "black")
);
for ($i = 0; $i < $inputExplodedArrayLength-1 ; $i++) {
$temp = $rules[$inputArray[$i]];
if(!in_array($inputArray[$i+1], $temp)) {
$num = $i + 2;
print("Invalid Input no. {$num}");
return -1;
}
}
print("Valid Input");
return 0;
}
bombDefuseValidation(Array('white', 'red', 'green', 'white'));
Upvotes: 1