Menu
CoddyTech

活动调度器

本课属于 Coddy R 学习旅程的“面向对象编程”单元。第 56 课,共 57 课。

challenge icon

挑战

困难

用两个文件构建一个事件日程安排器。

  • Event.R:包含字段 title、day、start、end(小时)的 S3 类 event。编写 new_event();编写 validate_event(),当条件不满足时分别以 day must be from 1 to 31 或 hours must be within 0 to 24 and start before end 作为错误信息停止运行;编写辅助函数 event(title, day, start, end),将文本参数转换为数字;编写 format.event(),返回 day 3 09-11 standup;还要编写 overlaps(a, b),当两个事件在同一天且各自的开始时间都早于另一个事件的结束时间时,返回 TRUE。
  • Scheduler.R:make_scheduler() 将事件保存在私有作用域中,并返回 add(e)。同一天有同名事件时,返回 duplicate;与已有事件重叠时,返回 conflicts with review;否则返回 added。还要返回 agenda(),按日期、开始时间和标题排序并格式化事件;以及 busiest_day(),按总小时数返回 busiest: day 3 (4 hours)(总小时数相同时选择较早的一天),没有事件时返回 no events。

使用 call. = FALSE。提供的代码会读取格式为 title,day,start,end 的行,为每行输出回复,然后输出日程安排和最忙的一天。

将代码写在 Event.R 和 Scheduler.R 中。main.R 包含提供的输入/输出代码,不能修改。

亲手试试

source("Event.R")
source("Scheduler.R")

# 提供的输入输出代码:保持原样。
input <- suppressWarnings(readLines(file("stdin")))
s <- make_scheduler()
for (line in input) {
  p <- strsplit(line, ",")[[1]]
  reply <- tryCatch(s$add(event(p[1], p[2], p[3], p[4])), error = function(e) paste("invalid:", conditionMessage(e)))
  cat(p[1], ": ", reply, "\n", sep = "")
}
cat("agenda:\n")
for (l in s$agenda()) cat("  ", l, "\n", sep = "")
cat(s$busiest_day(), "\n", sep = "")

面向对象编程中的所有课

自己练习: R 在线编译器