freecodecamp: Introduction to the Intermediate Algorithm Scripting Challenges
code to go far, remember passed snip
Sum All Numbers in a Range
" let r=0;
arr.sort((a,b)=>a>b)
for(let i=arr[0];i<=arr[1];i++){
r+=i;
}
return r;
}"
Diff Two Arrays
"function diffArray(arr1, arr2) {
var newArr = [];
for (var i = 0; i < arr1.length; i++) {
if(arr2.indexOf(arr1[i]) < 0){
newArr.push(arr1[i]);
}
}
for (var j = 0; j < arr2.length; j++) {
if(arr1.indexOf(arr2[j]) < 0){
newArr.push(arr2[j]);
}
}
return newArr;
}"
Seek and Destroy
"function destroyer(arr,...arg) {
// Remove all the values
let tArgs=Array.from(arg);
let l1=arr.length;
let l2=tArgs.length;
let t=[];
for(let i=0; i<l1;i++){
if(tArgs.indexOf(arr[i])<0)
{
t.push(arr[i]);
}
}
return t;
}
"
Wherefore art thou
"var srcKeys = Object.keys(source);
// filter the collection
return collection.filter(function (obj) {
for(var i = 0; i < srcKeys.length; i++) {
if(!obj.hasOwnProperty(srcKeys[i]) || obj[srcKeys[i]] !== source[srcKeys[i]]) {
return false;
}
}
return true;
});"
Spinal Tap Case
"function spinalCase(str) {
// Create a variable for the white space and underscores.
var regex = /\s+|_+/g;
// Replace low-upper case to low-space-uppercase
str = str.replace(/([a-z])([A-Z])/g, '$1 $2');
// Replace space and underscore with -
return str.replace(regex, '-').toLowerCase();
}"
Pig Latin
"function translatePigLatin(str) {
let regv=/^[aeoui]/;
let regc=/[aeoui]/;
let r=str.slice(0);
if(!regc.test(str))
return str +'ay';
if((regv).test(str))
return str + 'way';
else
{
let l=str.indexOf(str.match(regc));
return str.slice(l)+ str.substr(0,l)+'ay';
}"
Search and Replace
"function myReplace(str, before, after) {
let reg=/^[A-Z]/;
let uAfter=after.slice(0);
if(reg.test(before))
uAfter=after.charAt(0).toUpperCase()+after.slice(1);
let r=str.replace(before,uAfter);
return r;
}
"
DNA Pairing
"function isLegal(s1,s2){
let s=s1+s2;
if(s==='AT'||s==='TA'||s==='CG'||s==='GC')
return true;
else
return false;
}
function pairElement(str) {
let s=str.split('');
let l=s.length;
let c=['A','T','C','G'];
let r=[];
for(let i=0;i<l;i++)
{
let sc=s.slice(0);
let sr=sc.splice(i,1);//sr="a",ss-'a'
for(let j=0;j<c.length;j++)
{
if(isLegal(sr[0],c[j]))
r.push([sr[0],c[j]]);
}
}
return r;
}"
Missing letters
"function fearNotLetter(str) {
for(let i = 1; i < str.length; i++) {
var cCode = str.charCodeAt(i);
var bCode = str.charCodeAt(i - 1);
if(cCode > bCode + 1)
return String.fromCharCode(bCode + 1);
}
}
"
Sorted Union
"function uniteUnique(arr) {
let ans = [];
for(var i = 0; i < arguments.length; i++) {
for(var j = 0; j < arguments[i].length; j++) {
let val = arguments[i][j];
if(ans.indexOf(val)<0) {
ans.push(val);
}
}
}
return ans;
}
"
Convert HTML Entities
"function convertHTML(str) {
var mapping = {
"&" : "&",
"<" : "<",
">" : ">",
"\"" : """,
"'" : "'"
};
for(var key in mapping) {
str = str.replace(RegExp(key, "g"), mapping[key]);
}
return str;
}
"
Sum All Odd Fibonacci Numbers
"function sumFibs(num) {
// create an array of fib numbers till num
var arrFib = [1];
for (var i = 1; i <=num;) {
arrFib.push(i);
i = arrFib[arrFib.length - 1] + arrFib[arrFib.length - 2];
}
// return the sum of odd numbers from the array
var res = arrFib.reduce(function(prev, curr) {
if (curr%2 !== 0) return prev + curr;
else return prev;
});
return res;
}
"
Sum All Primes
"function sumPrimes(num) {
// step 1
let arr = Array.from({length: num+1}, (v, k) => k).slice(2);
// step 2
let onlyPrimes = arr.filter( (n) => {
let m = n-1;
while (m > 1 && m >= Math.sqrt(n)) {
if ((n % m) === 0)
return false;
m--;
}
return true;
});
// step 3
return onlyPrimes.reduce((a,b) => a+b);
}"
Smallest Common Multiple
"function smallestCommons(arr) {
// Sort array from greater to lowest
// This line of code was from Adam Doyle (http://github.com/Adoyle2014)
arr.sort(function(a, b) {
return b - a;
});
// Create new array and add all values from greater to smaller from the
// original array.
var newArr = [];
for (var i = arr[0]; i >= arr[1]; i--) {
newArr.push(i);
}
// Variables needed declared outside the loops.
var quot = 0;
var loop = 1;
var n;
// Run code while n is not the same as the array length.
do {
quot = newArr[0] * loop * newArr[1];
for (n = 2; n < newArr.length; n++) {
if (quot % newArr[n] !== 0) {
break;
}
}
loop++;
} while (n !== newArr.length);
return quot;
}
"Drop it
"function dropElements(arr, func) {
// drop them elements.
var times = arr.length;
for (var i = 0; i < times; i++) {
if (func(arr[0])) {
break;
} else {
arr.shift();
}
}
return arr;
}"
Steamroller
"function steamrollArray(arr) {
var flattenedArray = [];
// Create function that adds an element if it is not an array.
// If it is an array, then loops through it and uses recursion on that array.
var flatten = function(arg) {
if (!Array.isArray(arg)) {
flattenedArray.push(arg);
} else {
for (var a in arg) {
flatten(arg[a]);
}
}
};
// Call the function for each element in the array
arr.forEach(flatten);
return flattenedArray;
}"
Binary Agents
"function binaryAgent(str) {
var split = str.split(' ');
var newArray = [];
var result = [];
for(var i = 0; i < split.length; i++) {
newArray.push(parseInt(split[i],2));
result.push(String.fromCharCode(newArray[i]));
}
return result.join('');
}"
Everything Be True
"for (var c in collection) {
// If it is has property and value is truthy
if (!collection[c].hasOwnProperty(pre) || !Boolean(collection[c][pre])) {
return false;
}
}
return true;
}"
Arguments Optional
"function addTogether() {
// Function to check if a number is actually a number
// and return undefined otherwise.
var checkNum = function(num) {
if (typeof num !== 'number') {
return undefined;
} else
return num;
};
// Check if we have two parameters, check if they are numbers
// handle the case where one is not
// returns the addition.
if (arguments.length > 1) {
var a = checkNum(arguments[0]);
var b = checkNum(arguments[1]);
if (a === undefined || b === undefined) {
return undefined;
} else {
return a + b;
}
} else {
// If only one parameter was found, returns a new function that expects two
// Store first argument before entering the new function scope
var c = arguments[0];
// Check the number again, must be outside the function to about returning an object
// instead of undefined.
if (checkNum(c)) {
// Return function that expect a second argument.
return function(arg2) {
// Check for non-numbers
if (c === undefined || checkNum(arg2) === undefined) {
return undefined;
} else {
// if numbers then add them.
return c + arg2;
}
};
}
}
}"
Make a Person
"var Person = function(firstAndLast) {
var fullName = firstAndLast;
var arr = fullName.split(' ');
this.getFirstName = function() {
return arr[0];
};
this.getLastName = function() {
return arr[1];
};
this.getFullName = function() {
return fullName;
};
this.setFirstName = function(first) {
arr[0] = first;
fullName = arr.join(' ');
};
this.setLastName = function(last) {
arr[1] = last;
fullName = arr.join(' ');
};
this.setFullName = function(firstAndLast) {
fullName = firstAndLast;
arr = fullName.split(' ');
};
};"
Map the Debris
"function orbitalPeriod(arr) {
var GM = 398600.4418;
var earthRadius = 6367.4447;
var a = 2 * Math.PI;
var newArr = [];
var getOrbPeriod = function(obj) {
var c = Math.pow(earthRadius + obj.avgAlt, 3);
var b = Math.sqrt(c / GM);
var orbPeriod = Math.round(a * b);
delete obj.avgAlt;
obj.orbitalPeriod = orbPeriod;
return obj;
};
for (var elem in arr) {
newArr.push(getOrbPeriod(arr[elem]));
}
return newArr;
}"
Nhận xét
Đăng nhận xét