Matrix Spiral… Whew!

In brushing up on computer science fundamentals, I came across the topic of matrices. The sight alone of them can seem pretty daunting and requires the introduction of several variables at once, which can add layers of complexity to the problem, but once you see the solution, it’ll make a lot of sense . Thought I’d dissect a matrix example today.

Here’s the problem: Write a function that accepts an integer N and returns a NxN spiral matrix.

Examples:

Screen Shot 2018-02-12 at 10.40.46 AM.png

In the above example, you can see what outputs we should receive when specific input is plugged in. For example, when we call matrix(3), we should see 1, 2, 3 running from left to right on the top row, then the numbers increment as we travel down the matrix vertically, then to the left, up, and inwards towards the center, as a spiral does in a clockwise pattern. You’ll notice that each row is its own subarray. It’s easiest to see the pattern with larger inputs, as shown in the last example.

As you can see, it’s not a straightforward problem to solve and you’d be hard pressed to find a solution if you started simply writing code immediately from the outset. It’s important to draw a diagram to think through and visualize how you’re going to solve the problem before diving into it.

Screen Shot 2018-02-12 at 10.55.46 AM.png

First, below, we create an empty array called results, into which we’re going to be pushing all the subarrays. We will ultimately have n number of subarrays in the results array, so we want to loop through and push n arrays into our results array.

Screen Shot 2018-02-12 at 11.19.45 AM.png

If n = 3 and at this point, we console.log results, we’ll have three empty subarrays within a larger one, or [[], [], []].

We need to create a counter variable starting at one, and variables for the current position of each of the rows and columns indicated above based on the value of n, which is passed into the function. Keep in mind that these values will be changing throughout the course of the problem to remind ourselves what rows and columns we’re working on.

Screen Shot 2018-02-12 at 11.23.26 AM.png

We’re going to be doing a series of loops–starting from the start column and ending in the end column–that will determine the values that need to be inserted in between those by assigning it the counter variable and then incrementing it. While the start column is less than the end column and the start row is less then the end row, we’re going to be looping through and filling out the values in the matrix.

Here, we iterate from the start column to the end column. At results[start_row][i], we assign the counter variable, then we increment the counter.

Screen Shot 2018-02-12 at 11.24.35 AM.png

After the loop has gone through the top row, we then increment the start row value, which moves the start row to the second row – the value of the start row is now one. Then, since the top row values have been completed, we only deal with the remaining values that need to be filled in located in the second and third rows. Our second loop goes from the start row to the end row. Similar to the last loop, at results[i][end_column], or in this case, results[2][2], we assign a counter variable, then increment the counter by one.

Screen Shot 2018-02-12 at 11.08.26 AM.png

Screen Shot 2018-02-12 at 11.28.06 AM.png

After that, we decrement the end column. This gives us the limits of the areas we are trying to figure out the values of. At this point, we’re missing the four digits in the bottom left hand corner of the matrix.

Screen Shot 2018-02-12 at 11.11.55 AM.png

We then do the same for the other two sides.

Screen Shot 2018-02-12 at 11.28.56 AM.png

Here’s what the final solution looks like:

Screen Shot 2018-02-12 at 10.59.32 AM.png

 

 

 

 

 

Girl power! Resources for female job-hunting software engineers (and any stage of your career, really)

Transitioning from a background of public relations, which in NYC is primarily female-dominated, to software engineering, has been interesting. I’m not used to being the minority, so I’ve found myself being drawn to girl-focused meetups and might’ve even spent a whole day researching useful tools, groups, meetups, job boards and more that promote female empowerment. As a software engineer who’s just starting out in the field, it has been inspiring to hear women CTOs unravel their career tales and endearing to hear tidbits about their struggles and triumphs. Thought I’d share with you all today a few platforms that have been instrumental for me so far.

 

Tech Ladies
Tech group with networking perks and job drop emails for women. They have two membership levels–one free, one paid where you’ll be identified as a founding member–and on either level, you can email the team to request them to send your cover letter/resume directly to their contact for any job you’ve already applied from their list of jobs. 

“Tech Ladies is a robust and worldwide community with 20,000 members.

Founded by Allison Esposito who has worked for startups and tech companies including Google and Foursquare, our mission is to connect you with the best opportunities in tech, and to connect companies with the best techmakers.”

Fairygodboss
Female job board and company review site, based on thoughts and ratings from the perspective of women. Includes morsels of truth from real women about childcare and healthcare availability, work-life balance, existing networking groups for women, maternity leave, and other sorts of insider details.

