# MATH-03 / Base R only. Run: Rscript --vanilla --encoding=UTF-8 math03-reproduce.R
if(.Platform$OS.type=="windows") invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
script_arg <- grep("^--file=",commandArgs(),value=TRUE)
root <- if(length(script_arg)) dirname(normalizePath(sub("^--file=","",script_arg[1]))) else getwd()
penguins <- read.csv(file.path(root,"\uc2e4\uc81c\ub370\uc774\ud130","penguins.csv"),na.strings=c("","NA"),fileEncoding="UTF-8-BOM")
missing <- penguins$row_id[is.na(penguins$body_mass_g)]
known <- penguins[!is.na(penguins$body_mass_g),]
U <- known$row_id
A <- known$row_id[known$species=="Adelie"]
B <- known$row_id[known$body_mass_g>=4000]
both <- intersect(A,B); a_only <- setdiff(A,B); b_only <- setdiff(B,A)
neither <- setdiff(U,union(A,B))
stopifnot(setequal(setdiff(U,intersect(A,B)),union(setdiff(U,A),setdiff(U,B))),
          setequal(setdiff(U,union(A,B)),intersect(setdiff(U,A),setdiff(U,B))),
          length(union(A,B))==length(A)+length(B)-length(both),
          identical(missing,c(4L,272L)),
          all(c(length(both),length(a_only),length(b_only),length(neither))==c(39,112,138,53)))
gentoo_bad <- known$row_id[known$species=="Gentoo" & known$body_mass_g<4000]
empty <- known[known$body_mass_g>=7000,]
stopifnot(min(gentoo_bad)==193L,nrow(empty)==0L,
          all(empty$body_mass_g>=4000),!any(empty$body_mass_g>=4000))
metrics <- c(rows=nrow(penguins),universe=length(U),A=length(A),B=length(B),
             both=length(both),aOnly=length(a_only),bOnly=length(b_only),neither=length(neither),
             union=length(union(A,B)),exactlyOne=length(a_only)+length(b_only),
             firstPimpliesQCounterexample=min(a_only),firstQimpliesPCounterexample=min(b_only),
             gentooCounterexampleRow=min(gentoo_bad))
write.csv(data.frame(metric=names(metrics),value=as.numeric(metrics)),
          file.path(root,"math03-results-R.csv"),row.names=FALSE)
print(metrics)
