Quotes help make search much faster. Example: "Practice Makes Perfect"

Tuesday, May 16, 2017

FreeCodeCamp Wherefore Art Thou Sample Solution


function whatIsInAName(collection, source) {
  // What's in a name?
  var arr = [];
  // Only change code below this line
  //return Object.keys(source);
 
  var sourceKeys = Object.keys(source);
  var sourceValues = Object.values(source);
 
  for(var i=0; i<collection.length; i++){
    var collectionKeys = Object.keys(collection[i]);
    var collectionValues = Object.values(collection[i]);
   
    var allKeysTrue = true;
    var allValuesTrue = true;
    for(var j=0; j<sourceKeys.length; j++){
     
      if(!collectionKeys.toString().includes(sourceKeys[j].toString())){
        allKeysTrue = false;
      }
     
      if(!collectionValues.toString().includes(sourceValues[j].toString())){
        allValuesTrue = false;
      }
     
    }
    if(allKeysTrue && allValuesTrue){
      arr.push(collection[i]);
    }
  }
  // Only change code above this line
  return arr;
}

whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

FreeCodeCamp Everything Be True Sample Solution


function truthCheck(collection, pre) {
  // Is everyone being true?
  var test = true;
  for(var i=0; i<collection.length; i++){
    if(pre in collection[i]){
      if(!collection[i][pre]){
        test = false;
        break;
      }
    } else {
      test = false;
      break;
    }
  }
  return test;
}

truthCheck([{"user": "Tinky-Winky", "sex": "male", "age": 0}, {"user": "Dipsy", "sex": "male", "age": 3}, {"user": "Laa-Laa", "sex": "female", "age": 5}, {"user": "Po", "sex": "female", "age": 4}], "age");

Monday, May 15, 2017

FreeCodeCamp Binary Agents Sample Solution


function binaryAgent(str) {
  var arr = str.split(" ");
  var arr2 = [];
  for(var i=0; i<arr.length; i++){
    arr2.push(String.fromCharCode(parseInt(arr[i], 2)));
  }
  return arr2.join("");
}

binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");

FreeCodeCamp Steamroller Sample Solution


function steamrollArray(arr) {
  // I'm a steamroller, baby
  var flattened = arr.reduce(
    function(a, b) {
      return a.concat(Array.isArray(b) ? steamrollArray(b) : b);
    },[]);
  return flattened;
}

steamrollArray([[["a"]], [["b"]]]);

Saturday, May 13, 2017

FreeCodeCamp Drop It Sample Solution

function dropElements(arr, func) {
  // Drop them elements.
  for(var i=0; i<arr.length; i++){
    if([arr[i]].filter(func)>0){
      return arr.slice(i,arr.length);
    }
  }
  return [];
}

dropElements([1, 2, 3, 9, 2], function(n) {return n > 2;});

FreeCodeCamp Finders Keepers Sample Solution

function findElement(arr, func) {
  var filtered = arr.filter(func);
  return filtered[0];
}

findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; });

FreeCodeCamp Sum All Primes Sample Solution

function isPrime(value) {
  for(var i = 2; i < value; i++) {
    if(value % i === 0) {
      return false;
    }
  }
  return true;
}

function genPrimeArr(num){
  var arr = [];
  for(var i=2; i<=num; i++){
   
    if(isPrime(i)){
      arr.push(i);
    }
  }
  return arr;
}

function sumArr(arr){
  var sum = 0;
  for(var i=0; i<arr.length; i++){
    sum += arr[i];
  }
  return sum;
}

function sumPrimes(num) {
  return sumArr(genPrimeArr(num));
}

sumPrimes(10);

FreeCodeCamp Sum All Odd Fibonacci Numbers Sample Solution

function generateFibSeq(num){
  var arr=[1,1];
  while(num > arr[arr.length-1]){
    if(arr[arr.length-1]+arr[arr.length-2] > num){
      break;
    }
    arr.push(arr[arr.length-1]+arr[arr.length-2]);
  }
  return arr;
}

function sumFibs(num) {
  if(num===1){
    return 1;
  }
  var fibArr = generateFibSeq(num);
 
  var sum = 0;
  for(var i in fibArr){
    if(fibArr[i]%2 !== 0){
      sum += fibArr[i];
    }
  }
  return sum;
}

sumFibs(75025);

FreeCodeCamp Spinal Tap Case Sample Solution

function spinalCase(str) {
  var str2 = str.replace(/([a-z](?=[A-Z]))/g,'$1 ');
  var newStr = str2.replace(/\s|\x5F/g,"-");
  return newStr.toLowerCase();
}

