Skip to content

Instantly share code, notes, and snippets.

@jmarhee
Created March 22, 2023 02:20
Show Gist options
  • Save jmarhee/1cefbb61cc7c8be5952782f5c2ec8ed2 to your computer and use it in GitHub Desktop.
Save jmarhee/1cefbb61cc7c8be5952782f5c2ec8ed2 to your computer and use it in GitHub Desktop.
#include <stdio.h>
// The payoffs for each player in the game
int player1_payoff[2][2] = {{3, 0}, {5, 1}};
int player2_payoff[2][2] = {{3, 5}, {0, 1}};
// Function to calculate the Nash equilibrium
void calculate_nash_equilibrium() {
int row, col;
// Find the maximum payoff for player 1 in each row
for (row = 0; row < 2; row++) {
int max_payoff = player1_payoff[row][0];
for (col = 1; col < 2; col++) {
if (player1_payoff[row][col] > max_payoff) {
max_payoff = player1_payoff[row][col];
}
}
// Check if the maximum payoff is unique
int count = 0;
for (col = 0; col < 2; col++) {
if (player1_payoff[row][col] == max_payoff) {
count++;
}
}
// If the maximum payoff is unique, it's a Nash equilibrium
if (count == 1) {
printf("Nash equilibrium: (%d, %d)\n", row+1, col+1);
}
}
}
int main() {
// Print out the payoffs for each player
printf("Player 1 payoff matrix:\n");
printf(" 1 2\n");
printf("1 %d %d\n", player1_payoff[0][0], player1_payoff[0][1]);
printf("2 %d %d\n", player1_payoff[1][0], player1_payoff[1][1]);
printf("Player 2 payoff matrix:\n");
printf(" 1 2\n");
printf("1 %d %d\n", player2_payoff[0][0], player2_payoff[0][1]);
printf("2 %d %d\n", player2_payoff[1][0], player2_payoff[1][1]);
// Calculate and print the Nash equilibrium
printf("Calculating Nash equilibrium...\n");
calculate_nash_equilibrium();
return 0;
}

This is an example of a two-player game in C, along with code to calculate and demonstrate its Nash equilibrium.

In this example, we define a two-player game with payoffs given by the player1_payoff and player2_payoff matrices. We then define a function calculate_nash_equilibrium that calculates the Nash equilibrium of the game. This function iterates over each row of player1_payoff and finds the maximum payoff for player 1 in that row. If the maximum payoff is unique (i.e., there is only one column where player 1 receives the maximum payoff), then that row and column define a Nash equilibrium.

In the main function, we print out the payoffs for each player and then call calculate_nash_equilibrium to calculate and print the Nash equilibrium.

Note that this example game has a unique Nash equilibrium at (2,2), where both players choose the second option.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment