JavaScript Objects

Object.keys(obj) returns an array of keys in a hash object.

Examples:

var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']

// array like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']

// array like object with random key ordering
var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(an_obj)); // console: ['2', '7', '100']

Object.values(obj) returns an array of values in a hash object.

Examples:

var obj = { foo: 'bar', baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]

// array like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.values(obj)); // ['a', 'b', 'c']

// array like object with random key ordering
var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.values(an_obj)); // ['b', 'c', 'a']

obj.hasOwnProperty(prop) returns true/false indicating if an object has the specified property (key, NOT value).

Examples:

var object = {cat: 'meow'};
object.hasOwnProperty('cat'); // true
object.hasOwnProperty('meow'); // false

To access a property’s value:  object[key]

Example:  object['cat']; // 'meow'

Advertisements
JavaScript Objects

Hackerrank Day 0: Means, Median, Mode

screen-shot-2016-12-28-at-2-27-26-pm

My Solution in Ruby: 

screen-shot-2016-12-28-at-2-26-37-pm

This was a good review on arrays and hashes.

  • Find the sum of all elements in an array with: array.inject(0){|sum, x| sum + x}
  • Store number of occurrences in hashes so you can retrieve key-value pairs based on its value or key attributes.
  • String can be converted to array with .split(‘ ‘).map(&:to_i).
Hackerrank Day 0: Means, Median, Mode

Hackerrank Day 8: Dictionaries and Maps

Task

Given names and phone numbers, assemble a phone book that maps friends’ names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each name queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entry for name is not found, print Not found instead.

Note: Your phone book should be a Dictionary/Map/HashMap data structure.

Input Format

The first line contains an integer, n, denoting the number of entries in the phone book.
Each of the n subsequent lines describes an entry in the form of 2 space-separated values on a single line. The first value is a friend’s name, and the second value is an 8-digit phone number.

After the n lines of phone book entries, there are an unknown number of lines of queries. Each line (query) contains a name to look up, and you must continue reading lines until there is no more input.

Note: Names consist of lowercase English alphabetic letters and are first names only.

Constraints
≤ n 10^5
≤ queries 10^5
Output Format
On a new line for each query, print Not found if the name has no corresponding entry in the phone book; otherwise, print the full name  and phoneNumber in the format name=phoneNumber.
Sample Input
3
sam
99912222
tom
11122222
harry
12299933
sam
edward
harry
Sample Output
sam=99912222
Not found
harry=12299933

My Solution: 

screen-shot-2016-12-15-at-1-25-02-pm

Retrieving user input is probably the biggest challenge when working on Hacker Rank problems.

Need to review STDIN and all that jazz.

Hackerrank Day 8: Dictionaries and Maps

Morse Code

Build a function, ‘morse_encode(str)’ that takes in a string (no numbers or punctuation) and outputs the morse code for it. See http://en.wikipedia.org/wiki/Morse_code. Put two spaces between words and one space between letters.

You’ll have to type in morse code: I’d use a hash to map letters to codes. Don’t worry about numbers.

My solution:

I learned the difference between global variables and Ruby constants while solving this problem.  They both serve similar purposes but global variables’ values can be changed while Ruby constants cannot.  Also, constants are written in all uppercase and global variables start with “$”.

Another thing to remember is how to retrieve key/value from hash.  Here’s a handy cheat sheet of shortcuts for Ruby hashes.

screen-shot-2016-11-29-at-5-48-39-pm

Test Cases: 

screen-shot-2016-11-29-at-5-41-43-pm

Morse Code

Enumerables

.all? {|obj| block } -> true or false

Passes each element of an array (or collection) to the block.  Returns true if the block never returns false or nil.

%w[ant bear cat].all? { |word| word.length >= 3 } #=> true
%w[ant bear cat].all? { |word| word.length >= 4 } #=> false
[nil, true, 99].all?                              #=> false

 

.any? {|obj| block } -> true or false

Passes each element of an array (or collection) to the block.  Returns true if the block ever returns false or nil.

%w[ant bear cat].any? { |word| word.length >= 3 } #=> true
%w[ant bear cat].any? { |word| word.length >= 4 } #=> true
[nil, true, 99].any?                              #=> true

 

.map / .collect {|obj| block } -> array

Returns a new array with the results of each element in the enum.  If no block is given, returns an enumerator.

(1..4).map { |i| i*i }      #=> [1, 4, 9, 16]
(1..4).collect { "cat"  }   #=> ["cat", "cat", "cat", "cat"]

 

.max / max(n) {|a, b| block } -> object

Returns the object with the maximum value.  When an argument is given, returns maximum n elements.

The first form assumes all objects implement Comparable; the second uses the block to return a <=> b.