spinalCase("AllThe-small Things");

FreeCodeCamp Convert HTML Entities Sample Solution

function convertHTML(str) {
  // &colon;&rpar;
  var htmlCode = {
    "&":"&amp;",
    "<":"&lt;",
    ">":"&gt;",
    "\"":"&quot;",
    "'":"&apos;"
  };
  var arrayStr = str.split('');
  for(var i in arrayStr){
    for(var j in htmlCode){
      if(arrayStr[i] == j){
        arrayStr[i] = htmlCode[j];
      }
    }
  }
  return arrayStr.join('');
}

convertHTML("Dolce & Gabbana");

FreeCodeCamp Sorted Union Sample Solution


function uniteUnique(arr) {
  var args = Array.prototype.slice.call(arguments);
  var newArr = [];
 
  for(var i=0; i<args.length; i++){
    for(var j=0; j<args[i].length; j++){
      newArr.push(args[i][j]);
    }
  }
 
  var uniqueArray = newArr.filter(function(item, pos) {
    return newArr.indexOf(item) == pos;
  });
 
  return uniqueArray;
}

uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);

FreeCodeCamp Missing Letters Sample Solution

function fearNotLetter(str) {
  var arr = str.split('');
  var codes = [];
  for(var i=0; i<arr.length; i++){
    codes.push(arr[i].charCodeAt(0));
  }
 
  for(var j=0; j<codes.length; j++){
    if(codes[j] != codes[0]+j){
      return String.fromCharCode(codes[0]+j);
    }
  }
  return undefined;
}

fearNotLetter("abce");

FreeCodeCamp DNA Pairing Sample Solution

function pairElement(str) {
  var pairs = {
    'G':'C',
    'C':'G',
    'A':'T',
    'T':'A'
  };
  var arr = str.split("");
  var arrPairs = [];
  for(var i=0; i<arr.length; i++){
    arrPairs.push([arr[i],pairs[arr[i]]]);
  }
  return arrPairs;
}

pairElement("GCG");

FreeCodeCamp Pig Latin Sample Solution

function vowelCheck(str,index){
  if(str[index]=='a' || str[index]=='e' || str[index]=='i' || str[index]=='o' || str[index]=='u'){
    return true;
  }
}

function translatePigLatin(str) {
  //vowel case
  str = str.toLowerCase();
  var arr = [];
  var indexCount = 0;
  if(vowelCheck(str,0)){
    return str+"way";
  } else {
    arr.push(str[0]);
    indexCount++;
    for(var i=1; i<str.length; i++){
      if(!vowelCheck(str,i)){
        arr.push(str[i]);
        indexCount++;
      } else {
        break;
      }
    }
    return str.substr(indexCount,str.length)+arr.join('')+"ay";
  }
  return arr;
}

translatePigLatin("consonant");

FreeCodeCamp Search and Replace Sample Solution


function myReplace(str, before, after) {
  var test = '/'+ before +'/';
  //return after;
  if(before[0] == before[0].toUpperCase()){
    var firstLetter = after.split('').splice(0,1);
    var restOfTheWord = after.split('').splice(1,after.length).join('');
    after = firstLetter[0].toUpperCase()+restOfTheWord;
  }
  var newstr = str.split(before).join(after);
  return newstr;
}

myReplace("He is Sleeping on the couch", "Sleeping", "sitting");

FreeCodeCamp Roman Numeral Converter Sample Solution

function convertToRoman(num) {
 var chart = {
   0:'',
   1:'I',
   2:'II',
   3:'III',
   4:'IV',
   5:'V',
   6:'VI',
   7:'VII',
   8:'VIII',
   9:'IX',
   10:'X',
   20:'XX',
   30:'XXX',
   40:'XL',
   50:'L',
   60:'LX',
   70:'LXX',
   80:'LXXX',
   90:'XC',
   100:'C',
   200:'CC',
   300:'CCC',
   400:'CD',
   500:'D',
   600:'DC',
   700:'DCC',
   800:'DCCC',
   900:'CM',
   1000:'M',
   2000:'MM',
   3000:'MMM'
 };
 var numString = num.toString().split('');
 if(numString.length == 1){
   return chart[parseInt(numString[0])];
 } else if(numString.length == 2){
   return chart[parseInt(numString[0])*10]+chart[parseInt(numString[1])];
 } else if(numString.length == 3){
   return chart[parseInt(numString[0])*100]+
     chart[parseInt(numString[1])*10]+
     chart[parseInt(numString[2])];
 } else if(numString.length == 4){
   return chart[parseInt(numString[0])*1000]+
     chart[parseInt(numString[1])*100]+
     chart[parseInt(numString[2])*10]+
     chart[parseInt(numString[3])];
 }
}
convertToRoman(2);

