Coding Questions

Ace your homework & exams now with Quizwiz!

What does x return when: var x = 16 + "Volvo"

x = 16Volvo When the second operand is a string, JS will treat the first type as a string.

What does x return when: var x = 16 + 4 + "Volvo"

x = 20Volvo JS evaluates left to right.

What does x return when: var x = "Volvo" + 16 + 4;

x = Volvo164 Since the first operand is a string, the others are treated as such.

What is the value of foo? var foo = 10 + '20';

'1020' - because of type coercion

AJAX sorting list

Questions: Approach: How to Test:

Write a constructor function for a rectangle

Questions: Approach: var Rectangle = function (height, width){ this.height = height, this.width = width; this.area = function(){ return(width*height) } return } How to Test:

Duplicator -Write a function that duplicates an array

Questions: - Approach: Array.prototype.duplicator() = function() { return this.concat(this) } How to Test:

What is the difference between a stack and a heap?

Stack: Used for static memory allocation Heap: Used for dynamic memory allocation Both stored in the computer's RAM Stack has much faster lookups

Difference between "this" and "self"

"this" in Javascript is more flexible than "self" in Ruby. Self refers to the current object. It doesn't hold the title for long - once any method is called, it's receiver is self. This can refer to anything and at any time. It references the immediate parent or object a method is being called upon - or the window object globally.

Given a list of IDs, which contains many duplicate integers and one unique integer, find the unique integer.

A brute force approach would use two nested loops to go through every ID and check every other ID to see if there's a duplicate. This would take O(n^2)O(n ​2 ​​ ) time and O(1)O(1) space. Can we bring that runtime down? Well, we know every integer appears twice, except for one integer, which appears once. Can we just track how many times each integer appears? We could iterate through the list and store each integer in a dictionary, where the keys are the integers and the values are the number of times we've seen that integer so far. At the end, we'd just need to return the integer we saw one time.

What value is returned from the following statement? "i'm a lasagna hog".split("").reverse().join("");

A reversed string

Find the intersection of two arrays.

