Published
Edited
Sep 3, 2020
Insert cell
md`# Prisoner's Dilemma`
Insert cell
function play(x,y){
var x_score
var y_score
if (x && y){
//cooperation
x_score = 3
y_score = 3
}
else if (x && !y){
//sucker
x_score = 0
y_score = 5
}
else if (!x & y){
//snitch
x_score = 5
y_score = 0
}
else if (!x && !y){
//losers
x_score = 1
y_score = 1
}
return x_score+y_score
}
Insert cell
function optimize_for_y({str="",x_trust=1.0, y_trust=1.0, x_decision=true}={}){
var x_decision;
var y_decision;
if (str=="x"){
return x_decision = Math.random() >= 0.5;
}
if (str=="y"){
//console.log(x_trust)
return y_decision = ((x_trust >= 0.5) == x_decision)
}
}
Insert cell
function game(decision_function){
var num_plays = 10
var score
var total_score = 0
var i
for (i=0; i < num_plays; i++){
var x_reported_decision = decision_function({str:"x"});
var x_trust = Math.random();
var y_decision = decision_function({str:"y", x_trust:x_trust , x_decision:x_reported_decision});
//play with x_decision = x_trust XNOR x_reported_decision
score = play(x_reported_decision==(x_trust >= 0.5), y_decision);
total_score += score;
}
return total_score;
}
Insert cell
game(optimize_for_y)
Insert cell
function create_data(n_runs){
var i;
var counts = {};
for (i=0; i < n_runs; i++){
var result = game(optimize_for_y);
if (!(result in counts)){
counts[result]=1;
} else {
counts[result]++;
}
}
var counts_list = [];
var key2dict;
for (var key in counts){
key2dict = {'name': key, 'value':counts[key]}
counts_list.push(key2dict);
}
return counts_list;
}
Insert cell
data = create_data(100)
Insert cell
height = 500;
Insert cell
chart
Insert cell
import {chart} with {data, height} from "@d3/bar-chart"
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more