Skip to content

Instantly share code, notes, and snippets.

@mmloveaa
Created April 11, 2016 16:08
Show Gist options
  • Save mmloveaa/1fc779111b6295f93914061b718fdad6 to your computer and use it in GitHub Desktop.
Save mmloveaa/1fc779111b6295f93914061b718fdad6 to your computer and use it in GitHub Desktop.
4-11 diff problems
function scoreHand(cards) {
var aces = 0;
var score = cards.reduce(function(sum,card) {
var value = 10;
if(card.match(/\d/)) {
value = parseInt(card);
} else if(card === "A") {
value = 11;
aces++;
}
return sum + value;
}, 0);
// aces >=0
// score > 21
while(score > 21 && aces--) {
score -= 10;
// aces --;
}
// aces?
return score
}
scoreHand(["5", "4", "3", "2", "A", "K"]);
function missingWords(s, t) {
var missing = [];
var a = s. split(' ');
var b = t.split(' ');
for(var i=0, j=0; i < a.length; i++){
if(a[i] !== b[j]) {
missing.push(a[i]);
} else {
j++;
}
}
return missing;
}
missingWords('I am using hackerrank to improve programming', 'am hackerrank to improve')
// method 2
// function missingWords(s, t) {
// var missing = [];
// var a = s. split(' ');
// var b = t.split(' ');
// a.forEach((word, i) => {
// if(word !== b[i- missing.length]) {
// missing.push(word);
// }
// });
// return missing;
// }
// method 3
// function missingWords(x, y) {
// var a=x.split(' '), s=y.split(' '), m=[];
// for(var i=0;i<a.length;i++)
// if(a[i]!==s[i-m.length])
// m.push(a[i]);
// return m;
// }
// missingWords('I am using hackerrank to improve programming', 'am hackerrank to improve')
function closestNumbers(arr) {
arr.sort((a,b) => a-b );
var smallestGap = arr.reduce(function(gap, num , i) {
var thisGap = arr[i+1] - num;
return thisGap < gap ? thisGap : gap;
// num - arr[i+1]
}, infinity);
var pairs = [];
arr.forEach(function(num,i) {
var thisGap = arr[i+1] - num;
if(thisGap === smallestGap) {
pairs.push(num, arr[i+1]);
}
});
return pairs.join(' ');
}
closestNumbers([16,3,10,7,13,-4,5])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment