Skip to content

Instantly share code, notes, and snippets.

@wmjd
Last active April 18, 2019 22:32
Show Gist options
  • Save wmjd/da6eeb32c99ddcff74541c185d9f6134 to your computer and use it in GitHub Desktop.
Save wmjd/da6eeb32c99ddcff74541c185d9f6134 to your computer and use it in GitHub Desktop.
//see if sequence of nums is in increasing order, but seq is allowed to decrease once.
//some shared stuff first:
var arr = [0,1,2,3,5,4,5,7];
//currently these two functions are only used in v1 (v2-3 prints value of entire function)
const s = () => console.log("success");
const f = () => console.log("failure");
//v1 imperative style
function exeImperative(){
let dec = 0;
for(var i = 0; i < arr.length -1; i++){
if(arr[i+1] < arr[i]){
if(++dec > 1){break ;}
}
}
if(i === arr.length -1){
s();
}else{
f();
}
}
exeImperative();
//v2 transformed to functional style: recursion, no (re)assignments
const foo = function(i, dec){
if(dec > 1){return "fail"}
if(i === arr.length){return "succeed"}
if(arr[i+1]<arr[i]){return foo(i+1, dec+1)}
else{return foo(i+1, dec)}
};
console.log(foo(0,0));
//v3 transformed to single statement : )
const bar = (i, dec) =>
(dec > 1) ? "fail" :
(i === arr.length) ? "succeed" :
bar(i+1, (arr[i+1] < arr[i]) ? dec+1 : dec);
console.log(bar(0,0));
/* v4
this is a soln to a slightly different problem.
for example, [0,1,2,0,1] only decreases once but removing one elt won't make strictly increasing
*/
function isIncreasingIfRemoveOne(next, prev, dec){
if(dec > 1){
console.log(next,prev,dec);
return "reject" ;
}
if(next === arr.length){
return "accept" ;
}
if(arr[next] < arr[prev]){
return isIncreasingIfRemoveOne(next+1, prev, dec+1) ;
}else{
return isIncreasingIfRemoveOne(next+1, next, dec) ;
}
}
console.log(isIncreasingIfRemoveOne(1,0,0));
//current favorite : )
const isIncIfRemOne = (next, prev, dec) =>
(dec > 1) ?
"reject" :
(arr.length === next) ?
"accept" :
(arr[next] < arr[prev]) ?
isIncIfRemOne(next+1, prev, dec+1) :
isIncIfRemOne(next+1, next, dec) ;
console.log(isIncIfRemOne(1,0,0));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment