/** This program plays the game Mastermind, specifically the variant at: https://www.geogebra.org/m/urrmrv2f Its algorithm is very simple for a computer (but not for a human.) 1.) Make a list of all possible plays. 2.) Choose one play at random and play it. 3.) Using the feedback your opponent gives you, eliminate all of the plays from the list that can't match that feedback. Repeat until done. This is intended to be used interactively, but if you just want to watch it play, it will automatically pick a random secret pattern for you and play for you. Just hit the "enter" key every time and the computer will provide the correct defaults for you. */ // The possible colors. You can change these to whatever you want, including // full names. You can also use more or fewer colors and everything will // just work right. colors=["Red", "Orange", "Yellow", "Green", "Cyan", "Blue", "Fuchsia", "Gray"] // You can change from the normal 4-peg game to more or fewer pegs. numPegs = 4 // Create an array with all possible plays. This assumes each color can only // appear once in the code. opts = new array for combo = colors.combinations[numPegs] for p = combo.permute[] opts.push[p] // Pick a target play at random. target = random[opts] println["Suggest:" + target] // This is a function that will be passed to "select". It just returns true // for each move that matches the specified result pegs. sfunc = {|move, data| [target, result] = data rank[move, target] == result } // The main loop. do { println["Possible solutions remaining: " + length[opts]] move = opts.removeRandom[] // Choose a move at random [red,black] = rank[move,target] // Get default results for user. result = eval[input["Move is $move",[["Red: ", red], ["Black: ", black]]]] // Now just go through the remaining possible solutions and return only // the ones that could have matching results. opts = array[select[opts, sfunc, [move, result]]] } while result@0 != numPegs and length[opts] > 1 if result@0 == numPegs // All red? We guessed right last time! println["Guessed the solution correctly!"] else // Otherwise, we know what the solution will be. println["Solution is " + opts@0] /** This function determines how good a move was at matching the specified target. It returns the number of red and black pegs as the array [red, black] */ rank[move, target] := { red = 0 black = 0 targetCopy = target.shallowCopy[] // First, count total number of matches in any position. As a match is // found in any position, remove it from the list so it's not counted twice. for mpiece = move if targetCopy.removeValue[mpiece] // Returns true if a piece was removed black = black + 1 // Now count pieces in the correct positions. For each one found, remove // one from the "black" count and add one to the "red" count. for i = 0 to length[target]-1 if move@i == target@i { black = black - 1 red = red + 1 } return [red,black] }