FreeCodeCamp Diff Two Arrays Sample Solution

function cleanArray(actual) {
  var newArray = [];
  for (var i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
}

function diffArray(arr1, arr2) {
  var newArr = [];
  // Same, same; but different.
  var slicedArr1;
  var slicedArr2;
  for(var i=0; i<arr1.length; i++){
    for(var j=0; j<arr2.length; j++){
      if(arr1[i] === arr2[j]){
        //arr1.splice(i,1);
        delete arr1[i];
        //arr2.splice(j,1);
        delete arr2[j];
      }
    }  
  }
  newArr = arr1.concat(arr2);
  return cleanArray(newArr);
}

diffArray(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]);

FreeCodeCamp Sum All Numbers In Range Sample Solution

function sumAll(arr) {
  var sorted = arr.sort(function(a, b){return a-b});
  var sum = 0;
  for(var i=sorted[0]; i<=sorted[1]; i++){
    sum += i;
  }
  return sum;
}

sumAll([1, 4]);

FreeCodeCamp Caesars Cipher Sample Solution

function rot13(str) {
  var num = [];
  for(var i=0; i<str.length; i++){
    num.push(str.charCodeAt(i));
  }
 
  var num2 = num.map( function(value) {
    //A to Z is between 65 and 90 so only convert these values
    if(value>=65 && value<=90){
      if(value-13 >= 65){
        return value - 13;
      } else {
        return value + 13;
      }
    } else {
      return value;
    }
  });
 
  var num3 = [];
  for(var j=0; j<num2.length; j++){
    num3.push(String.fromCharCode(num2[j]));
  }
 
  return num3.join('');
}

Friday, May 12, 2017

FreeCodeCamp Where Do I Belong Sample Solution


function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  var sorted = arr.sort(function(a, b){return a-b});
  for(var i=0; i<sorted.length; i++){
    if(num > sorted[sorted.length-1]){
      return sorted.length;
    }
    if(sorted[i] >= num){
      return i;
    }  
  }
}

getIndexToIns([5, 3, 20, 3], 5);

FreeCodeCamp Falsy Bouncer Sample Solution

function bouncer(arr) {
  // Don't show a false ID to this bouncer.
  var newArr = arr.filter(function(val){
    return !!val;
  });
  return newArr;
}

bouncer([7, "ate", "", false, 9]);

FreeCodeCamp Mutations Sample Solution


function mutation(arr) {
  var arr1 = arr[0].toLowerCase().split('');
  var arr2 = arr[1].toLowerCase().split('');
  var temp = false;
  for(var i=0; i<arr2.length; i++){
    temp = false;
    for(var j=0; j<arr1.length; j++){
      if(arr2[i] === arr1[j]){
        temp = true;
      }  
    }
    if(temp === false){
      //all the letters in the first word didn't match
      break;
    }
  }
  return temp;
}

mutation(["hello", "Hello"]);

FreeCodeCamp Slasher Flick Sample Solution


function slasher(arr, howMany) {
  // it doesn't always pay to be first
  for(var i=0; i<howMany; i++){
    arr.shift();
  }
  return arr;
}

slasher([1, 2, 3], 2);

FreeCodeCamp Chunky Monkey Sample Solution

function chunkArrayInGroups(arr, size) {
  // Break it up.
  var temp = [];
  var divisions = arr.length / size;
  while(arr.length>0){
    var temp2 = [];
    for(var i=0; i<size; i++){
      if(arr.length<=0){
        break;
      }
      temp2.push(arr.shift());
    }
    temp.push(temp2);
  }
  return temp;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);

FreeCodeCamp Truncate A String Sample Solution


function truncateString(str, num) {
  // Clear out that junk in your trunk
  if(num >= str.length){
    return str;
  }
  if(num > 3){
    return str.substring(0,num-3) + "...";
  } else {
    return str.substring(0,num) + "...";
  }
}

truncateString("A-tisket a-tasket A green and yellow basket", 11);

FreeCodeCamp Repeat A String Repeat A String Sample Solution

function repeatStringNumTimes(str, num) {
  // repeat after me
  var temp='';
  if(num<=0){
    return '';
  } else {
    for(var i=0; i<num; i++){
      temp += str;
    }
  }
  return temp;
}

repeatStringNumTimes("abc", 3);

FreeCodeCamp Confirm The Ending Sample Solution


