# roptima v0.1 - Core War optima number calculator in R by John Metcalf # using the bomb-free space method # Usage: $ R -s --file=optima.r --args coresize [modulo] argv <- commandArgs(trailingOnly = TRUE) coresize <- if (length(argv) > 0) as.integer(argv[1]) else 8000 modulo <- if (length(argv) > 1) as.integer(argv[2]) else 1 gcd <- function(a, b) if (b != 0) gcd(b, a %% b) else a steps <- which(sapply(1:(coresize %/% 2), function(x) gcd(x, coresize) == modulo)) scores <- sapply(steps, function(step) { score <- coresize - 1 high <- low <- pos <- step while (pos != 0) { pos <- (pos + step) %% coresize high <- max(high, pos) low <- min(low, pos) score <- score + coresize - high + low - 1 } c(step, score) }) scores <- matrix(scores[, order(scores[2, ])], nrow = 2) cat("step,score\n") for (i in 1:20) { cat(scores[1, i], scores[2, i], sep = ",") cat("\n") }