a = %w(albatross dog horse)
a.max                                     #=> "horse"
a.max { |a, b| a.length <=> b.length }    #=> "albatross"
a.max(2)                                  #=> ["horse", "dog"]
a.max(2) {|a, b| a.length <=> b.length }  #=> ["albatross", "horse"]

 

.max_by / max_by(n) {|a, b| block } -> object

Returns the object with the maximum value from the given block.  When no block is given, returns an enumerator instead.

a = %w(albatross dog horse)
a.max_by { |x| x.length }   #=> "albatross"
a.max_by(2) {|x| x.length } #=> ["albatross", "horse"]

 

.min / min(n) {|a, b| block } -> object

Returns the object with the minimum value.  When an argument is given, returns minimum n elements.

a = %w(albatross dog horse)
a.min                                   #=> "albatross"
a.min { |a, b| a.length <=> b.length }  #=> "dog"a.min(2)                                  #=> ["albatross", "dog"]
a.min(2) {|a, b| a.length <=> b.length }  #=> ["dog", "horse"]

 

.min_by / min_by(n) {|a, b| block } -> object

Returns the object with the minimum value from the given block.  When no block is given, returns an enumerator instead.

a = %w(albatross dog horse)
a.min_by { |x| x.length }   #=> "dog"
p a.min_by(2) {|x| x.length } #=> ["dog", "horse"]

 

.minmax / minmax { |a, b| block } -> [min, max] 

a = %w(albatross dog horse)
a.minmax                                  #=> ["albatross", "horse"]
a.minmax { |a, b| a.length <=> b.length } #=> ["dog", "albatross"]
a.minmax_by { |x| x.length }   #=> ["dog", "albatross"]

 

.include?(obj) -> true or false

Returns true if any members of enum is equal to object.

"hello".include?("e")         #=> true
"hello".include?("a")         #=> false

 

.group_by { |obj| block } -> hash

Returns a hash where the keys are the evaluated results from the block and the values are arrays of elements in the collection that correspond to the keys. If no block is given, returns an enumerator.

(1..6).group_by { |i| i%3 }   #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]}

 

.select { |obj| block } -> array 

Returns an array containing all the elements in the enum for which the given block evaluates true.

[1,2,3,4,5].select { |num|  num.even?  }   #=> [2, 4]

 

.sort { |obj| block } -> array 

Returns an array containing all the items sorted by the results of the block.

%w(rhea kea flea).sort          #=> ["flea", "kea", "rhea"]
(1..10).sort { |a, b| b <=> a }  #=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

 

.sort_by { |obj| block } -> array 

Sorts enum using a set of keys generated by mapping the values in enum through the given block.

%w{apple fig}.sort_by {|word| word.length} #=> ["pear", "apple"]
Enumerables

Letter Count

Write a function, ‘letter_count(str)’ that takes a string and
returns a hash mapping each letter to its frequency. Do not include
spaces:

Test Cases:

screen-shot-2016-11-18-at-5-42-12-pm

My Solution:

screen-shot-2016-11-21-at-12-37-37-pm

Runtime:  0.00059 seconds

Provided Solution:

Screen Shot 2016-11-21 at 12.38.20 PM.png

Runtime:  0.00053 seconds

By using each_char (an enumerator), you’re able to skip splitting the string into words and then into letters. Instead, you can directly pull letters from the string as is.

Letter Count

Converting hash values into keys

Create an empty hash called ‘dogs’: 

irb(main):001:0> dogs = {}

=> {}

Enter the keys and values for dogs (‘compton’ is key, ‘doodle’ is value):

irb(main):002:0> dogs[‘compton’] = :doodle

=> :doodle

irb(main):003:0> dogs[‘hazel’] = :doodle

=> :doodle

irb(main):004:0> dogs[‘ebi’] = :maltese

=> :maltese

irb(main):005:0> dogs[‘cub’] = :coton

=> :coton

irb(main):006:0> dogs[‘walle’] = :havanese

=> :havanese

Show the key-value pairs for the hash: 

irb(main):007:0> dogs

=> {“compton”=>:doodle, “hazel”=>:doodle, “ebi”=>:maltese, “cub”=>:coton, “walle”=>:havanese}

Create a new hash called ‘breeds’ that sets the default values for all pairs at 0: 

irb(main):008:0> breeds = Hash.new(0)

=> {}

Convert the values for ‘dogs’ into keys for the new ‘breeds’ hash  (‘count’ will be the values): 

irb(main):009:0> dogs.values.each { |count| breeds[count] += 1 }

=> [:doodle, :doodle, :maltese, :coton, :havanese]

Show the key-value pairs for ‘breeds’: 

irb(main):010:0> breeds

=> {:doodle=>2, :maltese=>1, :coton=>1, :havanese=>1}

Converting hash values into keys