“Born in 2015 while our CEO was interviewing while 2 months pregnant (and hiding it), Fairygodboss helps women get hard-to-ask questions answered. We help you get the inside scoop on pay, corporate culture, benefits and work flexibility. We offer company ratingsjob listingsdiscussion boards and career advice.”

Career Contessa
Career website for women in any stage of a career. Features job advice, interviews, articles, webinars, coaching, e-learning opportunities and reviews for women; also has a job board.

“We help women cultivate successful careers through expert advice, interviews, and videos, one-on-one mentoring, online skills-based courses and resources, and a curated job board that speaks to our audience. Everything we do comes straight from the best kind of experts—real women who’ve been there and successfully done that.

We believe in a holistic approach to improving women’s careers so we also work in reverse, partnering with savvy companies to help them engage, hire, and retain top female talent through on-site talent development programs, educational marketing opportunities, and in-depth company profiles. Because career paths are no longer linear, supporting professional development is more important than ever in company cultures. Our programs help bridge the divide between employer and employee and build lasting relationships.”

Women Who Code NYC
Meetup group with longstanding algorithm practice meetup, plus events with women panelists and hacknights.

“A nonprofit organization that is one of the largest communities of women engineers in the world. Free technical study groups, Events featuring influential tech industry experts and investors, Hack events, Career and leadership development. Current and aspiring coders are welcome.”

Women in Software Engineering NYC
Another meetup group, mainly featuring talks led by powerful women in tech.

“This group is for anyone who supports the empowerment and equal representation of women and other minority groups in software engineering, specifically, as well as the broader tech industry. Every month, we will be showcasing talks and projects by powerful women leading innovation in tech.”

League of Women Coders
Hosts monthly event, “Cupcakes and Code: A Hacknight,” as a forum for women to share their side projects, ask questions, network and more.

“League of Women Coders is a grassroots collective that focusses on coding, hacking, and learning together. We’re like a book club for superhero women coders. You’ll find us championing free software, debating the best uses for ternary operators, defending against trolls, sharing what we know, and supporting each other in every way we can.

We meet at least once a month to hack on projects, give casual 5-minute lightning talks, ask all of our technical questions, and toss around ideas together. It’s a great way to make new friends, and to bounce ideas off each other to keep improving our coding skills. We usually have tasty treats of the baked variety and pizza for all of your om-ing and nom-ing needs. We also love to bring in interesting lady speakers, so let us know if you have anything you’d like to hear or talk about!”

 

Hackerrank Gaming Array Challenge

Hi! I attended a meetup a couple days ago revolving around problem solving practice for coders. The questions were pulled from Hackerrank, which is great tool for algorithm-based problems, but unfortunately, most of the answers online are in Python or Java… So today, thought I’d go through one of the problems and show how I approached and solved it using Javascript in hopes that this’ll come in handy for someone else!

Question (level medium on Hackerrank)

Andy loves playing games. He wants to play a game with his little brother, Bob, using an array, A, of n distinct integers. The rules are as follows:

  • Bob always plays first and the two players move in alternating turns.
  • In a single move, a player chooses the maximum element currently present in the array and removes it as well as all the other elements to its right. For example, if A = [2, 3, 5, 4, 1], then it becomes A = [2, 3] after the first move because we remove the maximum element (i.e. 5,) and all elements to its right (i.e. 4,  and 1).
  • The modifications made to the array during each turn are permanent, so the next player continues the game with the remaining array. The first player who is unable to make a move loses the game.

Andy and Bob play g games. Given the initial array for each game, can you find and print the name of the winner on a new line? If Andy wins, print ANDY; if Bob wins, print BOB.

Solution

Screen Shot 2018-01-26 at 2.29.15 PM.png

Since the instructions say Bob always goes first, we set him equal to a variable to indicate he’s the starting player. We also create a shallow copy of the array using slice — it’s good practice to leave the originals untouched in case we ever need to refer it in the future.

Then, we loop through the copy of the array, and as long as there are values in the array, we do a check to see who the current player is, then perform the following: switch the player’s name to indicate a change in turn, find the maximum value in the array, and as per the instructions, get rid of the maximum value and any values to the right of the max value.

Once there are no longer any values in the array, we exit out of the loop and make sure we return the winning player’s name in all capital letters.

 

Javascript: What’s the difference between let, var, and const?

If you’re here, you likely have a loose idea of which variables–out of let, var, or const–to use and when, but are wondering about the specific differences among the three. Here’s a brief rundown on their differences and limitations…

Var has function scope. When a value is assigned to var, it can be recalled throughout the entire function. Var, however, has different behavior when it’s inside a function versus inside a block.

 

