Skip to content

Main content

Best-Response Dynamics Demonstrator Source Code

Browse the implementation files for Best-Response Dynamics Demonstrator.
tool.ts typescript
// Tool: Best-Response Dynamics Demonstrator

const parseMatrix = (input: unknown): number[][] | null => {
	if (typeof input !== 'string' || input.trim() === '')
		return null;
	try {
		const matrix: unknown = JSON.parse(input);
		if (
			!Array.isArray(matrix) ||
			matrix.length === 0 ||
			matrix.length > 100 ||
			!Array.isArray(matrix[0]) ||
			matrix[0].length === 0 ||
			matrix[0].length > 100
		)
			return null;
		const width = matrix[0].length;
		return matrix.every(
			(row) =>
				Array.isArray(row) &&
				row.length === width &&
				row.every(
					(value) =>
						typeof value === 'number' && Number.isFinite(value)
				)
		)
			? matrix
			: null;
	} catch {
		return null;
	}
};

const parseIndex = (
	input: unknown,
	maximum: number
): number | null => {
	const value = Number(input);
	return Number.isSafeInteger(value) &&
		value >= 0 &&
		value < maximum
		? value
		: null;
};

export const demonstrateBestResponseDynamics = (
	rowPayoffsInput: unknown,
	columnPayoffsInput: unknown,
	initialRowInput: unknown,
	initialColumnInput: unknown,
	iterationCountInput: unknown
): string => {
	const rowPayoffs = parseMatrix(rowPayoffsInput);
	const columnPayoffs = parseMatrix(columnPayoffsInput);
	if (
		rowPayoffs === null ||
		columnPayoffs === null ||
		rowPayoffs.length !== columnPayoffs.length ||
		rowPayoffs[0].length !== columnPayoffs[0].length
	)
		return '';
	const initialRow = parseIndex(
		initialRowInput,
		rowPayoffs.length
	);
	const initialColumn = parseIndex(
		initialColumnInput,
		rowPayoffs[0].length
	);
	const iterationCount = Number(iterationCountInput);
	if (
		initialRow === null ||
		initialColumn === null ||
		!Number.isSafeInteger(iterationCount) ||
		iterationCount < 1 ||
		iterationCount > 10_000
	)
		return '';

	let row = initialRow;
	let column = initialColumn;
	const history = [{ iteration: 0, row, column }];
	const seen = new Map([[`${row},${column}`, 0]]);
	let cycleStart: number | null = null;

	for (
		let iteration = 1;
		iteration <= iterationCount;
		iteration += 1
	) {
		row = rowPayoffs.reduce(
			(best, payoffs, index) =>
				payoffs[column] > rowPayoffs[best][column]
					? index
					: best,
			0
		);
		column = columnPayoffs[row].reduce(
			(best, payoff, index) =>
				payoff > columnPayoffs[row][best] ? index : best,
			0
		);
		history.push({ iteration, row, column });
		const state = `${row},${column}`;
		if (seen.has(state)) {
			cycleStart = seen.get(state)!;
			break;
		}
		seen.set(state, iteration);
	}

	const previous = history.at(-2);
	const equilibrium =
		previous !== undefined &&
		previous.row === row &&
		previous.column === column;

	return JSON.stringify(
		{
			cycleLength:
				cycleStart === null
					? null
					: history.at(-1)!.iteration - cycleStart,
			cycleStart,
			equilibrium,
			finalStrategy: { row, column },
			history
		},
		null,
		2
	);
};

export const Tool: TypeTool = {
	name: 'Best-Response Dynamics Demonstrator',
	slug: 'game-theory/best-response-dynamics',
	intro:
		'Iteratively update two pure strategies to deterministic best responses and expose equilibria or cycles.',
	tool: demonstrateBestResponseDynamics,
	i: [
		{
			example: '[[3,0],[5,1]]',
			label: 'Row Payoffs',
			placeholder: 'JSON row-player payoff matrix',
			render: 'textarea',
			type: 'text',
			value: '[[3,0],[5,1]]'
		},
		{
			example: '[[3,5],[0,1]]',
			label: 'Column Payoffs',
			placeholder: 'JSON column-player payoff matrix',
			render: 'textarea',
			type: 'text',
			value: '[[3,5],[0,1]]'
		},
		{
			example: '0',
			label: 'Initial Row',
			placeholder: 'Zero-based row strategy',
			type: 'number',
			value: 0
		},
		{
			example: '0',
			label: 'Initial Column',
			placeholder: 'Zero-based column strategy',
			type: 'number',
			value: 0
		},
		{
			example: '100',
			label: 'Iterations',
			placeholder: 'Maximum update rounds',
			type: 'number',
			value: 100
		}
	],
	o: [
		{
			example: '{ "equilibrium": true, "history": [] }',
			label: 'Dynamics',
			placeholder: 'Best-response history will appear here...',
			render: 'textarea',
			type: 'text'
		}
	],
	cite: [
		{
			title: 'Best response — Wikipedia',
			url: 'https://en.wikipedia.org/wiki/Best_response'
		}
	]
};

export default Tool;

Description

Browse the implementation files for Best-Response Dynamics Demonstrator.

References

  1. Tool.io on GitHub
  2. Tool.io TypeScript tools library

Similar or alternative tools