Menu
CoddyTech

פרויקט סיום: הסבת חיישן

שיעור 48 מתוך 48 בקורס Ruby למפתחי R של Coddy.

challenge icon

אתגר

קל

התאימו את תוכנית הייחוס. ‏Above(limit)#accept?(n) מקבלת את n אם הוא גדול מ־limit בלבד. ‏Sensor(policy)#feed(token) מנתחת סימן אופציונלי ואחריו ספרה אחת או יותר מספרות ASCII, ללא רווחים או תווים אחרים, ומקבלת רק מספרים שלמים מ־-1000000 עד 1000000. אסימונים לא תקינים מגדילים את invalid; אסימונים תקינים שהתקבלו על ידי המדיניות מגדילים את accepted ומוסיפים ל־total. אסימונים תקינים שנדחו אינם משנים אף מונה. ‏summary מחזירה את accepted, ‏invalid ו־total כשהם מופרדים ברווחים. השורה הראשונה בקלט היא limit; כל שורה שנותרה היא אסימון אחד, לאחר הסרת סיום השורה. כל שלושת המונים מתחילים באפס. אובייקטים של מדיניות מותאמת אישית צריכים לעבוד.

החזירו טקסט מתוך solve(input) בלי להדפיס. מנהל ההתקן הנעול מדפיס את הטקסט שהוחזר עם תו ירידת שורה אחרון אחד, ובודק בנפרד את ממשקי ה־API הציבוריים הנדרשים.

הקוד שלכם נמצא בקבצים exercise.rb, above.rb, sensor.rb. הקובץ main.rb מכיל את קוד הקלט/פלט שסופק, ואי אפשר לערוך אותו.

תוכנית ייחוס ב־R. התאימו את ההתנהגות שלה באמצעות ממשקי ה־API הנדרשים של Ruby.

normalize <- function(text) {
  negative <- startsWith(text,"-")
  text <- sub("^[+-]","",text)
  text <- sub("^0+","",text)
  if(!nzchar(text)) return("0")
  if(negative) paste0("-",text) else text
}
compare_abs <- function(a,b) {
  if(nchar(a)!=nchar(b)) return(sign(nchar(a)-nchar(b)))
  ad <- utf8ToInt(a); bd <- utf8ToInt(b)
  different <- which(ad!=bd)
  if(!length(different)) 0 else sign(ad[different[1]]-bd[different[1]])
}
add_abs <- function(a,b) {
  ad <- rev(utf8ToInt(a)-48L); bd <- rev(utf8ToInt(b)-48L)
  size <- max(length(ad),length(bd))
  length(ad) <- size; length(bd) <- size
  ad[is.na(ad)] <- 0L; bd[is.na(bd)] <- 0L
  out <- integer(size+1L); carry <- 0L
  for(i in seq_len(size)) {
    value <- ad[i]+bd[i]+carry
    out[i] <- value %% 10L
    carry <- as.integer(value>=10L)
  }
  out[size+1L] <- carry
  normalize(paste(rev(out),collapse=""))
}
subtract_abs <- function(a,b) {
  ad <- rev(utf8ToInt(a)-48L); bd <- rev(utf8ToInt(b)-48L)
  length(bd) <- length(ad); bd[is.na(bd)] <- 0L
  out <- integer(length(ad)); borrow <- 0L
  for(i in seq_along(ad)) {
    value <- ad[i]-bd[i]-borrow
    borrow <- as.integer(value<0L)
    out[i] <- if(value<0L) value+10L else value
  }
  normalize(paste(rev(out),collapse=""))
}
add_decimal <- function(a,b) {
  a <- normalize(a); b <- normalize(b)
  an <- startsWith(a,"-"); bn <- startsWith(b,"-")
  av <- sub("^-","",a); bv <- sub("^-","",b)
  if(an==bn) {
    value <- add_abs(av,bv)
    return(if(an && value!="0") paste0("-",value) else value)
  }
  order <- compare_abs(av,bv)
  if(order==0) return("0")
  value <- if(order>0) subtract_abs(av,bv) else subtract_abs(bv,av)
  negative <- if(order>0) an else bn
  if(negative) paste0("-",value) else value
}

read_raw_lines <- function() {
  connection <- file("stdin","rb")
  on.exit(close(connection))
  bytes <- readBin(connection,"raw",n=.Machine$integer.max)
  lines <- list(); start <- 1L
  for(i in seq_along(bytes)) if(bytes[i]==as.raw(10)) {
    row <- if(i>start) bytes[seq.int(start,i-1L)] else raw()
    if(length(row) && tail(row,1)==as.raw(13)) row <- head(row,-1L)
    lines[[length(lines)+1L]] <- row
    start <- i+1L
  }
  if(start<=length(bytes)) {
    row <- bytes[seq.int(start,length(bytes))]
    if(length(row) && tail(row,1)==as.raw(13)) row <- head(row,-1L)
    lines[[length(lines)+1L]] <- row
  }
  lines
}
parse_token <- function(token) {
  bytes <- as.integer(token); index <- 1L; negative <- FALSE
  if(length(bytes) && bytes[1] %in% c(43L,45L)) {
    negative <- bytes[1]==45L; index <- 2L
  }
  if(index>length(bytes)) return(NULL)
  value <- 0L
  for(i in seq.int(index,length(bytes))) {
    digit <- bytes[i]-48L
    if(digit<0L || digit>9L) return(NULL)
    value <- value*10L+digit
    if(value>1000000L) return(NULL)
  }
  if(negative) -value else value
}
above <- function(limit) {
  force(limit)
  function(value) value>limit
}
new_sensor <- function(policy) {
  force(policy)
  accepted <- "0"; invalid <- "0"; total <- "0"
  list(
    feed=function(token) {
      value <- parse_token(token)
      if(is.null(value)) invalid <<- add_decimal(invalid,"1")
      else if(policy(value)) {
        accepted <<- add_decimal(accepted,"1")
        total <<- add_decimal(total,as.character(value))
      }
      invisible(NULL)
    },
    summary=function() paste(accepted,invalid,total)
  )
}
lines <- read_raw_lines()
sensor <- new_sensor(above(as.numeric(rawToChar(lines[[1]]))))
for(token in lines[-1]) sensor$feed(token)
cat(sensor$summary(),"\n",sep="")

נסו בעצמכם

require_relative 'exercise'
require_relative 'above'
require_relative 'sensor'
def check(value)
  raise 'Public API check failed' unless value
end
check(Above.new(4).accept?(5) && !Above.new(4).accept?(4))
policy = Object.new
def policy.accept?(n); n.even?; end
s = Sensor.new(policy)
["2", "-4", "3", "x", "4\n", "1000001"].each { |t| s.feed(t) }
check(s.summary == "2 3 -2" && s.summary == "2 3 -2")

puts solve(STDIN.read)

כל השיעורים ביחידה Ruby למפתחי R

תרגלו בעצמכם: קומפיילר Ruby אונליין