Posts

Showing posts from November, 2018

Code Wars: String incrementer

https://www.codewars.com/kata/54a91a4883a7de5d7800009c/train/javascript Your job is to write a function which increments a string, to create a new string. If the string already ends with a number, the number should be incremented by 1. If the string does not end with a number the number 1 should be appended to the new string. Examples: foo -> foo1 foobar23 -> foobar24 foo0042 -> foo0043 foo9 -> foo10 foo099 -> foo100 Attention: If the number has leading zeros the amount of digits should be considered. My Solution:  function incrementString (strng) {   let regex = /[0-9]/g;   let index = strng.search(regex);   let arr = [];      //split string at where a number first appears   if (index === -1 || strng === "") {     return strng + "1";   }   else arr.push( strng.substring(0, index), strng.substring(index, strng.length) );      //loop through element of ...

FCC: Project Euler: Problem 4: Largest palindrome product

https://learn.freecodecamp.org/coding-interview-prep/project-euler/problem-4-largest-palindrome-product A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two  n -digit numbers. My solution: function largestPalindromeProduct(n) { let largestPalindrome = 0 ; //tracker //get starting and ending numbers of n-digit numbers let lowest = "1" ; while (n > 1 ) { lowest += "0" ; n--; } let largest = parseInt(lowest + "0" ) - 1 ; lowest = parseInt(lowest); //start with largest number since likely to get to largest palindrome first for ( let i = largest; i >= lowest; i--) { for ( let j = largest - 1 ; j >= lowest; j--) { let number = i * j; //check if number is greater before checking if palindrome for efficiency if ( number...

Jquery: this == event.target

function(event) { event.target.hide(); } can replace 'event.target' with 'this' (i.e. what you clicked on)

Code Wars: Delete occurrences of an element if it occurs more than n times (SOLVED 2nd try)

https://www.codewars.com/kata/554ca54ffa7d91b236000023/train/javascript Enough is enough! Alice and Bob were on a holiday. Both of them took many pictures of the places they've been, and now they want to show Charlie their entire collection. However, Charlie doesn't like this sessions, since the motive usually repeats. He isn't fond of seeing the Eiffel tower 40 times. He tells them that he will only sit during the session if they show the same motive at most N times. Luckily, Alice and Bob are able to encode the motive as a number. Can you help them to remove numbers such that their list contains each number only up to N times, without changing the order? Task Given a list lst and a number N, create a new list that contains each number of lst at most N times without reordering. For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, and then take 3, which lead...

JQuery: on method (Team Treehouse Notes)

Instead of having 2 separate event listeners for click and keypress, use the on method to combine the two: $('#element').on(' click keypress ', function() { //do stuff when element is clicked OR when a key is pressed });

Code Wars: Find the odd int

https://www.codewars.com/kata/54da5a58ea159efa38000836/train/javascript Given an array, find the int that appears an odd number of times. There will always be only one integer that appears an odd number of times. function findOdd(A) {   let arr = A.sort((a,b) => a - b);   let counter = 1;     if (arr.length === 1) return arr[0];     for (let i = 0; i < arr.length - 1; i++) {         if (arr[i] === arr[i + 1]) {       counter++;     }     else if (arr[i] !== arr[i + 1]) {             if (counter % 2 !== 0) {         return arr[i];       }       // if it turns out to be last number in array with a count of 1 (since for loop doesnt get to it)       else if (i + 1 === arr.length - 1) {         return arr[i + 1];       }       count...

Code Wars: Maximum subarray sum

https://www.codewars.com/kata/54521e9ec8e60bc4de000d6c/train/javascript The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers: maxSequence([ -2 , 1 , -3 , 4 , -1 , 2 , 1 , -5 , 4 ]) // should be 6: [4, -1, 2, 1] Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead. Empty list is considered to have zero greatest sum. Note that the empty list or array is also a valid sublist/subarray. SOLUTION: var maxSequence = function(arr){   let maxSum = arr[0]; //current highest consecutive sum or single element     if (arr.find(item => item > 0) === undefined || arr.length === 0) {     return 0;   }     for (let i = 0; i < arr.length - 1; i++) {     let tracker = 0; //keeps track of consecutive sums. Reset at every 'pointer...

Code Wars: Kebabize (a lot of edge cases)

https://www.codewars.com/kata/57f8ff867a28db569e000c4a/train/javascript Modify the  kebabize  function so that it converts a camel case string into a kebab case. kebabize( 'camelsHaveThreeHumps' ) // camels-have-three-humps kebabize( 'camelsHave3Humps' ) // camels-have-humps Notes: the returned string should only contain lowercase letters function kebabize(str) {   let arr = str.split("");     for (let i = arr.length - 1; i >= 0; i--) {     if (Number(arr[i]) || arr[i] === "0") {       arr.splice(i, 1);       console.log('number')     }     else if (arr[i] === arr[i].toUpperCase() && !Number.isInteger(arr[i]) && i !== 0) {       arr.splice(i, 0, "-");     }   }   if (arr[0] === "-") {     arr.splice(0, 1);   }   return arr.join("").toLowerCase(); }

CSS- Fixed side navbar

#navbar { position: fixed; left: 0; z-index: 10; background-color: #CDDEF2; box-shadow: 0 2px 3px #777; height: 100%; width: 20%; padding: 10px; } #main-doc { padding-top: 0px; margin-left: 185px; /*width of side navbar- adj for fixed navbar that's out of flow of document (other elements don't see/recognize it)*/ } footer { margin-left: 185px; }

Code Wars: Two Sum

https://www.codewars.com/kata/two-sum/javascript Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in an array like so:  [index1, index2] . For the purposes of this kata, some tests may have multiple answers; any valid solutions will be accepted. The input will always be valid (numbers will be an array of length 2 or greater, and all of the items will be numbers; target will always be the sum of two different items from that array). BEST PRACTICE SOLUTION (more efficient for loop- not repeating sums): function twoSum ( numbers, target ) { for ( var i = 0 ; i < numbers.length -1 ; i++) { for ( var j = i+ 1 ; j < numbers.length; j++) { if (numbers[i] + numbers[j] === target) return [i, j]; } } } My solution: function twoSum(numbers, ...

Code Wars: Highest Scoring Word (passed on first try!)

https://www.codewars.com/kata/57eb8fcdf670e99d9b000272/train/javascript Given a string of words, you need to find the highest scoring word. Each letter of a word scores points according to it's position in the alphabet:  a = 1, b = 2, c = 3  etc. You need to return the highest scoring word as a string. If two words score the same, return the word that appears earliest in the original string. All letters will be lowercase and all inputs will be valid. function high(x){   let arr = x.split(" ");   let largest;  //stores the current string with largest score   let totalScore = 0;  //stores the current largest score for that particular string   //create an array of lowercase alphabets   let alphaArr = [];   for (let i = 0; i < 26; i++) {     alphaArr.push(String.fromCharCode(97 + i));   }      for (let i = arr.length - 1; i >= 0; i--) {  //loops through array ...

Code Wars: Write Number in Expanded Form

Link to code challenge function expandedForm(num) { let expandedNum = ""; let numArr = num.toString().split(""); for (let i = 0; i 0 && i === numArr.length - 1) { expandedNum += numArr[i] * ( Math.pow(10, (numArr.length - 1) - i) ); } else if(numArr[i] > 0) { expandedNum += numArr[i] * ( Math.pow(10, (numArr.length - 1) - i) ) + " + "; } } // take out last add sign if it's at end of string (CAN ALSO do .join with " + " on an array) if (expandedNum.substr(expandedNum.length - 3) === " + ") { return expandedNum.slice(0, expandedNum.length - 3); } return expandedNum; }

Code Wars: Replace With Alphabet Position

https://www.codewars.com/kata/546f922b54af40e1e90001da/train/javascript Welcome. In this kata you are required to, given a string, replace every letter with its position in the alphabet. If anything in the text isn't a letter, ignore it and don't return it. "a" = 1 ,  "b" = 2 , etc. Example alphabet_position( "The sunset sets at twelve o' clock." ) Should return  "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11"  (as a string) function alphabetPosition(text) {   //split string into array of letters only   let sentence = text.toLowerCase().split("");   for (let i = sentence.length - 1; i >= 0; i--) {     if(sentence[i].match(/[a-z]/) === null) {       sentence.splice(i, 1);     }   }   //create an array of alphabets (97 represents lower case "a", 65 would be "A")   let alphaArr = [];   for (let i = 0; i < 26; i++) {     alpha...

ES6- const & let are block level scoped variables

Block level means anything between curly braces. Variable defined within the curly braces will only be recognized there. As for 'var', it is not block level scoped so it will be a global variable unless it is inside a function.

Code Wars: Find the smallest (NOT PASSED YET)

https://www.codewars.com/kata/573992c724fc289553000e95/train/javascript function smallest(n) {     let arr = (n).toString().split("");     let index = 0;     let smallest = arr[0];     let smallest2 = arr[1];     let replaceItem;     let final;       //find the smallest number that is not the first number in array     for (i = 1; i < arr.length; i++) {       if(arr[i] < smallest) {         index = i;         smallest = arr[i];       }     }     //if above does not go thru, find next largest number after 1st number     if (index === 0) {       for (i = 2; i < arr.length; i++) {         if(arr[i] < smallest2) {           index = i;           smallest2 = arr[i];        ...

Code Wars: Counting Duplicates

Count the number of Duplicates Write a function that will return the count of  distinct case-insensitive  alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits. Example "abcde" -> 0  # no characters repeats more than once "aabbcde" -> 2  # 'a' and 'b' "aabBcde" -> 2  # 'a' occurs twice and 'b' twice (`b` and `B`) "indivisibility" -> 1  # 'i' occurs six times "Indivisibilities" -> 2  # 'i' occurs seven times and 's' occurs twice "aA11" -> 2  # 'a' and '1' "ABBA" -> 2  # 'A' and 'B' each occur twice function duplicateCount(text){   let arr = text.split("").map(item => item.toLowerCase());    //can lowercase when it's a string first!   let ar...

Code Wars: Where is my parent!?(cry) / Also lesson on iterating thru loop and removing items at same time

Mothers arranged dance party for children in school.On that party there are only mothers and their children.All are having great fun on dancing floor when suddenly all lights went out.Its dark night and no one can see eachother.But you were flying nearby and you can see in the dark and have ability to teleport people anywhere you want. Legend: -Uppercase letters stands for mothers,lowercase stand for their children. I.E "A" mothers children are "aaaa". -Function input:String contain only letters,Uppercase letters are unique. Task: Place all people in alphabetical order where Mothers are followed by their children.I.E "aAbaBb" => "AaaBbb". https://stackoverflow.com/questions/9882284/looping-through-array-and-removing-items-without-breaking-for-loop lexicographical order meaning: https://www.youtube.com/watch?v=LtlZtFXe8Io My solution: function findChildren(dancingBrigade){   let arr = dancingBrigade.split('').sort(...

TeamTreeHouse: Objects and Console.log notes

Objects If accessing object property using a variable, can do it only through bracket notation since if using dot notation, it would looking for a key by the variable name. An example of this scenario would be when using a for in loop with an object. object[variable] object.variable Console.log - Can separate parameters with commas and it will concatenate them: console.log(prop, ': ', shanghai[prop]);

Code Wars: Reverse or rotate?

The input is a string  str  of digits. Cut the string into chunks (a chunk here is a substring of the initial string) of size  sz  (ignore the last chunk if its size is less than  sz ). If a chunk represents an integer such as the  sum of the cubes of its digits is divisible by 2 , reverse that chunk; otherwise rotate it to the left by one position. Put together these modified chunks and return the result as a string. If sz  is  <= 0  or if  str  is  empty  return "" sz  is greater  (>)  than the length of  str  it is impossible to take a chunk of size  sz  hence return "". function revrot(str, sz) {      if (sz <= 0 || str === "" || sz > str.length) {     return "";   }       let arr1 = str.split('').map(item => parseInt(item));   let arr2 = [];   let sumUp = function add(a, b) { ...

do while loops

do { console.log('Hello'); }  while (false)  console.log('Goodbye'); How does this statement print out 'Goodbye'? Where in the code does it value to false? The loop starts with "do" and  ends  with "while". It's a "do...while" loop, not an ordinary "while" loop. So the part the prints out "Goodbye" comes  after  and outside the loop, and will always be done. Ah I get it! console.log('Goodbye'); is not in curly braces in which I was picturing that's how it was set up to be which would then be dependent on the while loop. Further, do while loops syntax just ends in "while()".