Wolves with a Collective Memory
A Wolf pack in R
The idea of this wolf pack is that it keeps in memory who's alive or dead, check what the dead wolves and the alive wolves used as attacks and change the choice probability accordingly.
Here is the R code:
infile <- file("stdin")
open(infile)
repeat{
input <- readLines(infile,1)
type <- substr(input,1,1)
id <- substr(input,2,3)
if(nchar(input)>3){
info <- substr(input,4,nchar(input))
}else{
info <- NULL
}
attack <- function(id,info){
if(info%in%c("B","L")){choice <- "S"}
if(info=="S"){choice <- "P"}
if(info=="W"){
if(exists("memory")){
dead <- memory$ID[memory$Status=="Dead"]
veteran <- memory[memory$Attack!="" & !is.na(memory$Attack), ]
if(nrow(veteran[!is.na(veteran[,1]),])>0){
deadvet <- table(factor(veteran$Attack[veteran$ID%in%dead],levels=c("R","P","S","")))
livevet <- table(factor(veteran$Attack[!veteran$ID%in%dead],levels=c("R","P","S","")))
probR <- (1+livevet['R'])/(1+livevet['R']+deadvet['R'])
probS <- (1+livevet['S'])/(1+livevet['S']+deadvet['S'])
probP <- (1+livevet['P'])/(1+livevet['P']+deadvet['P'])
choice <- sample(c("S","P","R"),1,prob=c(probS,probP,probR))
memory <- rbind(memory, data.frame(ID=id, Status="Alive", Attack=choice))
}else{
choice <- sample(c("S","P","R"),1)
memory <- rbind(memory, data.frame(ID=id, Status="Alive", Attack=choice))
}
}else{
choice <- sample(c("S","P","R"),1)
memory <- data.frame(ID=id, Status="Alive", Attack=choice)
}
}
paste(choice,id,sep="")
}
move <- function(id,info){
choice <- "H"
paste(choice,id,sep="")
}
initialize <- function(id){
if(exists("memory")){
memory <- rbind(memory,data.frame(ID=id,Status="Alive",Attack=""))
}else{
memory <- data.frame(ID=id,Status="Alive",Attack="")
}
confirmed_dead <- memory$ID[memory$Status=="Dead"]
last_seen <- memory[!memory$ID%in%confirmed_dead,]
last_seen <- last_seen[last_seen$Attack=="",]
lid <- table(last_seen$ID)
turns <- max(lid)
dead <- lid[lid<(turns-1)]
if(length(dead)>0){
dead_id <- names(dead)
for(i in dead_id){
memory <- rbind(memory, data.frame(ID=i, Status="Dead", Attack=""))
}
}
paste("K",id,sep="")
}
result <- switch(type,"A"=attack(id,info),"M"= move(id,info),"S"=initialize(id))
cat(result,"\n",sep="")
flush(stdout())
}
It uses @ProgrammerDan wrapper (thank you!), with WolfCollectiveMemory as custom name and "Rscript WolfCollectiveMemory.R" as invocation.