FCC: Nesting For Loops

Instructions:

Write a function multiplyAll so that it multiplies the product variable by each number in the sub-arrays of arr.

Solution: 

  • Iterate through inner subarrays with j.
  • Then iterate through the outer array with i.
  • Multiply each item with the stored result (product) as you iterate.

screen-shot-2017-01-11-at-11-45-30-pm

Test Cases: 

screen-shot-2017-01-11-at-11-46-10-pm

Advertisements
FCC: Nesting For Loops

Hackerrank Day 11: 2D Arrays

screen-shot-2016-12-22-at-7-53-09-pm

screen-shot-2016-12-22-at-7-54-15-pm

My Solution in Ruby:

screen-shot-2016-12-22-at-7-54-59-pm

This problem was a lot easier to tackle once I’ve sketched out the formula for calculating each hourglass.  That’s why I bought a notebook to derive future algorithms!

Also downloaded git and cleaned up my github today!  A few commands to remember when adding files and committing changes:

  1. Stage the file: git add .filename
    • stage a folder with files: git add folder/subfolder/*
  2. Commit: git commit -m “enter notes/messages about the changes
  3. Push to master branch: git push origin master
    • Push to another branch: git push origin BRANCH_NAME
Hackerrank Day 11: 2D Arrays

Rectangle Intersection

Write a function, `rec_intersection(rect1, rect2)` and returns the intersection of the two.

Rectangles are represented as a pair of coordinate-pairs: the bottom-left and top-right coordinates (given in `[x, y]` notation).

Hint: You can calculate the left-most x coordinate of the intersection by taking the maximum of the left-most x coordinate of each rectangle. Likewise, you can calculate the top-most y coordinate of the intersection by taking the minimum of the top most y coordinate of each rectangle.

This is probably the hardest problem I’ve encountered do date.  It’s a bit more logic than math and I definitely overcomplicated it by trying to make sense of it with math, which is not my strength..

Some helpful things to remember:

  • Plot out the coordinates and draw the rectangles on a piece of paper first.
  • Try not to confuse the (x,y) coordinates with arrays.  (This part tripped me up the most).
  • The trick is to use max and min to get the left and right coordinates of the intersection, respectively.   (This is a bit counterintuitive).
  • To access a value of a multidimensional array, use a[i][j], where i is the index of a, and j is the index of a[i] array.

Anyways, here’s the solution with my annotated comments:

screen-shot-2016-11-30-at-2-38-20-pm

Test Cases: 

Screen Shot 2016-11-30 at 2.37.47 PM.png

Rectangle Intersection