Screen Shot 2018-01-19 at 10.09.47 AM.png

Let, on the other hand, enables you to assign a value with block scope, like within if-statements and loops. We’ll illustrate with an example:

Screen Shot 2018-01-19 at 10.11.45 AM.png

As its name denotes, const (short for constant) is used when the value you’re assigning shouldn’t be reassigned (should remain unchanged). Like let, it has block scope. Attempting to reassign a value to const will throw an error. An important distinguishment, though, is that const values are not immutable… That means objects can’t be overwritten, but object values can be changed.

Screen Shot 2018-01-19 at 9.47.15 AM.pngBeing aware of the nuances is advantageous, as using these variables accurately helps increase precision and code readability.

 

 

React CSS Best Practices

Some people have no qualms with incorporating CSS and HTML into Javascript components. Some others are vehemently against it. There’s no clear-cut, agreed-upon way to style your front-end using React, so there’s no singular best practice, but there are definitely a few approaches that have emerged.

In-Line CSS
This is best if you have only a few components or a smaller one-page app. React actually prefers in-line CSS. It isn’t ideal for larger chunks of formatting since can be difficult to manage and end up looking messy. If you need to change one thing, you’d have to look through your code to locate the particular attribute. It’s also limiting in the sense that it becomes tedious to make overarching changes to your application.

One possibility is to store separate styles using variables, then include them as a reference in tags, like below.

css1

Another way is to include the CSS directly in your tag – this is a more concise way and better if you only have one or two style properties to attribute to your components. For example, <p style=”color: pink”>.



CSS Stylesheets
This means you can have a separate file containing styling pertaining to each component of your application, so if you have a Shirt.js component, you’ll have an accompanying Shirt.css file. Then, you’d make sure to import your css file in your component file.

 



CSS Modules
A CSS Module is a CSS file in which all class names and animation names are scoped locally by default.” What makes a CSS module a “module” and not just a “file” is using a CSS compiler.

CSS compilers intend to improve upon the default CSS syntax, allow you to write your stylesheets in a syntax more powerful, or more easily readable. CSS Modules compile to a low-level interchange format called ICSS or Interoperable CSS, but are written like normal CSS files.” CSS Modules Github

If you’re using Webpack, you already have access to a compiler. All you have to do is create a file that corresponds with your component and contains all the styles relevant to that component. When naming, make sure names are simple, descriptive, and useful for only the elements in that component.

css2