function confirmEnding(str, target) {
  // "Never give up and good luck will find you."
  // -- Falcor
  var diff = str.length - target.length;
  if(str.substring(diff,str.length) === target){
    return true;
  } else {
    return false;
  }
}

confirmEnding("Bastian", "n");

FreeCodeCamp Return Largest Numbers In Arrays Sample Solution

function largestOfFour(arr) {
  // You can do this!
  var largestArr = [];
  for(var i=0; i<arr.length; i++){
    var temp = -1000000;
    for(var j=0; j<arr[i].length; j++){
      if(temp < arr[i][j]){
        temp = arr[i][j];
      }
    }
    largestArr.push(temp);
  }
  return largestArr;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

FreeCodeCamp Title Case A Sentence Sample Solution

function titleCase(str) {
  var arr = str.toLowerCase().split(' ');
  var arr2 = [];
  for(var i=0; i<arr.length; i++){
    arr2.push(arr[i].substring(0,1).toUpperCase()+arr[i].substring(1,arr[i].length));
  }
  return arr2.join(' ');
}

titleCase("I'm a little tea pot");

FreeCodeCamp Find The Longest Word In A String Sample Solution


function findLongestWord(str) {
  var arr = str.split(' ');
  var longest = "";
  for(var i=0; i<arr.length; i++){
    if(arr[i].length > longest.length){
      longest = arr[i];
    }
  }
  return longest.length;
}

findLongestWord("The quick brown fox jumped over the lazy dog");

FreeCodeCamp Check For Palindromes Sample Solution

function palindrome(str) {
  // Good luck!
  var temp = str.toLowerCase().replace(/[^0-9a-zA-Z]/gi, '');
  if(temp === temp.split('').reverse().join('')){
    return true;
  } else {
    return false;
  }
}

palindrome("_eye");

FreeCodeCamp Factorialize A Number Sample Solution


function factorialize(num) {
  var prod = num;
  if(num === 0){
    return 1;
  }
  for(var i=num-1; i>0; i--){
    prod *= i;
  }
  return prod;
}

factorialize(5);

FreeCodeCamp Reverse A String Sample Solution

function reverseString(str) {
  return str.split('').reverse().join('');
}

reverseString("hello");

FreeCodeCamp Join Strings With Join Sample Solution


var joinMe = ["Split","me","into","an","array"];
var joinedString = '';

// Only change code below this line.

joinedString = joinMe.join(" ");

FreeCodeCamp Split Strings With Split Sample Solution


var string = "Split me into an array";
var array = [];

// Only change code below this line.

array = string.split(' ');

FreeCodeCamp Sort Arrays With Sort Sample Solution

var array = [1, 12, 21, 2];

// Only change code below this line.

array.sort(function(a, b) {
  return b - a;
});

Thursday, May 11, 2017

FreeCodeCamp Filter Arrays With Filter Sample Solution

var oldArray = [1,2,3,4,5,6,7,8,9,10];

// Only change code below this line.

var newArray = oldArray.filter(function(val) {
  return val < 6;
});

FreeCodeCamp Iterate Over Arrays With Map Sample Solution


var oldArray = [1,2,3,4,5];

// Only change code below this line.

var newArray = oldArray.map(function(val){
  return val + 3;
});

FreeCodeCamp Generate Whole Random Numbers Within A Range Sample Solution


// Example
function ourRandomRange(ourMin, ourMax) {

  return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;
}

ourRandomRange(1, 9);

// Only change code below this line.

function randomRange(myMin, myMax) {

  return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin; // Change this line

}

// Change these values to test your function
var myRandom = randomRange(5, 15);

FreeCodeCamp Profile Lookup Sample Solution

//Setup
var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
    {
        "firstName": "Sherlock",
        "lastName": "Holmes",
        "number": "0487345643",
        "likes": ["Intriguing Cases", "Violin"]
    },
    {
        "firstName": "Kristian",
        "lastName": "Vos",
        "number": "unknown",
        "likes": ["Javascript", "Gaming", "Foxes"]
    }
];


function lookUpProfile(firstName, prop){
// Only change code below this line
  var returnValue = "";
  for(var i=0; i < contacts.length; i++){
    if(firstName === contacts[i].firstName && contacts[i].hasOwnProperty(prop) === true){
        returnValue = contacts[i][prop];
        break;
    } else if(firstName === contacts[i].firstName && contacts[i].hasOwnProperty(prop) === false) {
        returnValue = "No such property";
        break;
    } else {
      returnValue = "No such contact";
    }
  }
  return returnValue;
// Only change code above this line
}

