input<-read_lines("Day2Sample.txt")
#### Original
#reports<-list()
#for (i in 1:length(input)){
# reports<-c(reports,list(as.numeric(unlist(str_split(input[i]," ")))))}
### Updated after online help/suggestion
reports<-lapply(str_split(input, " "),as.numeric)
Part 1
Uses diff() to see the difference between the elements in the vector.
Then checks to see if they’re all either between 1 & 3 or -1 &
-3
issafe<-function(rprt){
d<-diff(rprt)
if((all(d>=1)&&all(d<=3))||(all(d<=-1)&&all(d>=-3))){
d<-TRUE}else{d<-FALSE}
d}
counts the number of vectors that are safe
part1<-sum(sapply(reports,issafe))
part1
[1] 2
Part 2
check with the problem dampener
probdamp<-function(rpt){
### if it is safe, return TRUE
if(issafe(rpt)){return(TRUE)}
### otherwise, set to false
pd<-FALSE
i<-1
### cycle through removing level one at a time
### stop as soon as either a level is removed that makes the report safe
### or there aren't any left to try to remove
while(!pd&&i<=length(rpt)){
pd<-issafe(rpt[-i])
i<-i+1}
return(pd)}
part2<-sum(sapply(reports,probdamp))
part2
[1] 4
LS0tDQp0aXRsZTogIkRheSAyIE5vdGVib29rIg0Kb3V0cHV0OiBodG1sX25vdGVib29rDQotLS0NCg0KYGBge3Igc2V0dXAsIGluY2x1ZGU9RkFMU0V9DQpsaWJyYXJ5KHJlc2hhcGUyKQ0KbGlicmFyeShrbml0cikNCmxpYnJhcnkoZHBseXIpDQpsaWJyYXJ5KHN0cmluZ3IpDQpsaWJyYXJ5KHRpZHl2ZXJzZSkNCmxpYnJhcnkocmVhZHIpDQpsaWJyYXJ5KGNvbGxlY3Rpb25zKQ0Kb3B0aW9ucyhzY2lwZW4gPSA5OTkpDQpgYGANCg0KYGBge3J9DQppbnB1dDwtcmVhZF9saW5lcygiRGF5MlNhbXBsZS50eHQiKQ0KDQoNCiMjIyMgT3JpZ2luYWwNCiNyZXBvcnRzPC1saXN0KCkNCiNmb3IgKGkgaW4gMTpsZW5ndGgoaW5wdXQpKXsNCiMgIHJlcG9ydHM8LWMocmVwb3J0cyxsaXN0KGFzLm51bWVyaWModW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