(Credit: http://andrewhfarmer.com/what-are-css-modules/)

No more global variables. It can sometimes be tough to figure out where a particular p tag is getting its styling from, especially when styling happens in multiple places and you aren’t sure which CSS tag is of highest rank. That’s where CSS modules come into play. You can have super simple class names, but build tools in CSS modules automatically add uniqueness to the original class name and export it to a Javascript object literal and apply it to React components.

When a compiler runs your CSS and gives your class name a modified unique global variable, it also generates a Javascript object that associates your original class name with the name it generated for you. When you import styles from ‘./Cat.css’ in the example below, “styles” is just a Javascript object.

 

Your Brain + Coding

I’ve always been a huge fan of psychology and the brain — trying to understand how and why people are wired they way they are, how two beings who come from the same womb can turn out so drastically different from one another. I once took a course on the psychology of dreams, during which my mind was repeatedly blown by my professor’s accurate dissection and interpretation of my peers’ dreams. But I digress.

I started digging around for anything that straddled the two worlds and fell into a rabbit hole reading papers written by researcher at University of Passau (Germany) Janet Siegmund, and emerged on the other side after several “ah-ha” moments. Siegmund works in the field of empirical software engineering, program comprehension, and fMRI.

The Study: 17 people (15 male, one female) participated in the study. They all read a short 20-line snippet of code in Java and attempted to comprehend what they’d seen; no live-coding was performed.

Programming: Math, Science, or Language?

It’s like learning a new language. You’ll do better if you’re good at math. It’s likely you’ve heard those things a time or two before on your road to coding. So which is it really? Programming is undoubtedly making its way into school curriculums, but given its relative newness as a subject, its niche has yet to be determined. As of late 2016, 20 states have passed legislation for students to receive credit for computer science classes to fulfill either math, science, or foreign language credits. While most consider computer science a part of former two groups, Texas allows students to receive credits towards the latter group. (Kentucky and New Mexico had considered similar circumstances, but didn’t end up following through.)

Screen Shot 2017-09-25 at 10.03.40 PM.png

Programming requires sound logic and problem-solving skills, which align with skills that are required in math. However, interestingly enough, Siegmund’s research from 2014, in which she and a team of researchers (a psychologist, a neurobiologist, a linguist, as well as computer scientists and software engineers) peered into brains of programmers (using fMRIs), shows that the parts of the brain that do light up have a strong relationship with language-processing regions in the brain.

 

Screen Shot 2017-09-28 at 11.50.19 AM.png

Screen Shot 2017-09-28 at 11.50.28 AM.png



Learning to Code

One of the questions that emerged as a result of the study: how do we create excellent programmers? We’ve beared witness to coders who seem–for lack of another descriptor–gifted at the art of coding. If coding bears resemblance to language, then wouldn’t it make sense to have coding languages that write most like natural languages? SQL and Ruby come close.

According to Siegmund’s research, the fact that the brain uses portions specific to language processing suggests those great at and enjoy learning new languages may find it easier to learn programming languages, too. On the other hand, it’s still a mystery how excellent programmers, considered those who are 10 times more productive than their peers, got, well… So excellent… After having had comparable years of experience and teaching. What is known is that experts typically have much lower brain activation than newbies — for example, pro-golfers and musicians versus their novice counterparts. Siegmund suggests that these excellent programmers likely approach problems differently, and this very fact may help researchers abstract insights into how best to teach future generations of developers.

Siegmund’s study tested how well the participants’ understood the program. Results would likely be different if participants were challenged with implementing source code.

Fun Facts:

  • Researchers Sharif and Maletic used eye tracking to investigate the effect of under_score vs. camelCase style on recognition time. They found that identifiers in under_score style are recognized faster than identifiers in camelCase.
  • Did you know that the Chinese, along with other Asian groups, program in English? This obviously makes the learning curve for non-English speakers much higher, as they’re tasked with both learning English and a programming language simultaneously.

Link to full publication: http://www.infosun.fim.uni-passau.de/cl/publications/docs/SKA+14.pdf

What’s actually created with Rails Generators?

A few days after shifting gears from tedious form-writing in the world of Sinatra to learning about Rails, it has become quite apparent that the “magic” of Rails is there — it’s just a matter of figuring how best to wield the wand and understanding the details of what the platform offers.

One obvious time-saving tool Rails has gifted us: generators to create models, views, and controllers for CRUD actions. Though it seemed like a no-brainer to use migration generators, it also seemed like the other generators and scaffolding received much flack for providing “too much” unnecessary code and files, but I was curious if “too much” could be a good thing in certain scenarios and more importantly, if there exists a general set of guidelines for when to use each.

confused meme.jpg


A few basic things before we begin, including the general syntax for Rails generators…

rails generate [type of generator] NAME
OR
rails g [type of generator] NAME


Model Generator

Command: rails g model Shoes name brand shoe_size:integer

Creates:

  • A model in models

Screen Shot 2017-09-07 at 8.52.22 AM.png

  • A migration file with timestamp in db/migrate

Screen Shot 2017-09-07 at 8.51.01 AM.png



Resource Generator

Command: rails g resource Shoes name brand shoe_size:integer

Creates:

  • A model in models
  • A migration file with timestamp in db/migrate
  • A shoes_controller.rb file in controllers

Screen Shot 2017-09-07 at 9.03.11 AM.png

Screen Shot 2017-09-07 at 9.03.49 AM.png

  • Resources routes in routes.rb, typically found in the config directory

Screen Shot 2017-09-07 at 8.55.26 AM.png



Scaffolding

Command: rails g scaffold Shoes brand shoe_size:integer

Creates:

  • A model in models
  • A migration file with timestamp in db/migrate
  • A shoes_controller.rb file in controllers
  • Resources routes in routes.rb, typically found in the config directory
  • Seven view files for your RESTful routes (index, create, new, edit, show, update, destroy) with HTML and erb files — plus a json builder file for index and show pages

Screen Shot 2017-09-07 at 9.25.01 AM.png

While it’s advised that beginners build their own MVCs to familiarize themselves with creating each of these files entails, it can also be beneficial to play around with scaffolding to get an idea of what’s available.


I started digging into the list of other generators, too.

Task Generator 

Command: rails g task clothing shirt pants

Creation: lib/tasks/clothing.rake

Inside the file:

Screen Shot 2017-09-07 at 8.46.22 AM.png



Assets Generator 

Command: rails g assets jacket

Creates these empty templates:

  • app/assets
  • javascripts/jacket.coffee
  • stylesheets/jacket.scss


Scaffold Controller Generator 

Command: rails g scaffold_controller umbrella

Creates:

  • Front-end templates
  • Scaffolded controllers
  • No models!

Mailer Generator 

Command: rails g mailer Example

Creates:

  • A mailer
  • Blank mailer test


Migration Generator 

Command: rails g migration CreateClothes

Creates a timestamped migration file. If you need to add an extra column, you can do so through this command as well.

Command: rails g migration add_size_to_clothes size


I saved the best for last…. The undo button.

rails destroy
OR
rails d 

This will delete all the files that were previously created using the generator.

  • rails d model Shoes
  • rails d controller Shoes
  • rails d scaffold Shoes

yay meme.jpg

 

 

 

Basics of the not so basic Ruby regex

Have you ever noticed how all groups have their own jargon?

Two–almost three!–weeks into learning Ruby at Flatiron School,  I’m learning that developer jargon is a beast of its own. I find it funny that in addition to learning a programming language, I’m amassing new vocab with the intention of using said vocab to reference the language.

There’s OO, PORO, IRB, BASH. And that’s just the beginning.

While sifting through the pre-work and world web/wealth of Ruby forums, blogs, I saw one new thing after another, but one thing especially caught my eye. Regexp. Mainly because it looked something like this:

email =~ /^(([A-Za-z0-9]*\.+*_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\+)|([A-Za-z0-9]+\+))*[A-Za-z0-9]+@{1}((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,4}$/i)

https://giphy.com/embed/PkVHsFmmLeBfa

via GIPHY

People actually communicate with the symbols associated with the numbers on our keyboard? Huh? It stirred up curiosity then and prompted a self pinky swear to closer examine the subject at a later time. Here I am, a few weeks later, making good on my promise.

Here’s a quick tutorial of a basic selection of Ruby regex:

Definition
So what is regular expression, you might ask. According to Ruby docs, a “regexp holds a regular expression, used to match a pattern against strings.” On either side, the string is delimited with forward slashes:

/chocolate/


Match Operator
This is a simple one that checks if the pattern included between the slashes matches any portion of the accompanying string.
Examples:
“I love chocolate” =~ /ate/ ? “yes” : “no”
#=> yes

“I love chocolate” =~ /pizza/ ? “yes” : “no”
#=> no 

In the first example, the pattern “ate” is contained in the string. In the second, pizza isn’t.


regex cartoon 2
Photo credit: xkcd.com


Metacharacters

( , ) , [ , ] , { , } , . , ? , + , *

The above characters each have a specific meaning when they show up in a pattern. Backslashes are used to escape them.


 

Anchors

We can also use these anchors to match to a specific position:

  • \A – matches beginning of string
  • \z – matches end of string
  • \Z – end of string. If string ends with a newline, it matches just before newline.
  • \G – matches point where last match finishes
  • ^ – matches beginning of string
  • \b – word boundary
  • $ – end of line or string

So…

  • /^hey/ means match “hey” at the beginning of a line, while
  • /you$/ means match “you” at the end of a line

https://giphy.com/embed/uL0pJDdA6fQ08

via GIPHY

Modifiers

  • \d – digit [0-9]
  • \D – non-digit
  • i – ignore capitalization and case
  • /\w/ – a word character (can be either lowercase or upper case)
  • /\W/ – a non-word character
  • /\h / – a hexdigit character (0-9a-fA-F)
  • /\h / – a non-hexdigit character (anything other than those listed the above)


Splitting strings using regexp
Here’s how we split usually:

“margherita,pizza”.split(“, “)
#=> [“margherita”, “pizza”]

We can also use regular expression here. The pipe indicates that both patterns should be searched for at the same time.

margherita,pizza!yum”.split(/!|-/)
#=> [“margherita”, “pizza!”, “yum”]

Above, the | operator means “or,” which means we could also do this…

/th(i|a)nk/ 

…in order to match “think” or “thank.”


Brackets

We can use square brackets to search for the range included in between the brackets, surrounded by black slashes.

“ice cream donuts” =~ /[1-9]/ ? “yes” : “no”
#=> no 

“ice cream donuts” =~ /[a-z]/ ? “yes” : “no”
#=> yes 

For a more limited selection, [abc] matches any of the included character of “a”, “b”, or “c”.

holey creamPhoto credit: Holey Cream

(Yes, ice cream donuts are actually a thing.)


Gsub

Gsub is string substitution that typically uses regex. It allows you to find and replaces all string instances with the second argument.

string = “HI, ARE YOU HUNGRY? 

words.gsub!(/\w{3}/) {|word| “[” + word.downcase() _ + “]” }

words = HI, are you HUNGRY?

This means replace all three-character words with downcased versions of themselves.


Can you tell I was hungry when writing this?

monkey emoji

Design a site like this with WordPress.com
Get started