Skip to content

Instantly share code, notes, and snippets.

@danman01
Last active February 8, 2018 21:55
Show Gist options
  • Save danman01/1be766b4e6828e089632f02457cf4498 to your computer and use it in GitHub Desktop.
Save danman01/1be766b4e6828e089632f02457cf4498 to your computer and use it in GitHub Desktop.
ripped books: find min/max pages that an array of ripped pages could represent.
Sure, there's a way to use reduce and do this all in one line. This v2 is 477 bytes as is.
test data:
const sample_input = [[7,8,100,101,222,223],
[ 2,3,88,89,90,103,177 ],
[ 2,3,6,7,10,11 ],
[ 1 ],
[ 1,2 ]]
const sample_output = [ "4/5","5/6","3/6","1/1","1/2" ]
and test with:
console.log(app(sample_input).toString() === sample_output.toString() ? "success" : "fail")
const app = function(input){
const minMaxPages=function(ripped){
let min=0
let max=0
let eos=0
let oes=0
for(let i=0;i<ripped.length;){
min++
max++
if(ripped[i-2]!==undefined && ripped[i-2]===ripped[i-1]-1 && ripped[i]===ripped[i-1]+1){
max-=1
}
if(ripped[i+1]!==undefined && ripped[i+1]===ripped[i]+1){
ripped[i]%2===0?eos+=1:oes+=1
max+=1
i+=1
}
i+=1
}
eos>oes?(min+=oes,max-=oes):(min+-eos,max-=eos)
return `${min}/${max}`
}
let out=[]
for(let i = 0; i < input.length; i++) {
let ripped=input[i]
out.push(minMaxPages(ripped))
}
return out
}
const mnMx=(ripd)=>{
let min=0
let max=0
let eos=0
let oes=0
for(let i=0;i<ripd.length;){
min++
max++
if(ripd[i-2]!==undefined && ripd[i-2]===ripd[i-1]-1 && ripd[i]===ripd[i-1]+1){
max-=1
}
if(ripd[i+1]!==undefined && ripd[i+1]===ripd[i]+1){
ripd[i]%2===0?eos+=1:oes+=1
max+=1
i+=1
}
i+=1
}
eos>oes?(min+=oes,max-=oes):(min+-eos,max-=eos)
return `${min}/${max}`
}
const app=(pgs)=>pgs.map((ripd)=>mnMx(ripd))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment