9.19 Study Log

2.75h.  Day 79! Today I did some more HackerRank problems and finished off the last of the #freeCodeCamp intermediate algorithm problems. I have 1/5 final projects done as well! Lastly I have been getting the InterviewCake newsletter and it has interesting interview problems in it. I’ll include the one from today below.

the problem was to solve for the nth fibonnaci number.
my solve

interview Cake return the nth fib problem

function fib(n){ //O(n) time and O(1) space.
let thisFib=1;
let lastFib=1;
for (let i=2;i<n;i++){
[thisFib,lastFib]=[lastFib+thisFib,thisFib]
}
return thisFib
}
fib(2)

Their solution:

def fib(n):
# Edge cases:
if n < 0:
raise ValueError('Index was negative. No such thing as a '
'negative index in a series.')
elif n in [0, 1]:
return n

# We'll be building the fibonacci series from the bottom up
# so we'll need to track the previous 2 numbers at each step
prev_prev = 0  # 0th fibonacci
prev = 1       # 1st fibonacci

for _ in xrange(n - 1):
# Iteration 1: current = 2nd fibonacci
# Iteration 2: current = 3rd fibonacci
# Iteration 3: current = 4th fibonacci
# To get nth fibonacci ... do n-1 iterations.
current = prev + prev_prev
prev_prev = prev
prev = current

return current

Here are the FCC problems. The hackerRank ones weren’t that interesting. (I’m not up to the hard stuff yet.)

EVERYTHING BE TRUE
Check if the predicate (second argument) is truthy on all elements of a collection (first argument).
In other words, you are given an array collection of objects. The predicate prewill be an object property and you need to return trueif its value is truthy. Otherwise, return false.
In JavaScript, truthyvalues are values that translate to truewhen evaluated in a Boolean context.
Remember, you can access object properties through either dot notation or []notation.
function truthCheck(collection, pre) {
/*
strategy
iterate through each object and the first key pair
check if the predicate is present in all properties
return true if present, false if not.
*/
let outStatus=true
collection.forEach(function(each){
if (each.hasOwnProperty(pre)!=true){
outStatus=false
}
if (Boolean(each[pre])!=true){
outStatus=false
}
})
return outStatus;
}

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

/*
what I learned
how to use Boolean() to sheck for truthyness
this took a little fiddling to figure out how to make all tests pass, but I'm no upset about that. That seems like a normal development workflow.
*/
Create a function that sums two arguments together. If only one argument is provided, then return a function that expects one argument and returns the sum.
/*
Strategy
use ...args to capture args
test for length
if two
and they are valid numbers
then return sum
else
return undefined
if one then return a function looking for another input
similarly look for valid numbers
*/
if (args.length==2){
if ((typeof args[0]=='number')&&(typeof args[1]=='number')){
return args[0]+args[1]
} else {
return undefined
}
} else {
if ((typeof args[0]=='number')){
if (typeof secondNumber=='number'){
return secondNumber+args[0]
} else {
return undefined
}
}
} else {
return undefined
}
}
}

/*
WHAT I LEARNED
I NEED TO CLEAN MY KEYBOARD.  It is greasy
function(a)(b) will call b as the arg for the function returned from function(a)
*/

MAKE A PERSON

var Person = function(firstAndLast) {
/*
strategy
make a bunch of methods to do those things
*/
// Complete the method below and implement the others similarly
let first=firstAndLast.split(" ")[0]
let last=firstAndLast.split(" ")[1]

this.getFullName = function() {
return (first + " " + last);
};
this.getFirstName = function() {
return (first);
};
this.getLastName = function() {
return (last);
};
this.setFullName = function(firstAndLast) {
first=firstAndLast.split(" ")[0]
last=firstAndLast.split(" ")[1]
};
this.setFirstName = function(firstIn) {
first=firstIn
};
this.setLastName = function(lastIn) {
last=lastIn
};
return firstAndLast;
};

var bob = new Person('Bob Ross');
/*
What I learned.
the methods were pretty easy
then I failed the "6 keys" test
Eventually I remembered the idea of local variables (closure) and applied that.
*/
MAP THE DEBRIS
Return a new array that transforms the elements’ average altitude into their orbital periods (in seconds).
The array will contain objects in the format {name: ‘name’, avgAlt: avgAlt}.
The values should be rounded to the nearest whole number. The body being orbited is Earth.

/*
strategy
look up the equation and write it in javascript
*/

//2pi times the square root of the (radius cubed divided by GM)
function orbitalPeriod(arr) {
for (let i=0;i<arr.length;i++){
var GM = 398600.4418;
delete arr[i].avgAlt
arr[i].orbitalPeriod= orbitalPeriod
}
return arr
}

console.log(orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]));

/*
lessons learned
I initially didn't consider the second case where there are multiple objects in the array
I had to do some head scratching to sort out the square root, squared, and rounding.
I initially wasnt adding the earth's radius to the avgAlt, I guess I was assuming that it was already included in the number
*/

PALINDROME CHECKER

function palindrome(str) {
/*
strategy
sanitize the string, and lowercase it.
use a loop to iterate through the split string
compare first and last values
with i and length-i-1
if they are the same, keep going
it they are not, return false
at the end of the loop, return true
*/
str=str.toLowerCase()
str=str.match(/[a-zA-Z0-9]*/g).join("")
let reversed=str.split("").reverse().join("")
return reversed==str
}

palindrome("eye”);
palindrome("never odd or even")
palindrome("not a palindrome")
palindrome("0_0 (: /-\ :) 0-0")

/*
lessons learned
I struggled trying to make reversed work. I never should have trusted autocomplete
I misunderstood the question about whitespace. I should have read more slowly.
I am happy I was able to do it without any loops and in so few lines.
*/

This site uses Akismet to reduce spam. Learn how your comment data is processed.