// Change these values to test your function
//lookUpProfile("Akira", "likes");
lookUpProfile("Akira", "address");

FreeCodeCamp Iterate With Javascript While Loops Sample Solution

// Setup
var myArray = [];

// Only change code below this line.
var i = 0;
while(i < 5) {
  myArray.push(i);
  i++;
}

FreeCodeCamp Nesting For Loops Sample Solution

function multiplyAll(arr) {
  var product = 1;
  // Only change code below this line
  for (var i=0; i < arr.length; i++) {
    for (var j=0; j < arr[i].length; j++) {
      product *= arr[i][j];
    }
  }
  // Only change code above this line
  return product;
}

// Modify values below to test your code
multiplyAll([[1,2],[3,4],[5,6,7]]);

FreeCodeCamp Iterate Through An Array With A For Loop Sample Solution


// Example
var ourArr = [ 9, 10, 11, 12];
var ourTotal = 0;

for (var i = 0; i < ourArr.length; i++) {
  ourTotal += ourArr[i];
}

// Setup
var myArr = [ 2, 3, 4, 5, 6];

// Only change code below this line
var total=0;
for (var i = 0; i < myArr.length; i++){
  total += myArr[i];
}

FreeCodeCamp Iterate With Javascript For Loops Sample Solution

// Example
var ourArray = [];

for (var i = 0; i < 5; i++) {
  ourArray.push(i);
}

// Setup
var myArray = [];

// Only change code below this line.
for (var i = 0; i < 5; i++) {
  myArray.push(i+1);
}

FreeCodeCamp Accessing Nested Arrays Sample Solution

// Setup
var myPlants = [
  {
    type: "flowers",
    list: [
      "rose",
      "tulip",
      "dandelion"
    ]
  },
  {
    type: "trees",
    list: [
      "fir",
      "pine",
      "birch"
    ]
  }
];

// Only change code below this line

var secondTree = myPlants[1].list[1];

FreeCodeCamp Accessing Nested Objects Sample Solution

// Setup
var myStorage = {
  "car": {
    "inside": {
      "glove box": "maps",
      "passenger seat": "crumbs"
     },
    "outside": {
      "trunk": "jack"
    }
  }
};

// Only change code below this line

var gloveBoxContents = myStorage.car.inside["glove box"];

FreeCodeCamp Manipulating Complex Objects Sample Solution

var myMusic = [
  {
    "artist": "Billy Joel",
    "title": "Piano Man",
    "release_year": 1973,
    "formats": [
      "CS",
      "8T",
      "LP" ],
    "gold": true
  }
  // Add record here
];
myMusic.push({
  "artist": "John Mayer",
  "title": "Continuum Extended",
  "release_year": 2017,
  "formats": [
      "CS",
      "8T",
      "LP" ]
});

FreeCodeCamp checkObj(checkProp) Sample Solution

// Setup
var myObj = {
  gift: "pony",
  pet: "kitten",
  bed: "sleigh"
};

function checkObj(checkProp) {
  // Your Code Here
 
  if(myObj.hasOwnProperty(checkProp)){
    return myObj[checkProp];
  } else {
    return "Not Found";
  }
}

// Test your code by modifying these values
checkObj("gift");

FreeCodeCamp phoneticLookup(val) Sample Solution

function phoneticLookup(val) {
  var result = "";

  // Only change code below this line
  var lookup = {
    "alpha":"Adams",
    "bravo":"Boston",
    "charlie":"Chicago",
    "delta":"Denver",
    "echo":"Easy",
    "foxtrot":"Frank"
  };
  result = lookup[val];
  // Only change code above this line
  return result;
}

FreeCodeCamp Counting Cards Sample Solution

function cc(card) {
  // Only change code below this line
  switch(card){
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
      count++;
      break;
    case 7:
    case 8:
    case 9:
      break;
    case 10:
    case 'J':
    case 'Q':
    case 'K':
    case 'A':
      count--;
      break;
  }
  if(count>0){
    return count + " Bet";
  } else {
    return count + " Hold";
  }
  // Only change code above this line
}

FreeCodeCamp abTest(a,b) Sample Solution

function abTest(a, b) {
  // Only change code below this line
  if(a < 0 || b < 0){
    return undefined;
  }
  // Only change code above this line

  return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
}

FreeCodeCamp chainToSwitch(val) Sample Solution

function chainToSwitch(val) {
  var answer = "";
  // Only change code below this line
  switch(val){
    case "bob":
      answer = "Marley";
      break;
    case 42:
      answer = "The Answer";
      break;
    case 1:
      answer = "There is no #1";
      break;
    case 99:
      answer = "Missed me by this much!";
      break;
    case 7:
      answer = "Ate Nine";
      break;
  }
  // Only change code above this line
  return answer;
}