Compare both arrays using while the length of each array is greater than 0 Both arrays are assumed to be sorted here - so sort them if not! Declare an empty array If a[0] is less than b[0] - shift off a[0] else if b[0 is less than a[0] - shift off b[0] else they're equal, so push a[o].shift() into the empty array and shift off b[0]

What is the outcome of the two alerts below? var foo = "Hello"; (function() { var bar = " World"; alert(foo + bar); })(); alert(foo + bar);

First alert reads "Hello World" - as the assignment/declaration is made before the function is invoked. The second alert fails, as bar is undefined.

Design an OOP Elevator system.

First, there is an elevator class. It has a direction (up, down, stand, maintenance), a current floor and a list of floor requests sorted in the direction. It receives request from this elevator. min_floor & max_floor are two additional attributes for Elevator. Then, there is a bank. It contains the elevators and receives the requests from the floors. These are scheduled to all active elevators (not in maintenance). The scheduling will be like: if available pick a standing elevator for this floor. else pick an elevator moving to this floor. else pick a standing elevator on an other floor. else pick the elevator with the lowest load. Each elevator has a set of states. Maintenance: the elevator does not react to external signals (only to its own signals). Stand: the elevator is fixed on a floor. If it receives a call. And the elevator is on that floor, the doors open. If it is on another floor, it moves in that direction. Up: the elevator moves up. Each time it reaches a floor, it checks if it needs to stop. If so it stops and opens the doors. It waits for a certain amount of time and closes the door (unless someting is moving through them. Then it removes the floor from the request list and checks if there is another request. If so the elevator starts moving again. If not it enters the state stand. Down: like up but in reverse direction. There are additional signals: alarm. The elevator stops. And if it is on a floor, the doors open, the request list is cleared, the requests moved back to the bank. door open. Opens the doors if an elevator is on a floor and not moving. door closes. Closed the door if they are open.

Shuffle an array.

Fisher-Yates Shuffle The fastest way to shuffle is to do the entire shuffle in-place, without any extra space. The back of the array stores the shuffled elements, and the front of the array stores the remaining elements. Use a while loop to track the length of the array and replace elements all the way down the line. myArray = [9, 5, 4, 3, 7, 8, 1, 2]; function shuffle(array) { var m = array.length, t, i; while (m) { i = Math.floor(Math.random() * m--) t = array[m]; array[m] = array[i]; array[i] = t; } return array } shuffle(myArray)

Pluck values from key/value pairs -Pull the values for a key - like "Price" or "Artist" - from an array of key/value pairs

Question: Approach: var pluck = function(someArray, someKey) { var result = someArray.map(function (currentValue, index){ return currentValue[someKey]; }); return result; }; var albums = [ {'name': 'Gossamer', 'artist': 'Passion Pit'}, {'name': 'Sigh no more', 'artist': 'Mumford and Sons'}, {'name': 'Time to Pretend', 'artist': 'MGMT'} ]; var plucked = pluck(albums,'artist'); console.log(plucked); How to Test:

Reverse a String -Write a function that takes in a string and returns the reverse of it without using .reverse()

Questions to ask: -Can I use array methods? Approach: -Convert the string to an array with .split(', ') -Inside a for loop for the length of the array, use the return of pop() to unshift() to the front of the array. -Outside of the loop, use .join('') to convert the new array back to a string How to Test:

FizzBuzz: -Return Fizz on multiples of 3, Buzz on multiples of 5, FizzBuzz on multiples of both

Questions to ask: -What is the range? Beginning at 1 or 0 - ending where? -Any specificity for the output? CSV, string, array? Approach: -inside function and for loop, declare variables for modulos. -start with most exclusive conditional first (&&) -end with returning i How to Test:

Filter emails -Your program will be passed a data file with the specific string to search for and a list of e-mail subjects. Your program should return the single e-mail subject that has the most occurrences of the provided search string. Search should be not be case-sensitive and the string doesn't have to be full words.

Questions: Approach: How to Test:

Find a commonality -In an org, given two employees, find their common manager

Questions: Approach: How to Test:

Javascript Closures -Write a function that serves as an example of a JS Closure

Questions: Approach: How to Test:

Mergesort / Quicksort

Questions: Approach: How to Test:

Parking Lot Spaces -There's a parking lot with infinity spaces and the attendant knows which ones are taken. How can he tell a new driver where the closest available spot is?

Questions: Approach: How to Test:

jQuery tabs

Questions: Approach: How to Test:

isPalindrome() Write a simple function that returns a boolean indicating whether or not a string is a palindrome.

Questions: Approach: var is_palindrome = function (string){ var length = string.length; for (var i = 0; i <=Math.round(length/2); i++) { //i did this to account for even and odd numbers. if (string.charAt(i) === string.charAt(length-1-i)) { //i did this to compare R to L and L to R! return true } else { return false } } } console.log(is_palindrome(string)); How to Test:

Anagrams -Like "Asleep" and "Please" - write a function to determine whether two words are anagrams of one another?

Questions: Approach: For each array of words, you must split, sort and join. Then you compare arrays in a loop if a[i] === b[i] then it's an anagram. How to Test:

Fibonacci Sequence: Number hunt -Find a specific number in any spot in the Fibonacci Sequence.

Questions: Approach: Run the Fib Sequence Array with the index number in question as the length (i < num) in the loop Use pop(index) to find that value from the Fib Sequence array. How to Test:

Removing duplicates -Remove duplicates in an array

Questions: Approach: Use filter! The filter function will allow you to create a new array, using a callback function once for each element in the array. So you could set up the unique array like this: var duplicatesArray = ['mike','james','james','alex']; var uniqueArray = duplicatesArray.filter(function(elem, pos) { return duplicatesArray.indexOf(elem) == pos; }); The unique array will run through all of the values in the duplicate array. The elem variable represents the value of the element in the array (mike,james,james,alex), the position is it's 0-indexed position in the array (0,1,2,3...), and the duplicatesArray.indexOf(elem) value is just the index of the first occurrence of that element in the original array. So, because the element 'james' is duplicated, when we loop through all of the elements in the duplicatesArray and push them to the uniqueArray, the first time we hit james, our "pos" value is 1, and our indexOf(elem) is 1 as well, so James gets pushed to the uniqueArray. The second time we hit James, our "pos" value is 2, and our indexOf(elem) is still 1 (because it only finds the first instance of an array element), so the duplicate is not pushed. Therefore, our uniqueArray contains only unique values. How to Test:

Zip two arrays Take two arrays, and combine them. Input- var artists = ["Passion Pit", "Mumford and Sons", "MGMT"]; var albums = ["Gossamer", "Sigh no more", "Time to Pretend"]; Output- [ [ 'Passion Pit', 'Gossamer' ], [ 'Mumford and Sons', 'Sigh no more' ], [ 'MGMT', 'Time to Pretend' ] ]

Questions: Approach: var artists = ["Passion Pit", "Mumford and Sons", "MGMT"]; var albums = ["Gossamer", "Sigh no more", "Time to Pretend"]; var zip = function (firstArray, secondArray){ var result = firstArray.map(function(element, index){ return [element, secondArray[index]] }) return result; }; console.log(zip(artists,albums)); How to Test:

Compress a String -Use a pattern and consolidate the amount of characters into a simplified string var input = "AAASSSDDDDRDDSASSDDDSSSAD" output pattern = 3A3S4DR2DSA2S3D3SAD If a character is represented more than once, append the number of occurrences in front of it. If a character is only represented once, just put that letter

Questions: Approach: var input = "AAASSSDDDDRDDSASSDDDSSSAD" var compress = function(string) { var counter = 1; var output = ''; for (var i=0; i<=string.length; i++) { if (string[i] === string[i+1]) { counter++; output+= counter+1 + string[i]; } else if (word[i] !== word[i+1]) { counter = 1; output+= string[i]; } return output } }; console.log(compress(input)); How to Test:

Prime Number Return true or false to indicate whether or not a number is a prime number.

Questions: Approach: var isPrime = function(num) { if (isNaN(num)) { return false } if ((num %2 === 0) && (num !== 2) || (num !== 3) && (num%3 === 0) || (num%5===0) || (num%7===0)) { return false } else if ((Math.sqrt(num))%1 === 0) { return false } else { return true } }; console.log(isPrime(397)); How to Test:

Make a To-Do list with jQuery

Questions: -Confirm adding, editing, deleting functionality Approach: $(document).ready(function(){ $(".add-btn").on("click", function(e){ e.preventDefault; var text = $('#string').val() var listItem = $("<li>").text(text); var del = $('<button class="btn btn-xs btn-danger">X</button>'); listItem.append(del); del.click(function(){ $(this).closest('li').remove(); }); $(".list").append(listItem); $('#string').val(''); }) }); How to Test:

Fibonacci Sequence -Find the first 10 numbers in the Fibonacci Sequence.

Questions: -Fibonacci Sequence clarification - Next fibonacci number = previous + one before previous Approach: var fib = []; fib[0] = 0; fib[1] = 1; for(i=2; i<=10; i++) { fib[i] = fib[i-2] + fib[i-1]; console.log(fib[i]); } Test:

Sum method Write a sum method which will work properly when invoked using either syntax below. console.log(sum(2,3)); // Outputs 5 console.log(sum(2)(3)); // Outputs 5

Questions: -For testing, should I take into account the type of argument - test for isNan? Approach: Use arguments.length to access the (2)(3) vals as part of an array and then use arguments[0] + arguments[1] - as well as a normal x + y function in if else How to Test:

Find the missing number in an array -In an array of numbers 1-100, one number is missing. Find it and print it.

Questions: -Is the array already sorted? -Is the array increasing or decreasing? Approach: var array = [1,2,3,4,6,7,8] var findMissing = function(arr) { for (var i=0; i < arr.length; i++) { if (arr[i] - (arr[i] - 1) != 1){ console.log (arr[i]) } } } findMissing(array) How to Test: -Use a different, higher range of numbers -Use an array of strings

isInteger(x) -Write a function that determines if x is an integer

Questions: -Lots of ways to do it - preference on using Math.round or typeOf with modulo? Approach: -Return must be a boolean - so write it in a conditional How to Test:

What does .substr() do?

Returns characters in a string beginning at the specified location. Two parameters - starting index and length. If length isn't specified, the characters from the start until the string's end will be returned. Otherwise, you can specify the amount of characters you'd like. Negative value in starting index begins at the end. Negative or 0 value for length returns an empty string.

Flatten an array of arrays Input: ([[1, 2, 3], [4,5,6],7]) Output: [1, 2, 3, 4, 5, 6, 7]

input.reduce(prev, current) { prev.concat(current) },[];

What will be the output of the code below? console.log(0.1 + 0.2 == 0.3);

This is a trick question in that at first glance, you might expect the console to print out "true" The correct answer is that you can't know for sure, because of how JavaScript treats floating point values. In fact, in the above example, it will print out:

Design a Blackjack game.

Use constructor functions to set up basic functionality of the game for Card and Hand - then write the game play functions for user, dealer and declaring a winner. Card(suit, number): suits=["Hearts","Diamonds","Clubs","Spades"]; ranks=["Ace","King","Queen","Jack",2,3,4,5,6,7,8,9,10]; Card.prototype.getNumber Card.prototype.getSuit Card.prototype.getValue (converts facecards to 10, chooses whether Ace is 1 or 11 or keeps number value) ---- Deal function returns new Card (random suit and random value) ---- Hand is a function with two cards using Deal Hand.prototype.getHand & printHand Hand.prototype.hitMe deals one more card Hand.prototype.score does the math to change the ace to a one if score is over 11 and also calculates the value of each hand --- Game functions: playAsDealer - deals with hitting if under 17 playAsUser - brings in new hand, score and hit me declareWinner(userHand, dealerHand) does the math to compare both hands playGame runs declareWinner with playAsUser and playAsDealer

Print out all permutations of a string.

Use substr after checking if the string's length is greater than 0 - or returning if the string is 1. function permutate(word){ if (!word || !word.length) return; print(word); if (word.length == 1) return; var c = word[0]; var rem = word.substr(1); for (i in rem+1){ if (i==0) continue; var perm = rem.substr(0, i) + c + rem.substr(i); print(perm); } permutate(rem); print(c); } idx = 0; function print(text){ document.getElementById('perm-result').innerHTML += ++idx + ' '; document.getElementById('perm-result').innerHTML += text + '<br />'; } function clear(){ document.getElementById('perm-result').innerHTML = ''; } function toArray(text){ var a = []; for (c in text) a.push(text[c]); return a; }

What is the value of window.foo? ( window.foo || ( window.foo = "bar" ) );

bar

What is the difference between the following outputs? var y = 123e5; var z = 123e-5;

e is for scientific notation. y is zeros from decimal point to the left - z is to the right of the decimal point that number of places y = 12300000 z = 0.00123

What is the value of foo.length? var foo = []; foo.push(1); foo.push(2);

foo.length = 2

What is the value of foo.x? var foo = {n: 1}; var bar = foo; foo.x = foo = {n: 2};

foo.x is undefined - Rather, bar.x is {n: 2}. foo.x = foo = {n: 2} is the same as foo.x = (foo = {n: 2}). It is because a left term is first referenced and then a right term is evaluated when an assignment is performed in JavaScript. When foo.x is referenced, it refers to an original object, {n: 1}. So, when the result of the right term, {n: 2}, is evaluated, it will assigned to the original object, which is at the moment referenced by bar.

How can you return 5? var obj = { x: 5 } var getX = function({return this.x})

getX.apply(obj)

What does the following code print? console.log('one'); setTimeout(function() { console.log('two'); }, 0); console.log('three');

one / three / undefined / two undefined because return value (ID) of setTimeout is undefined until the method runs - and then it outputs 2

int [] elements = {99, 8, 47, 51, 9, 22, 47, 74, 33}; int duplicate = findDuplicate(elements); private int findDuplicate(int [] elements) { }

var arr = (int [] elements).split('').sort() private int findDuplicate(int [] elements) { for (var i = 0; i < arr.length; i++){ if (arr[i] === arr[i+1]){ return arr[i] } } } VERDICT: Too heavily reliant on library methods that may not be efficient - what's happening under the hood with sort? Try it without sorting at all. NEXT SOLUTION: shifting item off the front of the array into a new array to compare it to the index 0 of the old array - VERDICT: too much memory to create another dataset FINAL SOLUTION: non-destructive - comparing index[0] to all successors - then comparing index[1] to all successors - etc. VERDICT: Winner!


Related study sets

Economics of Immigration - Chapter 11

View Set

Voting, Elections, and Campaigns

View Set

ICS 184 - Quiz 2 Networking infrastructure and documentation

View Set