Created
March 1, 2018 16:57
-
-
Save jonurry/a94a038272e4661fcc1b1e4cb11f98a3 to your computer and use it in GitHub Desktop.
7.1 Measuring a robot (Eloquent JavaScript Solutions)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function runRobot(state, robot, memory) { | |
for (let turn = 0;; turn++) { | |
if (state.parcels.length == 0) { | |
return turn; | |
} | |
let action = robot(state, memory); | |
state = state.move(action.direction); | |
memory = action.memory; | |
} | |
} | |
function compareRobots(robot1, memory1, robot2, memory2) { | |
let totalIterations = 100; | |
let robot1Results = []; | |
let robot2Results = []; | |
for (let i = 0; i < totalIterations; i++) { | |
let state = VillageState.random(); | |
robot1Results.push(runRobot(state, robot1, memory1)); | |
robot2Results.push(runRobot(state, robot2, memory2)); | |
} | |
let r1a = Math.floor(robot1Results.reduce((a, c) => a + c, 0) / robot1Results.length + 0.5); | |
let r2a = Math.floor(robot2Results.reduce((a, c) => a + c, 0) / robot2Results.length + 0.5); | |
console.log(`Route Robot completed in an avarage of ${r1a} turns.`); | |
console.log(`Goal Oriented Robot completed in an avarage of ${r2a} turns.`); | |
} | |
compareRobots(routeRobot, [], goalOrientedRobot, []); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hints
You’ll have to write a variant of the
runRobot
function that, instead of logging the events to the console, returns the number of steps the robot took to complete the task.Your measurement function can then, in a loop, generate new states and count the steps each of the robots takes. When it has generated enough measurements, it can use
console.log
to output the average for each robot, which is the total amount of steps taken divided by the number of measurements.