FreeCodeCamp sequentialSizes(val) Sample Solution

function sequentialSizes(val) {
  var answer = "";
  // Only change code below this line
  switch(val){
    case 1:
    case 2:
    case 3:
      answer = "Low";
      break;
    case 4:
    case 5:
    case 6:
      answer = "Mid";
      break;
    case 7:
    case 8:
    case 9:
      answer = "High";
      break;
  }
  // Only change code above this line
  return answer;
}

FreeCodeCamp switchOfStuff Sample Solution

function switchOfStuff(val) {
  var answer = "";
  // Only change code below this line
  switch(val){
    case "a":
      answer = "apple";
      break;
    case "b":
      answer = "bird";
      break;
    case "c":
      answer = "cat";
      break;
    default:
      answer = "stuff";
  }
  // Only change code above this line
  return answer;
}

FreeCodeCamp First Switch Exercise

//sample solution
function caseInSwitch(val) {
  var answer = "";
  // Only change code below this line
  switch(val){
    case 1:
      answer = "alpha";
      break;
    case 2:
      answer = "beta";
      break;
    case 3:
      answer = "gamma";
      break;
    case 4:
      answer = "delta";
      break;
  }
  // Only change code above this line
  return answer;
}

FreeCodeCamp Golf Code

//sample solution
function golfScore(par, strokes) {
  // Only change code below this line
  if(strokes == 1){
    return "Hole-in-one!";
  } else if(strokes <= par - 2) {
    return "Eagle";
  } else if(strokes == par - 1) {
    return "Birdie";
  } else if(strokes == par) {
    return "Par";
  } else if(strokes == par + 1) {
    return "Bogey";
  } else if(strokes == par + 2) {
    return "Double Bogey";
  } else if(strokes >= par + 3) {
    return "Go Home!";
  }
  // Only change code above this line
}

Tuesday, May 9, 2017

Codecademy Learn ReactJS: Part 1 Exercise 13 of 15

//sample solution to app.js

var React = require('react');
var ReactDOM = require('react-dom');

// Write code here:
var myList = (
  <ul>
    <li>
    Superman
    </li>
    <li>
    Batman
    </li>
    <li>
    Flash
    </li>
    <li>
    Aquaman
    </li>
    <li>
    Wonderwoman
    </li>
  </ul>
);

ReactDOM.render(myList,document.getElementById('app'));

Codecademy Learn ReactJS: Part 1 Exercise 12 of 15

<!--sample solution to index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/styles.css">
<title>Learn ReactJS</title>
</head>

<body>
  <span id="container"></span>
  <script src="/app.compiled.js"></script>
</body>

</html>


//sample solution to app.js
var React = require('react');
var ReactDOM = require('react-dom');

// Write code here:
ReactDOM.render(<h1>Render me!</h1>, document.getElementById('container'));

Codecademy Learn ReactJS: Part 1 Exercise 11 of 15

//sample solution to app.js
var React = require('react');
var ReactDOM = require('react-dom');

// Write code here:
ReactDOM.render(<h1>Render me!</h1>,document.getElementById('app'));

Codecademy Learn ReactJS: Part 1 Exercise 10 of 15

var React = require('react');
var ReactDOM = require('react-dom');

ReactDOM.render(<h1>Hello world</h1>, document.getElementById('app'));

Codecademy Learn ReactJS: Part 1 Exercise 9 of 15

var blog = (
  <div>
    <img src="pics/192940u73.jpg" />
    <h1>
      Welcome to Dan's Blog!
    </h1>
    <article>
      Wow I had the tastiest sandwich today.  I <strong>literally</strong> almost freaked out.
    </article>
  </div>
);

Codecademy Learn ReactJS: Part 1 Exercise 8 of 15

var myDiv = (
  <div>
    <h1>
      Hello world
    </h1>
  </div>
);

Codecademy Learn ReactJS: Part 1 Exercise 7 of 15

var p1 = <p id="large">foo</p>;
var p2 = <p id="small">bar</p>;

Codecademy Learn ReactJS: Part 1 Exercise 6 of 15

var myArticle = <article>An article</article>;

Codecademy Learn ReactJS: Part 1 Exercise 5 of 15

<p>Hello world</p>

Codecademy SQL: Analyzing Business Metrics Exercise 13 of 14

--first answer

select
  date(g1.created_at) as dt,
  g1.user_id,
  g2.user_id
