If you run agendaSearch.js you should get the same output as output.txt
I reverse-engineered the optimisations made in the mark scheme solution. They were:
- If a cheaper path exists to a node in the agenda already, don't add the more expensive path to the agenda. If you find a cheaper path to a node than you already have in the agenda, remove the more expensive path.
- Don't expand nodes which were already expanded, even if you reach them through a different path. In UCS, the path to every node expanded so far should already be optimal.
The algorithm works even without those two optimisations, but the agenda size gets quite big - not an issue for a computer on such a small problem, possibly a problem for a computer on a much larger problem, definitely a problem for someone doing this in an exam.
To turn off the simplifying assumptions:
- To turn off (1), comment out the following:
// Reduces agenda size by not adding nodes to which there is a cheaper path.
// This works by picking the first encountered state for a particular node,
// which because the agenda is sorted will be the cheapest path to that node.
const nodeToAgendaItem = new Map();
for (const item of agenda) {
if (!nodeToAgendaItem.has(item.node)) {
nodeToAgendaItem.set(item.node, item);
}
}
// We have to re-sort the agenda here because the Map() implementation might have hashed
// the entries in a different order to what was on the agenda before
agenda = [...nodeToAgendaItem.values()].sort(byCost);
- To turn off (2), replace
const visitedNodeSet = new Set(globalVisitedNodes);
withconst visitedNodeSet = new Set();
Observe how the agenda changes (but the chosen path and cost remains the same).