from gameplays as g1
  join gameplays as g2 on
    g1.user_id = g2.user_id
    and date(g1.created_at) = date(datetime(g2.created_at, '-1 day'))
order by 1
limit 100;

--second answer

select
  date(g1.created_at) as dt,
  count(distinct g1.user_id) as total_users,
  count(distinct g2.user_id) as retained_users
from gameplays as g1
  left join gameplays as g2 on
    g1.user_id = g2.user_id
    and date(g1.created_at) = date(datetime(g2.created_at, '-1 day'))
group by 1
order by 1
limit 100;

--third answer

select
  date(g1.created_at) as dt,
  round(100 * count(distinct g2.user_id) /
    count(distinct g1.user_id)) as retention
from gameplays as g1
  left join gameplays as g2 on
    g1.user_id = g2.user_id
    and date(g1.created_at) = date(datetime(g2.created_at, '-1 day'))
group by 1
order by 1
limit 100;

Codecademy SQL: Analyzing Business Metrics Exercise 12 of 14

--first answer

select
  date(created_at) as dt,
  user_id
from gameplays as g1
order by dt
limit 100;

--second answer

select
  date(g1.created_at) as dt,
  g1.user_id
from gameplays as g1
  join gameplays as g2 on
    g1.user_id = g2.user_id
order by 1
limit 100;

Codecademy SQL: Analyzing Business Metrics Exercise 9 of 14

--first answer

with daily_revenue as (
  select
    date(created_at) as dt,
    round(sum(price), 2) as rev
  from purchases
  where refunded_at is null
  group by 1
),
daily_players as (
  select
    date(created_at) as dt,
    count(distinct user_id) as players
  from gameplays
  group by 1
)
select * from daily_players order by dt;

--second answer

with daily_revenue as (
  select
    date(created_at) as dt,
    round(sum(price), 2) as rev
  from purchases
  where refunded_at is null
  group by 1
),
daily_players as (
  select
    date(created_at) as dt,
    count(distinct user_id) as players
  from gameplays
  group by 1
)
select
  daily_revenue.dt,
  daily_revenue.rev / daily_players.players
from daily_revenue
  join daily_players using (dt);

Codecademy SQL: Analyzing Business Metrics Exercise 8 of 14

with daily_revenue as (
  select
    date(created_at) as dt,
    round(sum(price), 2) as rev
  from purchases
  where refunded_at is null
  group by 1
)
select * from daily_revenue order by dt;

Codecademy SQL: Analyzing Business Metrics Exercise 6 of 14

select
  date(created_at),
  round(sum(price) / count(distinct user_id), 2) as arppu
from purchases
where refunded_at is null
group by 1
order by 1;

Codecademy SQL: Analyzing Business Metrics Exercise 5 of 14

select
  date(created_at),
  platform,
  count(distinct user_id) as dau
from gameplays
group by 1, 2
order by 1, 2;

Codecademy SQL: Analyzing Business Metrics Exercise 4 of 14

select
  date(created_at),
  count(distinct user_id) as dau
from gameplays
group by 1
order by 1;

Codecademy SQL: Analyzing Business Metrics Exercise 3 of 14

select
  date(created_at),
  round(sum(price), 2) as daily_rev
from purchases
where refunded_at is not null
group by 1
order by 1;

Codecademy SQL: Analyzing Business Metrics Exercise 2 of 14

select
  date(created_at),
  round(sum(price), 2)
from purchases
group by 1
order by 1;

Codecademy SQL: Analyzing Business Metrics Exercise 1 of 14

--first answer

select *
from purchases
order by id
limit 10;

--second answer

select *
from gameplays
order by id
limit 10;

Friday, May 5, 2017

Codecademy SQL SpeedySpoon Exercise 11

select name, count(DISTINCT order_id)
from order_items
group by 1
order by 1;

-- number of people making the orders

select name, round(1.0 * count(DISTINCT order_id) /
  count(DISTINCT delivered_to), 2) as reorder_rate
from order_items
  join orders on
    orders.id = order_items.order_id
group by 1
order by 2 desc;

Codecademy SQL SpeedySpoon Exercise 9

select *,
  case name
    when 'kale-smoothie'    then 'smoothie'
    when 'banana-smoothie'  then 'smoothie'
    when 'orange-juice'     then 'drink'
    when 'soda'             then 'drink'
    when 'blt'              then 'sandwich'
    when 'grilled-cheese'   then 'sandwich'
    when 'tikka-masala'     then 'dinner'
    when 'chicken-parm'     then 'dinner'
    else 'other'
  end as category
from order_items
order by id
limit 100;

-- percentages

select
  case name
    when 'kale-smoothie'    then 'smoothie'
    when 'banana-smoothie'  then 'smoothie'
    when 'orange-juice'     then 'drink'
    when 'soda'             then 'drink'
    when 'blt'              then 'sandwich'
    when 'grilled-cheese'   then 'sandwich'
    when 'tikka-masala'     then 'dinner'
    when 'chicken-parm'     then 'dinner'
    else 'other'
  end as category, round(1.0 * sum(amount_paid) /
    (select sum(amount_paid) from order_items) * 100, 2) as pct
from order_items
group by 1
order by 2 desc;

Codecademy SQL SpeedySpoon Exercise 7

select name, round(sum(amount_paid) /
  (select sum(amount_paid) from order_items) * 100.0, 2) as pct
from order_items
group by 1
order by 2 desc;

Codecademy SQL SpeedySpoon Exercise 6

select name, round(sum(amount_paid), 2)
from order_items
group by name
order by 2 desc;

Codecademy SQL SpeedySpoon Exercise 4

select date(ordered_at), round(sum(amount_paid), 2)
from orders
    join order_items on
      orders.id = order_items.order_id
group by 1
order by 1;

--for kale-smoothie

select date(ordered_at), round(sum(amount_paid), 2)
from orders
    join order_items on
      orders.id = order_items.order_id
where name = 'kale-smoothie'    
group by 1
order by 1;

Codecademy SQL SpeedySpoon Exercise 3

select date(ordered_at), count(1)
from orders
group by 1
order by 1;

Codecademy SQL SpeedySpoon Exercise 2

select date(ordered_at)
from orders
order by 1
limit 100;

Codecademy SQL SpeedySpoon Exercise 1

select *
from orders
order by id
limit 100;

select *
from order_items
order by id
limit 100;

Codecademy SQL Replace enriched_flour with flour

SELECT REPLACE(ingredients,'enriched_',' ') as item_ingredients
FROM baked_goods;

Codecademy SQL Combine the first_name and last_name columns from the bakeries table

SELECT first_name || ' ' || last_name as full_name
FROM bakeries;

Codecademy SQL Find the greatest and least time value for cool down and cook time for each item in the table

--Greatest Time
SELECT id, MAX(cook_time, cool_down_time)
FROM baked_goods;

--Least Time
SELECT id, MIN(cook_time, cool_down_time)
FROM baked_goods;

Codecademy SQL Find the bakery's distance from the market rounded to two decimal places

SELECT ROUND(distance, 2) as distance_from_market FROM bakeries;

Codecademy SQL Create a query returning all the packaging times for the goods

SELECT DATETIME(delivery_time, '+5 hours', '20 minutes', '2 days') as package_time
FROM baked_goods;

Codecademy SQL Find the number of baked goods by date of delivery

SELECT DATE(delivery_time), count(*) as count_baked_goods
FROM baked_goods
GROUP BY DATE(delivery_time);

Codecademy Sample Solution for delivery_time

Using the datetime function, select the date and time of all deliveries in the baked_goods table using the column delivery_time.

SELECT DATETIME(delivery_time) FROM baked_goods;

Monday, May 1, 2017

Codefights Sample Solution makeArrayConsecutive2(statues)

function makeArrayConsecutive2(statues) {
    ideal=0;
    real=statues.length;
    sorted = statues.sort(function(a, b){return a-b});
    for(i=sorted[0];i<=sorted[sorted.length-1];i++){
        ideal++;
    }
    statuesNeeded = ideal - real;
    return statuesNeeded;
}

Codefights Sample Solution shapeArea(n)

function shapeArea(n) {
    if(n==1){
        return 1;
    } else {
        return 4*(n-1) + shapeArea(n-1);
    }
}

Codefights Sample Solution for adjacentElementsProduct

function adjacentElementsProduct(inputArray) {
    max = -1000000;
    for(i=0; i<inputArray.length-1; i++){
        product = inputArray[i]*inputArray[i+1];
        if(product>max){
           max = product;   
        }
    }
    return max;
}

Codefights Sample Solution checkPalindrome

function checkPalindrome(inputString) {
    reverseString = inputString.split("").reverse().join("");
    if(inputString===reverseString){
        return true;
    } else {
        return false;
    }
}

Codefights Sample Solution for centuryFromYear

function centuryFromYear(year) {
    a = year/100;
    b = parseInt(a);
    c = a % 1;
    if(c>0){
        return b+1;
    } else {
        return b;
    }
}


This is an example of scrolling text using Javascript.

Popular Posts