Browse Source

Re-formatted some blog posts using new formatting script.

pull/77/head
jrtechs 5 years ago
parent
commit
c6c704e992
6 changed files with 522 additions and 361 deletions
  1. +60
    -36
      blogContent/posts/hardware/2018-rochester-maker-faire.md
  2. +103
    -64
      blogContent/posts/java/gremlin-in-10-minutes.md
  3. +35
    -32
      blogContent/posts/java/top-three-recommended-java-ides.md
  4. +111
    -71
      blogContent/posts/other/college-cookbook.md
  5. +113
    -82
      blogContent/posts/programming/cs-theory-exam-2-review.md
  6. +100
    -76
      blogContent/posts/programming/everything-fibonacci.md

+ 60
- 36
blogContent/posts/hardware/2018-rochester-maker-faire.md View File

@ -1,78 +1,102 @@
![Rochester Maker Faire RITlug table.](media/makerFaire/20181117_091159.jpg)
# Introduction
A few weeks ago I presented my [musical floppy drives](https://jrtechs.net/projects/musical-floppy-drive-build-log)
at the [Rochester Maker Faire](https://rochester.makerfaire.com/) with [RITlug](https://ritlug.com/).
Wow, that sentence had a ton of links-- you should check them out. This post is a
quick recap of my experience at the Maker Faire and a project update for my musical floppy drive project. For those of you who
don't know, [Maker Faires](https://makerfaire.com/) are community gatherings where people "celebrate arts, crafts,
engineering, science projects and the Do-It-Yourself (DIY) mindset".
I would like to give a huge thanks to [Christian](https://ctmartin.me/)
for providing me with some of these pictures and [RITlug](https://ritlug.com/)
for giving me the opportunity to present at the Maker Faire.
A few weeks ago I presented my [musical floppy
drives](https://jrtechs.net/projects/musical-floppy-drive-build-log)
at the [Rochester Maker Faire](https://rochester.makerfaire.com/) with
[RITlug](https://ritlug.com/). Wow, that sentence had a ton of
links-- you should check them out. This post is a quick recap of my
experience at the Maker Faire and a project update for my musical
floppy drive project. For those of you who don't know, [Maker
Faires](https://makerfaire.com/) are community gatherings where people
"celebrate arts, crafts, engineering, science projects and the
Do-It-Yourself (DIY) mindset".
I would like to give a huge thanks to
[Christian](https://ctmartin.me/) for providing me with some of these
pictures and [RITlug](https://ritlug.com/) for giving me the
opportunity to present at the Maker Faire.
# Project Background
Musical floppy drives are floppy drives wired to an Arduino to play music. I initially started with two floppy drives;
however, that grew to 8 drives very fast.
Musical floppy drives are floppy drives wired to an Arduino to play
music. I initially started with two floppy drives; however, that grew
to 8 drives very fast.
<youtube src="Y5msiFa54Ug" />
I currently have 10 floppy drives stacked together in a tower like structure to make it easier to take to places
like the Maker Faire and [Imagine RIT](https://www.rit.edu/imagine/).
I currently have 10 floppy drives stacked together in a tower like
structure to make it easier to take to places like the Maker Faire and
[Imagine RIT](https://www.rit.edu/imagine/).
![Rochester Maker Faire RITlug table.](media/makerFaire/20181117_092417.jpg)
# Future Project Upgrades
Although the 10 floppy drives are quite loud in a small room, people typically found it difficult to hear at the
Maker Faire. This was largely due to the noisiness of the hundreds of people at the convention center. To fix this
in the future I want to bring a small amplifier for the floppy drives.
Although the 10 floppy drives are quite loud in a small room, people
typically found it difficult to hear at the Maker Faire. This was
largely due to the noisiness of the hundreds of people at the
convention center. To fix this in the future I want to bring a small
amplifier for the floppy drives.
The second improvement which I plan on making is creating some form of web application where people can
request music for the floppy drives to play. The potential down side of this is that it is often difficult connecting
to the internet at conventions.
The second improvement which I plan on making is creating some form of
web application where people can request music for the floppy drives
to play. The potential down side of this is that it is often difficult
connecting to the internet at conventions.
I have a ton of old IDE hard drives that I plan on incorporating into my musical orchestra. The tricky part of that
upgrade would be to somehow incorporate those into my current floppy drive structure so that it is easy to take places.
My current plan is to have the hard drives completely separate from the floppy drives and run it on its own Arduino board.
I have a ton of old IDE hard drives that I plan on incorporating into
my musical orchestra. The tricky part of that upgrade would be to
somehow incorporate those into my current floppy drive structure so
that it is easy to take places. My current plan is to have the hard
drives completely separate from the floppy drives and run it on its
own Arduino board.
# Cool Projects at the Maker Faire
Although there were a ton of really cool projects at the Maker Faire, I did not have the time explore everything
and take a lot of pictures. However, I want to share some of the really cool projects that I saw at the Maker Faire.
Although there were a ton of really cool projects at the Maker Faire,
I did not have the time explore everything and take a lot of
pictures. However, I want to share some of the really cool projects
that I saw at the Maker Faire.
## HatChan
![HatChan](media/makerFaire/20181117_095844.jpg)
This is a project that one person is calling "HatChan". This is a hat equipped with a ton of LED lights, and
a fully functioning wireless access point. When you connect to his access point, the captcha portal takes you
to a 4chan esk site where you can upload pictures -- mostly memes.
This is a project that one person is calling "HatChan". This is a hat
equipped with a ton of LED lights, and a fully functioning wireless
access point. When you connect to his access point, the captcha portal
takes you to a 4chan esk site where you can upload pictures -- mostly
memes.
## 8-bit Computer
![Rochester Maker Faire](media/makerFaire/20181117_120948.jpg)
This one person brought a home made 8-bit computer to the Maker Faire. What I find the most impressive
about this project was that the person who made it was only a sophomore in high school.
This one person brought a home made 8-bit computer to the Maker Faire.
What I find the most impressive about this project was that the person
who made it was only a sophomore in high school.
## Foss@Magic
![Rochester Maker Faire](media/makerFaire/MVIMG_20181117_151211.jpg)
*Photo provided by [Christian](https://ctmartin.me/)*
FOSS@Magic is a organization at RIT which aims to promote
free and open source software-- i'm also a part of this group. This year the FOSS group demoed their colorful MAGIC letters. On
a tablet beneath the letters, there is a web site open where you can select the color of each individual
RGB letter.
FOSS@Magic is a organization at RIT which aims to promote free and
open source software-- i'm also a part of this group. This year the
FOSS group demoed their colorful MAGIC letters. On a tablet beneath
the letters, there is a web site open where you can select the color
of each individual RGB letter.
## RITlug
![Rochester Maker Faire](media/makerFaire/MVIMG_20181117_151247.jpg)
*Photo provided by [Christian](https://ctmartin.me/)*
The RIT Linux Users Group (RITlug) is a student-led organization aimed to promote and teach students about Linux and open source.
This year we presented my Floppy Drive project, a Raspberry Pi [Lakka](https://www.raspberrypi.org/magpi/easy-retro-gaming-lakka/) gaming set up, a
[Magic Mirror](https://github.com/MichMich/MagicMirror), and [Tiger OS](https://ritlug.com/tigeros).
The RIT Linux Users Group (RITlug) is a student-led organization aimed
to promote and teach students about Linux and open source. This year
we presented my Floppy Drive project, a Raspberry Pi
[Lakka](https://www.raspberrypi.org/magpi/easy-retro-gaming-lakka/)
gaming set up, a [Magic
Mirror](https://github.com/MichMich/MagicMirror), and [Tiger
OS](https://ritlug.com/tigeros).

+ 103
- 64
blogContent/posts/java/gremlin-in-10-minutes.md View File

@ -1,44 +1,57 @@
# What is Gremlin?
Gremlin is a graph traversal language: think of Gremlin as the SQL for graph databases. Gremlin is not
a graph database server, it is a language; but, there is a Gremlin Server and a Gremlin Console available for
interacting with graph databases. It is possible to use Gremlin on large database platforms
like [Titan](https://www.digitalocean.com/community/tutorials/how-to-set-up-the-titan-graph-database-with-cassandra-and-elasticsearch-on-ubuntu-16-04)
and [HBase](https://docs.janusgraph.org/latest/hbase.html).
Gremlin is a graph traversal language: think of Gremlin as the SQL for
graph databases. Gremlin is not a graph database server, it is a
language; but, there is a Gremlin Server and a Gremlin Console
available for interacting with graph databases. It is possible to use
Gremlin on large database platforms like
[Titan](https://www.digitalocean.com/community/tutorials/how-to-set-up-the-titan-graph-database-with-cassandra-and-elasticsearch-on-ubuntu-16-04)
and [HBase](https://docs.janusgraph.org/latest/hbase.html).
# Graph Data Base Basics
A graph database is based on graph theory. A graph is composed of nodes, edges, and properties. A key
object/component in a graph database is stored as a node. Nodes are connected via edges representing
relationships. For example, you may represent people as nodes and have edges representing friendships.
You can assign properties to both nodes and edges. A person (node) may have the properties of age and name,
where a friendship (edge) may have a start date property.
A graph database is based on graph theory. A graph is composed of
nodes, edges, and properties. A key object/component in a graph
database is stored as a node. Nodes are connected via edges
representing relationships. For example, you may represent people as
nodes and have edges representing friendships. You can assign
properties to both nodes and edges. A person (node) may have the
properties of age and name, where a friendship (edge) may have a
start date property.
## Why Graph Databases?
Graph databases are great for modeling data where the value lies in the shape of the graph. Graph databases
also allow to to model more complex relationships which would be difficult to model in a normal table-based
database.
Graph databases are great for modeling data where the value lies in
the shape of the graph. Graph databases also allow to to model more
complex relationships which would be difficult to model in a normal
table-based database.
## Gremlin Installation
Download and extract the following:
Download and extract the following:
- [Gremlin Console](https://www.apache.org/dyn/closer.lua/tinkerpop/3.3.3/apache-tinkerpop-gremlin-console-3.3.3-bin.zip)
- [Gremlin Server](https://www.apache.org/dyn/closer.lua/tinkerpop/3.3.3/apache-tinkerpop-gremlin-server-3.3.3-bin.zip)
Start the Gremlin server by running it with the start script in the bin folder. As a prerequisite for running gremlin, you
must have Java installed on your computer.
```
Start the Gremlin server by running it with the start script in the
bin folder. As a prerequisite for running gremlin, you must have Java
installed on your computer.
```bash
./gremlin-server.sh
```
Start the Gremlin console by running the gremlin.sh or gremlin.bat script in the bin folder.
```
Start the Gremlin console by running the gremlin.sh or gremlin.bat
script in the bin folder.
```bash
./gremlin.sh
```
Now you need to instantiate a new graph on the server to use. To to that, execute the following commands in
the Gremlin console.
Now you need to instantiate a new graph on the server to use. To to
that, execute the following commands in the Gremlin console.
```java
#Creates a empty graph
gremlin> graph = EmptyGraph.instance()
@ -56,26 +69,32 @@ gremlin> g = graph.traversal().withRemote(DriverRemoteConnection.using(cluster,
# Gremlin Syntax
Now that you have your gremlin server and console set up, you are ready to start executing Gremlin queries.
Now that you have your gremlin server and console set up, you are
ready to start executing Gremlin queries.
## Adding a Vertex
In Gremlin nodes are referred to as "Vertexes". To add a node/vertex to the graph, you simply use the
command addV() on your graph traversal source. For consistency, most people
use "g" as their default graph traversal source. To append properties to your your vertex, you add a series of
".property('property_name', 'property_value')" strings to the add vertex query.
In Gremlin nodes are referred to as "Vertexes". To add a node/vertex
to the graph, you simply use the command addV() on your graph
traversal source. For consistency, most people use "g" as their
default graph traversal source. To append properties to your your
vertex, you add a series of ".property('property_name',
'property_value')" strings to the add vertex query.
EX:
EX:
```java
g.addV('student').property('name', 'Jeffery').property('GPA', 4.0);
```
## Updating a Property
Unlike SQL, you are not limited to a specific schema in a graph database. If you want to add or change
a property on a vertex or edge, you simply use the property command again.
The "g.V(1)" in the following example refers to a specific vertex with the primary id of 1-- the graph database auto assigns these ids.
You can replace "g.V(1)" with a command to select a specific vertex or edge.
Unlike SQL, you are not limited to a specific schema in a graph
database. If you want to add or change a property on a vertex or
edge, you simply use the property command again. The "g.V(1)" in the
following example refers to a specific vertex with the primary id of
1-- the graph database auto assigns these ids. You can replace
"g.V(1)" with a command to select a specific vertex or edge.
```java
g.V(1).property('name', 'Jeffery R');
@ -83,29 +102,38 @@ g.V(1).property('name', 'Jeffery R');
## Selection
Selecting nodes and edges is the most complicated part of Gremlin. The concept is not particularly hard, but, there
are dozens of ways to do graph traversals and selections. I will cover the most common aways to traverse a graph.
Selecting nodes and edges is the most complicated part of Gremlin. The
concept is not particularly hard, but, there are dozens of ways to do
graph traversals and selections. I will cover the most common aways to
traverse a graph.
This example will select all vertexes which have the label "student".
The ".valueMap()" command appended to the end of the query makes
Gremlin return a map of all the objects it returns with their
properties.
This example will select all vertexes which have the label "student". The ".valueMap()" command appended to the end of the query
makes Gremlin return a map of all the objects it returns with their properties.
```java
g.V().hasLabel('student').valueMap();
```
In this following example, instead of returning a ValueMap of values, we are just returning the names of the students
in the graph.
In this following example, instead of returning a ValueMap of values,
we are just returning the names of the students in the graph.
```java
g.V().hasLabel('student').values('name');
```
This example will return the GPA of the student with the name "Jeffery R".
This example will return the GPA of the student with the name "Jeffery
R".
```java
g.V().hasLabel('student').has('name', 'Jeffery R').values('gpa');
```
This command will return all the students in order of their GPA.
This command will return all the students in order of their GPA.
```java
g.V().hasLabel('student').order().by('gpa', decr).value('name')
```
@ -113,10 +141,12 @@ g.V().hasLabel('student').order().by('gpa', decr).value('name')
## Adding Edges
The easiest way (my opinion) to add edges in Gremlin is by
using aliasing. In this example we select two nodes and assign them a name: in this case it is "a", and "b".
After we have selected two edges, we can add an edge to them using the "addE()" command. The syntax of this is
nice because we know that "a" is friends with "b"-- it is easy to tell the direction of the edge.
The easiest way (my opinion) to add edges in Gremlin is by using
aliasing. In this example we select two nodes and assign them a name:
in this case it is "a", and "b". After we have selected two edges, we
can add an edge to them using the "addE()" command. The syntax of this
is nice because we know that "a" is friends with "b"-- it is easy to
tell the direction of the edge.
```java
g.V(0).as('a').V(1).as('b').addE('knows')
@ -126,12 +156,15 @@ g.V(0).as('a').V(1).as('b').addE('knows')
# Using Gremlin with Java
Now that you know the basic syntax of Gremlin, you are ready to use it somewhere other than the Gremlin console. If you
are trying to use Gremlin with Java, there is a great Maven dependency for TinkerPop and Gremlin. If you want to quickly
connect to your Gremlin server with Java, make sure your server is set up exactly as it was before this tutorial started discussing
Gremlin syntax.
Now that you know the basic syntax of Gremlin, you are ready to use it
somewhere other than the Gremlin console. If you are trying to use
Gremlin with Java, there is a great Maven dependency for TinkerPop and
Gremlin. If you want to quickly connect to your Gremlin server with
Java, make sure your server is set up exactly as it was before this
tutorial started discussing Gremlin syntax.
## Maven dependency for Java:
```html
<!-- https://mvnrepository.com/artifact/com.tinkerpop/gremlin-core -->
<dependency>
@ -154,8 +187,10 @@ Gremlin syntax.
</dependency>
```
It is helpful to wrap everything relating to the graph database connection into a single Java class. This is roughly
the code that I usually use to interact with a Gremlin Server-- anybody is free to use it.
It is helpful to wrap everything relating to the graph database
connection into a single Java class. This is roughly the code that I
usually use to interact with a Gremlin Server-- anybody is free to use
it.
```java
public class GraphConnection
@ -188,6 +223,8 @@ public class GraphConnection
```
## Basic GraphConnection.java Usage:
```java
RemoteConnection con = new RemoteConnection()
String query = "g.V().hasLabel('player')" +
@ -202,6 +239,8 @@ this.con.queryGraph(query);
```
## Overly complex usage with a lambda statement
```java
/**
* Fetches the list of a player's friends.
@ -212,11 +251,9 @@ this.con.queryGraph(query);
private List<Player> getFriendsFromGraph(String id)
{
List<Player> friends = new ArrayList<>();
String query = "g.V().hasLabel('player')" +
".has('id', '" + id + "')" +
".both().valueMap()";
this.con.queryGraph(query).stream().forEach(r ->
friends.add(new Player(
((ArrayList) (((HashMap<String, Object>) (r.getObject()))
@ -228,21 +265,22 @@ private List getFriendsFromGraph(String id)
}
```
The most important thing to do while playing around with Gremlin in Java is to keep an eye on the
return type. From experience, I can say that it is often easier to return the vertex from your
query rather than returning the valueMap.
The most important thing to do while playing around with Gremlin in
Java is to keep an eye on the return type. From experience, I can say
that it is often easier to return the vertex from your query rather
than returning the valueMap.
Without returning the valueMap in the query, you can directly access
the vertex in the result rather than doing some voodoo witchcraft and
casting between ArrayLists and HashMaps.
Without returning the valueMap in the query, you can directly access the vertex
in the result rather than doing some voodoo witchcraft and casting between ArrayLists and HashMaps.
The previous example could be re-written as this:
The previous example could be re-written as this:
```java
List<Player> friends = new ArrayList<>();
String query = "g.V().hasLabel('player')" +
".has('id', '" + id + "')" +
".both()";
for(Result r: this.con.queryGraph(query))
{
friends.add(new Player(r.getVertex("name").value().toString),
@ -250,14 +288,15 @@ for(Result r: this.con.queryGraph(query))
}
```
You now know enough about Gremlin to be dangerous with it. Yay! If you want to do more than basic things with Gremlin,
I highly suggest that you look at the tutorial [SQL 2 Gremlin](http://sql2gremlin.com/).
If you plan on deploying this to production, it is recommended that you use HBase for a persistent back end storage
server.
You now know enough about Gremlin to be dangerous with it. Yay! If you
want to do more than basic things with Gremlin, I highly suggest that
you look at the tutorial [SQL 2 Gremlin](http://sql2gremlin.com/). If
you plan on deploying this to production, it is recommended that you
use HBase for a persistent back end storage server.
# Resources
- [SQL 2 Gremlin](http://sql2gremlin.com/)
- [Practical Gremlin](http://kelvinlawrence.net/book/Gremlin-Graph-Guide.html)
- [Apache TinkerPop](http://tinkerpop.apache.org/)
- [Steam Friends Graph (Personal Gremlin Project)](https://github.com/jrtechs/SteamFriendsGraph)
- [Steam Friends Graph (Personal Gremlin Project)](https://github.com/jrtechs/SteamFriendsGraph)

+ 35
- 32
blogContent/posts/java/top-three-recommended-java-ides.md View File

@ -1,45 +1,48 @@
An IDE (Integrated Development Environment) is a single program that wraps
everything you need to program with. An IDE usually consists of a code editor,
debugger, and a compiler. A good IDE can make you more productive. Without a IDE
you would be stuck writing all of your apps in notepad and compiling via command
line – which is not bad for learning how to program. A good IDE has syntax
highlighting which makes the code easier to read and error highlighting which
makes finding that missing semi colon easier. Here is a list of three IDEs that
work well for me.
An IDE (Integrated Development Environment) is a single program that
wraps everything you need to program with. An IDE usually consists of
a code editor, debugger, and a compiler. A good IDE can make you more
productive. Without a IDE you would be stuck writing all of your apps
in notepad and compiling via command line – which is not bad for
learning how to program. A good IDE has syntax highlighting which
makes the code easier to read and error highlighting which makes
finding that missing semi colon easier. Here is a list of three IDEs
that work well for me.
# NetBeans
NetBeans is the most productive IDE for large java projects. NetBeans is great
at detecting errors in your code. You can also have multiple projects open in
the same window which is great for anyone who is constantly flipping between
projects – even if they are in different coding languages. This is a must have
program for everyone looking to develop Java. This program also supports PHP,
JavaScript and C/C++.
NetBeans is the most productive IDE for large java projects. NetBeans
is great at detecting errors in your code. You can also have multiple
projects open in the same window which is great for anyone who is
constantly flipping between projects – even if they are in different
coding languages. This is a must have program for everyone looking to
develop Java. This program also supports PHP, JavaScript and C/C++.
![NetBeans IDE](media/2a20326e77c3f67aa3753401ba4bc612.png)
# Eclipse
Eclipse is a very popular programming IDE; however, it is harder to use than
NetBeans. The largest benefit of Eclipse is that it has tons of templates for
you to use. Eclipse also has a better GUI creation tool than NetBeans has.
Eclipse is a very popular programming IDE; however, it is harder to
use than NetBeans. The largest benefit of Eclipse is that it has tons
of templates for you to use. Eclipse also has a better GUI creation
tool than NetBeans has.
![Eclipse](media/f5cb2682e219549cb07acd1d01c2ccb1.png)
# JCreator
I want to warn you that this is a old IDE. You hate yourself if you decide to
use this program. The only reason I am putting this on my list is because I
think it is great for teaching people how to program – it’s what my high school
used. Unlike Eclipse and NetBeans, it gives you very little help when writing
your code. There is no autocompletes or dropdowns when you are accessing members
of an object. This does not even give you red highlights when you have a syntax
error. What it instead shows you is the errors that you would receive in the
command line when you compile this project. This is great for AP Computer
Science students who have to memorize/learn what certain errors mean.
I want to warn you that this is a old IDE. You hate yourself if you
decide to use this program. The only reason I am putting this on my
list is because I think it is great for teaching people how to program
– it’s what my high school used. Unlike Eclipse and NetBeans, it gives
you very little help when writing your code. There is no autocompletes
or dropdowns when you are accessing members of an object. This does
not even give you red highlights when you have a syntax error. What it
instead shows you is the errors that you would receive in the command
line when you compile this project. This is great for AP Computer
Science students who have to memorize/learn what certain errors mean.
![JCreator](media/c1e712bdead908ebd72921ec2d1cbd5e.png)
@ -48,11 +51,11 @@ Science students who have to memorize/learn what certain errors mean.
\*Update 2018
I have converted to a full time Intellij user since writing this article in
2015. This program is simply fantastic in every aspect – expect ram usage. If
you have never heard of Intellij or any of the other JetBrains products I would
highly recommend you check them out. The main reason I switched was because
Intellij could scale nicely to 4k and NetBeans did not. The user experience
overall feels nice.
I have converted to a full time Intellij user since writing this
article in 2015. This program is simply fantastic in every aspect –
expect ram usage. If you have never heard of Intellij or any of the
other JetBrains products I would highly recommend you check them out.
The main reason I switched was because Intellij could scale nicely to
4k and NetBeans did not. The user experience overall feels nice.
![Intellij](media/2a96900bae1e8946a1df243d8318e69f.png)

+ 111
- 71
blogContent/posts/other/college-cookbook.md View File

@ -1,21 +1,24 @@
I occasionally cooked during High School, however, college was my first real experience cooking on
a daily basis. Since I have lived to tell the tail, I want to share some of the recipes that
I created/modified which got me through my first two years of college.
I occasionally cooked during High School, however, college was my
first real experience cooking on a daily basis. Since I have lived to
tell the tail, I want to share some of the recipes that I
created/modified which got me through my first two years of college.
# Level 1: Cooking in the Dorms
Being stuck in a dorm room you are limited to only being able to use the microwave.
Desperate times calls for depraved cooking solutions.
Being stuck in a dorm room you are limited to only being able to use
the microwave. Desperate times calls for depraved cooking solutions.
## Ramen Pizza
![Romen Pizza Final Result](media/cooking/lvl1/romenPizza.jpg)
This recipe surprised me as to how it turned out.
You start making this by microwaving ramen noodles for about a third of the instructed time in a bowl of water.
When you place the noodles in the bowl, make sure to not break them apart.
After cooking, take the romen noodles out of the bowl, dry, and place on a plate.
Next, you slather the ramen noodles with your desired pizza toppings and place in the microwave for around 2 minutes.
This recipe surprised me as to how it turned out. You start making
this by microwaving ramen noodles for about a third of the instructed
time in a bowl of water. When you place the noodles in the bowl, make
sure to not break them apart. After cooking, take the romen noodles
out of the bowl, dry, and place on a plate. Next, you slather the
ramen noodles with your desired pizza toppings and place in the
microwave for around 2 minutes.
### Ingredients
@ -28,19 +31,22 @@ Next, you slather the ramen noodles with your desired pizza toppings and place i
![Eggs in a Mug Result](media/cooking/lvl1/eggs.jpg)
Life hack: you can cook scrambled eggs in a microwave using a coffee mug.
The resulting eggs are abnormally fluffy and taste a little strange, but, it makes for a quick meal.
It just so happens that you can also cook hot dogs in the microwave.
Life hack: you can cook scrambled eggs in a microwave using a coffee
mug. The resulting eggs are abnormally fluffy and taste a little
strange, but, it makes for a quick meal. It just so happens that you
can also cook hot dogs in the microwave.
When I stumbled upon this recipe, I clung to it since it was fast, cheep,
and most of the dinning places on campus were closed by the time I got out of work.
To make this, you crack and mix two eggs in a coffee cup.
You then microwave the coffee mug, mixing the eggs every 30 seconds.
Half way through cooking the eggs, you add a diced hotdog and some shredded cheese.
Once your eggs have all cooked, you can add a healthy dosage of salsa.
Voila, you have an omelet which can compete with whatever they are serving at the dinning hall.
When I stumbled upon this recipe, I clung to it since it was fast,
cheep, and most of the dinning places on campus were closed by the
time I got out of work. To make this, you crack and mix two eggs in a
coffee cup. You then microwave the coffee mug, mixing the eggs every
30 seconds. Half way through cooking the eggs, you add a diced hotdog
and some shredded cheese. Once your eggs have all cooked, you can add
a healthy dosage of salsa. Voila, you have an omelet which can compete
with whatever they are serving at the dinning hall.
## Ingredients
- 1-2 Eggs
- 1 Hotdog
- Cheese
@ -48,19 +54,24 @@ Voila, you have an omelet which can compete with whatever they are serving at th
# Level 2: Cooking With no Time
Time is *very* scarce as a college student, I found the following recipes to be fast and easy.
These recipes are very forgiving in the sense that you can change the directions and ingredients and still end up with something resembling food.
Time is *very* scarce as a college student, I found the following
recipes to be fast and easy. These recipes are very forgiving in the
sense that you can change the directions and ingredients and still end
up with something resembling food.
## Chili
![Chili with rice and cheese](media/cooking/lvl2/chili.jpg)
It is *very* hard to make a bad chili.
All you essentially have to do is gather/prep all the ingredients and plop them in a crock pot and cook for 6-8 hours on low.
You don't have to cook this in a crock pop, however, it takes more time to prepare on the stove since you have to monitor it while it cooks for an hour on medium heat.
I usually saute the onions while I cook the ground beef so that it cooks in the grease of the beef.
The average prep time for this recipe is around 20-30 minutes.
However, if you made this vegetarian you can probably cut the prep time down to a mere 10 minutes.
It is *very* hard to make a bad chili. All you essentially have to do
is gather/prep all the ingredients and plop them in a crock pot and
cook for 6-8 hours on low. You don't have to cook this in a crock pop,
however, it takes more time to prepare on the stove since you have to
monitor it while it cooks for an hour on medium heat. I usually saute
the onions while I cook the ground beef so that it cooks in the grease
of the beef. The average prep time for this recipe is around 20-30
minutes. However, if you made this vegetarian you can probably cut
the prep time down to a mere 10 minutes.
### Ingredients
@ -86,12 +97,15 @@ However, if you made this vegetarian you can probably cut the prep time down to
![Poor mans Chicken Parmesan Serving Picture](media/cooking/lvl2/chickenParm.jpg)
I call this poor man's chicken parmesan only because it uses chicken patties, this actually tastes really good.
To prepare this you slather chicken patties with pasta sauce and cheese and then cook normally in the oven.
While the chicken patties bake, you can cook your normal pasta noodles and sauce.
You serve the pasta noodles with the sauce topped with the cheesy chicken pattie.
I call this poor man's chicken parmesan only because it uses chicken
patties, this actually tastes really good. To prepare this you slather
chicken patties with pasta sauce and cheese and then cook normally in
the oven. While the chicken patties bake, you can cook your normal
pasta noodles and sauce. You serve the pasta noodles with the sauce
topped with the cheesy chicken pattie.
### Ingredients
- Chicken Patties
- Pasta Sauce
- Pasta Noodles
@ -101,16 +115,21 @@ You serve the pasta noodles with the sauce topped with the cheesy chicken pattie
![Chicken Soup Served with Mozzarella Cheese](media/cooking/lvl2/chickenSoup.jpg)
This is an easy recipe which has *so* many combinations.
I usually make some form of chicken soup, the rest of the ingredients are entirely dependent on what I have in the kitchen.
You will have to play around with my recommenced ingredient list to find the perfect combination for you, however, I have not found a combination which did not work with me-- yet.
Similar to chili, you just put all the ingredients in a crock pot and let simmer on low for 6-8 hours.
I would recommend putting in spices like garlic and basil during the last hour of cooking to keep their flavors sharp.
You want to add the salt and pepper to the soup in the beginning.
This is an easy recipe which has *so* many combinations. I usually
make some form of chicken soup, the rest of the ingredients are
entirely dependent on what I have in the kitchen. You will have to
play around with my recommenced ingredient list to find the perfect
combination for you, however, I have not found a combination which did
not work with me-- yet. Similar to chili, you just put all the
ingredients in a crock pot and let simmer on low for 6-8 hours. I
would recommend putting in spices like garlic and basil during the
last hour of cooking to keep their flavors sharp. You want to add the
salt and pepper to the soup in the beginning.
![Chicken Soup with a red sauce](media/cooking/lvl2/redSoup.jpg)
### Ingredients
- Bag of Frozen Chicken Strips
- 3-4 Diced Potatoes
- Chicken Stock
@ -135,14 +154,17 @@ You want to add the salt and pepper to the soup in the beginning.
![Potato Casserole](media/cooking/lvl2/cheesePotatoes.jpg)
For this recipe you cut all the vegetables and place them in a large baking pan with the chicken strips.
If you want, you can also mix in some seasonings like salt, garlic, pepper, and basil.
You then then mix everything together with some canola or vegetable oil.
Cook this casserole in a 350 degrease oven for around 30 minutes.
Briefly take this out of the oven and top with cheese and ranch dressing and place back in oven for another 10-15 minutes.
If you are really cheap, you can make this with hot dogs rather than pre-cooked chicken strips.
For this recipe you cut all the vegetables and place them in a large
baking pan with the chicken strips. If you want, you can also mix in
some seasonings like salt, garlic, pepper, and basil. You then then
mix everything together with some canola or vegetable oil. Cook this
casserole in a 350 degrease oven for around 30 minutes. Briefly take
this out of the oven and top with cheese and ranch dressing and place
back in oven for another 10-15 minutes. If you are really cheap, you
can make this with hot dogs rather than pre-cooked chicken strips.
### Ingredients
- 4-6 Peeled and Cubed Potatoes
- 1-2 Diced Onions
- Bag of Chicken Strips
@ -156,20 +178,25 @@ If you are really cheap, you can make this with hot dogs rather than pre-cooked
# Level 3 Cooking
Once you master the art of sauteing onions and making soups, you are ready to advance to level three.
Nothing I will present is incredibly difficult, but, there is more room for mistakes and takes longer to prepare.
Once you master the art of sauteing onions and making soups, you are
ready to advance to level three. Nothing I will present is incredibly
difficult, but, there is more room for mistakes and takes longer to
prepare.
## Fried Rice
![Fried Rice Final Result](media/cooking/lvl3/friedRice.jpg)
The challenging part of this recipe is getting the correct timing.
To finish this dish in 40 minutes, you want to cook 2 cups of rice, brown ground beef with onions and cook 3 scrambled eggs all simultaneously.
You then combine all these ingredients in a large fry pan with vegetables and soy sauce.
If you want to prevent the dish from turning out sticky, you should use left over rice.
Or, cook the rice first and then let if cool in the fridge for a few hours.
The challenging part of this recipe is getting the correct timing. To
finish this dish in 40 minutes, you want to cook 2 cups of rice, brown
ground beef with onions and cook 3 scrambled eggs all simultaneously.
You then combine all these ingredients in a large fry pan with
vegetables and soy sauce. If you want to prevent the dish from turning
out sticky, you should use left over rice. Or, cook the rice first
and then let if cool in the fridge for a few hours.
### Ingredients
- 1-2 Cups of Rice
- 1/2 lbs of Ground Beef
- 1 Onion
@ -180,17 +207,22 @@ Or, cook the rice first and then let if cool in the fridge for a few hours.
![Chicken Right Out of Oven](media/cooking/lvl3/ovenChicken.jpg)
Cooking raw chicken is definitely not on the syllabus for most college students.
When cooking the chicken I would strongly recommend using a meat thermometer to make sure that the chicken reaches 165 degrease.
Either buy chicken breasts or cut a whole chicken-- use the left over chicken spine and wings for chicken stock.
On a baking pan lather the chicken in the marinara sauce that you just mixed (ingredients below) and sprinkle some salt and pepper on the chicken.
Let the chicken cook for around 30 minutes in a oven that is 400 degrease (until the chicken reaches 165).
After the chicken comes out of the oven, sear it on a ripping hot skillet with some more of the marinara sauce.
Cooking the chicken this way will keep the chicken juicy and the skin crispy.
Cooking raw chicken is definitely not on the syllabus for most college
students. When cooking the chicken I would strongly recommend using a
meat thermometer to make sure that the chicken reaches 165 degrease.
Either buy chicken breasts or cut a whole chicken-- use the left over
chicken spine and wings for chicken stock. On a baking pan lather the
chicken in the marinara sauce that you just mixed (ingredients below)
and sprinkle some salt and pepper on the chicken. Let the chicken cook
for around 30 minutes in a oven that is 400 degrease (until the
chicken reaches 165). After the chicken comes out of the oven, sear it
on a ripping hot skillet with some more of the marinara sauce. Cooking
the chicken this way will keep the chicken juicy and the skin crispy.
![Chicken Searing](media/cooking/lvl3/chickenSear.jpg)
### Marinara Sauce Ingredients
- 4 TBSP Oil
- 3 TBSP Honey
- Minced Garlic
@ -201,17 +233,22 @@ Cooking the chicken this way will keep the chicken juicy and the skin crispy.
![Ingredients for Stock](media/cooking/lvl3/stockIngredients.jpg)
If you happen to cook with a whole chicken and end up with some chicken bones, you are in the perfect position to make chicken stock.
Essentially all you need to do is put your chicken bones, onions, carrots, and basil in a crock pot cook for 8-12 hours on low.
Periodically you should skim off the fat that surfaces to the top.
At the end of the 12 hours you use a fine mesh skimmer to filter out all the chicken and vegetables.
If you want a darker flavor to the stock, roast the chicken parts and vegetables in the oven before adding them to the crock pot.
If you happen to cook with a whole chicken and end up with some
chicken bones, you are in the perfect position to make chicken stock.
Essentially all you need to do is put your chicken bones, onions,
carrots, and basil in a crock pot cook for 8-12 hours on low.
Periodically you should skim off the fat that surfaces to the top. At
the end of the 12 hours you use a fine mesh skimmer to filter out all
the chicken and vegetables. If you want a darker flavor to the stock,
roast the chicken parts and vegetables in the oven before adding them
to the crock pot.
![Cooking Chicken Stock](media/cooking/lvl3/cookingBroth.jpg)
![Stock Final Result](media/cooking/lvl3/ChickenBroth.jpg)
### Ingredients
- Chicken Bones
- 1-2 Quartered Onions
- 2-3 Carrots
@ -226,16 +263,19 @@ If you want a darker flavor to the stock, roast the chicken parts and vegetables
![Chicken and Rice Plate Picture](media/cooking/lvl3/chickenAndRice.jpg)
My version of chicken and rice may not be orthodox.
This recipe came into existence because I needed something to make which shared ingredients with the other dishes that I frequently make.
My version of chicken and rice may not be orthodox. This recipe came
into existence because I needed something to make which shared
ingredients with the other dishes that I frequently make.
Essentially, you make rice and put a thick red sauce with chicken, onions, peppers over it.
You prepare the rice like normal.
In a large sauce pan you saute onions and peppers.
Once the onions start to brown, you add diced tomatoes, corn, minced garlic, basil, brown sugar, frozen chicken strips and mustard.
Once the chicken has thawed, you are ready to serve this dish.
Essentially, you make rice and put a thick red sauce with chicken,
onions, peppers over it. You prepare the rice like normal. In a large
sauce pan you saute onions and peppers. Once the onions start to
brown, you add diced tomatoes, corn, minced garlic, basil, brown
sugar, frozen chicken strips and mustard. Once the chicken has thawed,
you are ready to serve this dish.
### Ingredients
- 2 Cups Rice
- Bag of Grilled Chicken Strips
- 1-2 Onions
@ -245,4 +285,4 @@ Once the chicken has thawed, you are ready to serve this dish.
- 1 Can Corn
- Minced Garlic
- Brown Sugar
- Basil
- Basil

+ 113
- 82
blogContent/posts/programming/cs-theory-exam-2-review.md View File

@ -1,19 +1,26 @@
This a very high level review post that I am making for myself and other people reviewing CS Theory.
If you want to lean more about content in this blog post I recommend cracking open a text book-- I know, gross.
This hastily thrown together post will cover how to solve typical problems relating to topics covered by my second CS Theory exam.
This a very high level review post that I am making for myself and
other people reviewing CS Theory. If you want to lean more about
content in this blog post I recommend cracking open a text book-- I
know, gross. This hastily thrown together post will cover how to solve
typical problems relating to topics covered by my second CS Theory
exam.
# Myhill-Nerode Theorem
## Definition
L is regular if and only if it has a finite index. The index is the maximum number of elements that are pairwise distinguishable.
Two strings are said to be pairwise distinguishable if you can append something to both of the strings and it makes one string
accepted by the language and the other string rejected.
The size of an index set X equals the number of equivalence classes it has and the minimum number of states required to represent it
using a DFA. Each element in the language is accepted by only one equivalence class.
L is regular if and only if it has a finite index. The index is the
maximum number of elements that are pairwise distinguishable. Two
strings are said to be pairwise distinguishable if you can append
something to both of the strings and it makes one string accepted by
the language and the other string rejected. The size of an index set
X equals the number of equivalence classes it has and the minimum
number of states required to represent it using a DFA. Each element in
the language is accepted by only one equivalence class.
## Problem Approach
Prove that language L is regular.
Prove that language L is regular.
1) Define a set X which is infinite in size - this doesn't have to be in the language.
@ -23,13 +30,13 @@ the other is not in the language.
## Example
Prove the following language is non-regular:
Prove the following language is non-regular:
$$
L={ww^r | w \in {0,1}^*}
$$
answer:
answer:
1)
@ -37,13 +44,14 @@ $$
X = {(01)^i | i \geq 0}
$$
Pick any 2 elements of X and show pairwise distinguishable
Pick any 2 elements of X and show pairwise distinguishable
$$
x = (01)^i, y = (01)^j | i \neq j
$$
suppose we pick
suppose we pick
$$
z = (10)^i\\
xz \in L\\
@ -53,78 +61,91 @@ $$
# DFA minimization algorithm
Types of Problems:
Types of Problems:
- Prove DFA is minimal
- Minimize the DFA
The argument for DFA minimization comes from the Myhill-Nerode theorem. Given
a DFA, if you can form a set of strings which represent each state and they are all
pairwise distinguishable, then the DFA is minimal with that many states.
The argument for DFA minimization comes from the Myhill-Nerode
theorem. Given a DFA, if you can form a set of strings which represent
each state and they are all pairwise distinguishable, then the DFA is
minimal with that many states.
## Prove DFA is minimal
For these types of problems you construct a table and show that each state is pairwise distinguishable.
To show pairwise distinguishably you have to show that there exists a string where if appended to one element
makes it accepted by the language but pushes the other string out of the language.
For these types of problems you construct a table and show that each
state is pairwise distinguishable. To show pairwise distinguishably
you have to show that there exists a string where if appended to one
element makes it accepted by the language but pushes the other string
out of the language.
### Example
Prove the following DFA is minimal.
Prove the following DFA is minimal.
![DFA Example](media/CSTHEORY/DFAMinimalProof.png)
Find a set of strings which represent the minimal path to each state in the DFA.
Find a set of strings which represent the minimal path to each state
in the DFA.
$$
X = \{\epsilon, b, bb, ba\}
$$
Show that each state is pairwise distinguishable.
Show that each state is pairwise distinguishable.
![DFA Example](media/CSTHEORY/DFAMinimalTable.png)
## Minimize the DFA
To use the concept of being indistinguishable to minimize a DFA, you can use a table to keep track which
states are distinguishable from each other. The states which are not indistinguishable can
be combined. To solve one of these problems you start by creating a table which compares each of the
states in the DFA. You then go through and mark the states which are indistinguishable -- start with
the ones with different accepting statuses. Then you continue marking off states where if you transition with
a symbol on the DFA you are distinguishable and the other state is non-distinguishable according to the table.
To use the concept of being indistinguishable to minimize a DFA, you
can use a table to keep track which states are distinguishable from
each other. The states which are not indistinguishable can be
combined. To solve one of these problems you start by creating a table
which compares each of the states in the DFA. You then go through and
mark the states which are indistinguishable -- start with the ones
with different accepting statuses. Then you continue marking off
states where if you transition with a symbol on the DFA you are
distinguishable and the other state is non-distinguishable according
to the table.
### Example
Minify the Following DFA:
Minify the Following DFA:
![DFA Example](media/CSTHEORY/DFAMinification.png)
After marking the states with different accepting criteria as being distinguishable you get this table:
After marking the states with different accepting criteria as being
distinguishable you get this table:
![Half Complete Table](media/CSTHEORY/MinificationTable.svg)
After looping through all pairs and marking them on the table if there exists symbol which results in one state
to be distinguishable and one to be indistinguishable you get this table:
After looping through all pairs and marking them on the table if there
exists symbol which results in one state to be distinguishable and
one to be indistinguishable you get this table:
![Min TableTable](media/CSTHEORY/MinTable2.svg)
According to the table you are able to combine {D, A, B}, {C, F}, and {E, G}.
According to the table you are able to combine {D, A, B}, {C, F}, and
{E, G}.
Minimal DFA:
Minimal DFA:
![Min DFA](media/CSTHEORY/MinimalDFA.svg)
# Pumping lemma for regular languages
The pumping lemma cannot prove that a language is regular, however, you can use it
to show that some languages are non-regular. This theory gets at the idea that if
a regular language is long enough/infinite, it will have a state somewhere which is
repeated on the path that accepts the string.
The pumping lemma cannot prove that a language is regular, however,
you can use it to show that some languages are non-regular. This
theory gets at the idea that if a regular language is long
enough/infinite, it will have a state somewhere which is repeated on
the path that accepts the string.
The accepted strings can be divided into three parts:
The accepted strings can be divided into three parts:
- Symbols leading up to the loop
- Symbols which complete a loop and come back to start of loop
@ -134,7 +155,7 @@ The accepted strings can be divided into three parts:
To Show that a language L is not regular using pumping lemma:
To Show that a language L is not regular using pumping lemma:
- Use a proof by contradiction
- Assume L is regular
@ -148,52 +169,53 @@ To Show that a language L is not regular using pumping lemma:
## Example
Show that the following language is non-regular.
Show that the following language is non-regular.
$$
{0^n1^n | n \geq 0}
$$
Proof by contradiction
Proof by contradiction
Assume that L is regular.
Assume that L is regular.
Let p be the pumping length associated with L
Let p be the pumping length associated with L
$$
S = o^p1^p
$$
S is valid since
S is valid since
$$
|s| \geq p, S \in L
$$
For any valid decomposition
For any valid decomposition
S = xyz
S = xyz
such that |xy| <= p and |y| > 0
such that |xy| <= p and |y| > 0
Consider:
Consider:
$$
xy^2z
$$
By the pumping lemma this should be in the language but it is not. Therefore our assumption that the
language is regular is false.
By the pumping lemma this should be in the language but it is not.
Therefore our assumption that the language is regular is false.
![Min DFA](media/CSTHEORY/PumpingLemmaExample.svg)
# Context-free grammars, closure properties for CFLs
The context-free grammars are a super-set of the regular languages. This means that CFG's can represent
some non-regular languages and every regular language. Contest-free Languages are defined by Context-Free Grammars and accepted using
Push-down Automata machines.
The context-free grammars are a super-set of the regular languages.
This means that CFG's can represent some non-regular languages and
every regular language. Contest-free Languages are defined by
Context-Free Grammars and accepted using Push-down Automata machines.
Context Free Grammars are Represented using:
Context Free Grammars are Represented using:
- **Terminals** = Set of symbols in that language
- **Variables** = Set of symbols representing categories
@ -202,7 +224,7 @@ Context Free Grammars are Represented using:
## Example 1
Grammar G:
Grammar G:
$$
A \rightarrow 0A1 \\
@ -211,7 +233,7 @@ B \rightarrow \# \\
$$
This grammar describes the following language:
This grammar describes the following language:
$$
L = \{0^k\#1^k | k \geq 0\}
@ -219,7 +241,7 @@ $$
## Example 2
Give CFG for non-Palindromes
Give CFG for non-Palindromes
$$
S \rightarrow aXb | bXa | aSa | bSb | ab | ba \\
@ -227,13 +249,14 @@ X \rightarrow aX | bX | a | b \\
$$
In this example, the S rule recursively applies itself until something that is not a palindrome is added.
Once you exit the S state, you can finish by appending anything to the middle of the string.
In this example, the S rule recursively applies itself until something
that is not a palindrome is added. Once you exit the S state, you can
finish by appending anything to the middle of the string.
## Example 3
Give CFG for the following language:
Give CFG for the following language:
$$
\{a^ib^jc^kd^l | i+k = j + l\}
@ -248,28 +271,32 @@ $$
## Closure
CFLs are closed under union, concatenation, and Kleene star.
CFLs are closed under union, concatenation, and Kleene star.
- Union: Create a new starting variable which goes to either branch.
-Kleene Star: We can repeatedly concat the derivations of the string. However, we also need to make sure that epsilon occurs in the string.
- Concatenation: From start variable we force the concatenation of two variables representing each state sub CFG
# Parse trees, ambiguity
Parse Trees are simply graphical means to illustrate a deviation of a string from a grammar.
The root of the tree will be the start variable, interior nodes are other variables. Leaf nodes are
terminal symbols.
Parse Trees are simply graphical means to illustrate a deviation of a
string from a grammar. The root of the tree will be the start
variable, interior nodes are other variables. Leaf nodes are terminal
symbols.
A CFG is said to be ambiguous if there is at least one string with two or more distinct derivations.
Leftmost and rightmost derivations are not ambiguous.
A CFG is said to be ambiguous if there is at least one string with two
or more distinct derivations. Leftmost and rightmost derivations are
not ambiguous.
To remove ambiguity try to force order or break CFG into cases.
To remove ambiguity try to force order or break CFG into cases.
# Chomsky Normal Form
Useful form for CFGs since they allow you to easily identify if a string is in a language.
Useful form for CFGs since they allow you to easily identify if a
string is in a language.
Form:
Form:
$$
A \rightarrow BC\\
@ -277,7 +304,7 @@ A \rightarrow a\\
S \rightarrow \epsilon
$$
Convert CFG to CNF (Chomsky Normal Form).
Convert CFG to CNF (Chomsky Normal Form).
- Add new start variable
@ -289,7 +316,7 @@ Convert CFG to CNF (Chomsky Normal Form).
## Example
Convert the following CFG to a CNF
Convert the following CFG to a CNF
$$
S \rightarrow ASA | aB\\
@ -297,7 +324,7 @@ A \rightarrow B | S\\
B \rightarrow b | \epsilon
$$
Step 1: Add new start variable.
Step 1: Add new start variable.
$$
S_0 \rightarrow S\\
@ -306,7 +333,7 @@ A \rightarrow B | S\\
B \rightarrow b | \epsilon
$$
Step 2: Remove epsilon rules.
Step 2: Remove epsilon rules.
$$
S_0 \rightarrow S\\
@ -323,7 +350,7 @@ A \rightarrow B | S\\
B \rightarrow b
$$
Step 3: Remove unit rules
Step 3: Remove unit rules
(Remove A -> B)
@ -354,12 +381,14 @@ $$
# Push-Down automata
These are NFAs but they also have a stack. This allows us to solve any problem which
can be represented with a CFG.
These are NFAs but they also have a stack. This allows us to solve any
problem which can be represented with a CFG.
The stack has it's own alphabet. The dollar symbol typically represents the empty stack.
The stack has it's own alphabet. The dollar symbol typically
represents the empty stack.
With each transition you can examine the stack, push to the stack and move to a new state.
With each transition you can examine the stack, push to the stack and
move to a new state.
## Example
@ -373,16 +402,18 @@ $$
# Construction to convert CFG to a PDA
Basic idea: use stack to hold progressive derivations of a string using rules of grammar.
Basic idea: use stack to hold progressive derivations of a string
using rules of grammar.
## Example
Convert the following CFG to a PDA:
Convert the following CFG to a PDA:
$$
S \rightarrow aTb | b \\
T \rightarrow Ta | \epsilon
$$
![](media/CSTHEORY/PDAConstruction.svg)

+ 100
- 76
blogContent/posts/programming/everything-fibonacci.md View File

@ -1,19 +1,19 @@
If you have ever taken a computer science class you probably
know what the fibonacci sequence is and how to calculate it.
For those who don't know: [Fibonacci](https://en.wikipedia.org/wiki/Fibonacci)
is a sequence of numbers starting with 0,1 whose next number is the sum
of the two previous numbers. After having multiple of my CS classes
give lectures and homeworks on the Fibonacci sequence; I decided
to write a blog post going over
the 4 main ways of calculating the nth term of the Fibonacci sequence.
In addition to providing the python code for calculating the nth perm of the sequence, a proof for their validity
and an analysis of their time complexities both mathematically and empirically will
be examined.
If you have ever taken a computer science class you probably know what
the fibonacci sequence is and how to calculate it. For those who don't
know: [Fibonacci](https://en.wikipedia.org/wiki/Fibonacci) is a
sequence of numbers starting with 0,1 whose next number is the sum of
the two previous numbers. After having multiple of my CS classes give
lectures and homeworks on the Fibonacci sequence; I decided to write
a blog post going over the 4 main ways of calculating the nth term of
the Fibonacci sequence. In addition to providing the python code for
calculating the nth perm of the sequence, a proof for their validity
and an analysis of their time complexities both mathematically and
empirically will be examined.
# Slow Recursive Definition
By the definition of the Fibonacci sequence, it is the most natural to write it as
a recursive definition.
By the definition of the Fibonacci sequence, it is the most natural to
write it as a recursive definition.
```Python
def fib(n):
@ -24,17 +24,19 @@ def fib(n):
##Time Complexity
Observing that each call has two recursive calls we can place an upper bound on this
function as $O(2^n)$. However, if we solve this recurrence we can place a tight bound for time complexity.
Observing that each call has two recursive calls we can place an upper
bound on this function as $O(2^n)$. However, if we solve this
recurrence we can place a tight bound for time complexity.
We can write a recurrence for the number of times fib is called:
We can write a recurrence for the number of times fib is called:
$$
F(1) = 1\\
F(n) = F(n-1) + F(n-2)\\
$$
Next, we replace F(n) with $a^n$ since we want to find rate of exponential growth.
Next, we replace F(n) with $a^n$ since we want to find rate of
exponential growth.
$$
a^n = a^{n-1} + a^{n-2}\\
@ -43,25 +45,28 @@ $$
a = \frac{1 \pm sqrt(5)}{2}\\
$$
From this calculation we can conclude that F(n) $\in \Theta 1.681^n$. We don't have to worry about
the negative root since it would not be asymptotically relevant by the definition of $\Theta$.
From this calculation we can conclude that F(n) $\in \Theta 1.681^n$.
We don't have to worry about the negative root since it would not be
asymptotically relevant by the definition of $\Theta$.
## Measured Performance
Here is a graph of the actual performance that I observed from this recursive definition of Fibonacci.
Here is a graph of the actual performance that I observed from this
recursive definition of Fibonacci.
![Recursive Definition](media/fibonacci/RecursiveDefinition.png)
# Accumulation Solution
The problem with the previous recursive solution is that you had to recalculate certain
terms of fibonacci a ton of times. A summation variable would help us avoid this problem.
You could write this solution using a simple loop or dynamic programming
, however, I chose to use recursion to demonstrate that it's recursion which made the first
problem slow.
The problem with the previous recursive solution is that you had to
recalculate certain terms of fibonacci a ton of times. A summation
variable would help us avoid this problem. You could write this
solution using a simple loop or dynamic programming , however, I chose
to use recursion to demonstrate that it's recursion which made the
first problem slow.
```Python
@ -70,23 +75,26 @@ def fibHelper(n, a, b):
return a
elif n == 1:
return b
return fibHelper(n-1, b, a+b)
return fibHelper(n-1, b, a+b)
```
```python
def fibIterative(n):
return fibHelper(n, 0, 1)
```
In this code example, fibHelper is a method which accumulates the previous two terms.
The fibIterative is a wrapper method which sets the two initial terms equal to 0 and 1
representing the fibonacci sequence. At first it may not be obvious that fibIterative(n)
is equivalent to fib(n). To demonstrate that these two are in fact equivalent, I broke this
into two inductive proofs.
In this code example, fibHelper is a method which accumulates the
previous two terms. The fibIterative is a wrapper method which sets
the two initial terms equal to 0 and 1 representing the fibonacci
sequence. At first it may not be obvious that fibIterative(n) is
equivalent to fib(n). To demonstrate that these two are in fact
equivalent, I broke this into two inductive proofs.
## Proof for Fib Helper
**Lemma:** For any n $\epsilon$ N if n $>$ 1 then
$fibHelper(n, a, b) = fibHelper(n - 1, a, b) + fibHelper(n - 2, a, b)$.
**Proof via Induction**
**Base Case**: n = 2:
@ -99,7 +107,7 @@ $$
**Inductive Step:**
Assume proposition is true for all n and show n+1 follows.
Assume proposition is true for all n and show n+1 follows.
$$
RHS=fibHelper(n+1;a,b)\\
@ -114,7 +122,7 @@ $\Box$
## Proof That fibIterative = Fib
**Lemma:** For any n $\in$ N, $fib(n)$ = $fibIterative(n, 0, 1)$
**Proof via Strong Induction**
**Base Case**: n = 0:
@ -131,7 +139,7 @@ $$
**Inductive Step:**
Assume proposition is true for all n and show n+1 follows.
Assume proposition is true for all n and show n+1 follows.
$$
fib(n+1) = fib(n) + fib(n-1)\\
@ -144,9 +152,10 @@ $\Box$
## Time Complexity
Suppose that we wish to solve for the time complexity in terms of the number of additions needed to be
computed. Based on fibHelper we can see that it performs one addition every recursive call.
We can now form a recurrence for time complexity.
Suppose that we wish to solve for the time complexity in terms of the
number of additions needed to be computed. Based on fibHelper we can
see that it performs one addition every recursive call. We can now
form a recurrence for time complexity.
$$
T(0) = 0\\
@ -155,12 +164,12 @@ $$
T(n) = n-1\\
$$
From this recurrence we can say that fibHelper $\in \Theta(n)$.
From this recurrence we can say that fibHelper $\in \Theta(n)$.
## Measured Performance
Notice how much faster this solution is compared to the original recursive solution for
Fibonacci.
Notice how much faster this solution is compared to the original
recursive solution for Fibonacci.
![Iterative Performance](media/fibonacci/Iterative.png)
@ -168,8 +177,9 @@ Fibonacci.
# Matrix Solution
We can actually get better than linear for performance for Fibonacci while still using
recursion. However, to do so we need to know this fact:
We can actually get better than linear for performance for Fibonacci
while still using recursion. However, to do so we need to know this
fact:
$$
\begin{bmatrix}
@ -183,10 +193,12 @@ F_n & F{n-1}
$$
Without any tricks, raising a matrix to a power n times would not get
us better than linear performance. However, if we use the [Exponentiation by Squaring](https://en.wikipedia.org/wiki/Exponentiation_by_squaring)
method, we can expect to see logarithmic time. Since two spots in the matrix are always equal,
I represented the matrix as an array with only three elements to reduce the space and
computations required.
us better than linear performance. However, if we use the
[Exponentiation by
Squaring](https://en.wikipedia.org/wiki/Exponentiation_by_squaring)
method, we can expect to see logarithmic time. Since two spots in the
matrix are always equal, I represented the matrix as an array with
only three elements to reduce the space and computations required.
```Python
@ -196,8 +208,9 @@ def multiply(a,b):
product[1] = a[0]*b[1] + a[1]*b[2]
product[2] = a[1]*b[1] + a[2]*b[2]
return product
```
```python
def power(l, k):
if k == 1:
return l
@ -206,8 +219,9 @@ def power(l, k):
return multiply(temp, temp)
else:
return multiply(l, multiply(temp, temp))
```
```python
def fibPower(n):
l = [1,1,0]
return power(l, n)[1]
@ -216,15 +230,19 @@ def fibPower(n):
## Time Complexity
For this algorithm, lets solve for the time complexity as the number of additions and multiplications required.
For this algorithm, lets solve for the time complexity as the number
of additions and multiplications required.
Since we are always multiplying two 2x2 matrices, that operation is constant time.
Since we are always multiplying two 2x2 matrices, that operation is
constant time.
$$
T_{multiply} = 9
$$
Solving for the time complexity of fib power is slightly more complicated.
Solving for the time complexity of fib power is slightly more
complicated.
$$
T_{power}(1) = 0\\
T_{power}(n) = T(\left\lfloor\dfrac{n}{2}\right\rfloor) + T_{multiply}\\
@ -234,7 +252,8 @@ $$
T_{power}(n) = T(\left\lfloor\dfrac{n}{2^k}\right\rfloor) + 9k\\
$$
let $k=k_0$ such that $\left\lfloor\dfrac{n}{2^{k_0}}\right\rfloor = 1$
let $k=k_0$ such that $\left\lfloor\dfrac{n}{2^{k_0}}\right\rfloor =
1$
$$
\left\lfloor\dfrac{n}{2^{k_0}}\right\rfloor = 1 \rightarrow 1 \leq \frac{n}{2^{k_0}} < 2\\
@ -246,13 +265,14 @@ $$
T_{fibPower}(n) = T_{power}(n)\\
$$
Now we can state that $fibPower(n) \in \Theta(log(n))$.
Now we can state that $fibPower(n) \in \Theta(log(n))$.
## Inductive Proof for Matrix Method
I would like to now prove that this matrix identity is valid since it is not at first obvious.
I would like to now prove that this matrix identity is valid since it
is not at first obvious.
**Lemma:** For any n $\epsilon$ N if n $>$ 0 then
$$
@ -266,7 +286,7 @@ I would like to now prove that this matrix identity is valid since it is not at
\end{bmatrix}^n
$$
Let
Let
$$
A=
@ -317,26 +337,29 @@ $\Box$
![FibPower Performance](media/fibonacci/FibPower.png)
As expected by our mathematical calculations, the algorithm appears to be running in
logarithmic time.
As expected by our mathematical calculations, the algorithm appears to
be running in logarithmic time.
## Measured Performance With Large Numbers
![FibPower Performance](media/fibonacci/FibPowerBigPicture.png)
When calculating the fibonacci term for extremely large numbers despite having a polynomial
time complexity, the space required to compute each Fibonacci term grows exponentially. Since our
performance is only pseudo-polynomial we see a degrade in our performance when calculating
large terms of the fibonacci sequence.
When calculating the fibonacci term for extremely large numbers
despite having a polynomial time complexity, the space required to
compute each Fibonacci term grows exponentially. Since our performance
is only pseudo-polynomial we see a degrade in our performance when
calculating large terms of the fibonacci sequence.
The one amazing thing to point out here is that despite calculating the 10,000 term of Fibonacci,
this algorithm is nearly 400 times faster than the recursive algorithm when calculating
the 30th term of Fibonacci.
The one amazing thing to point out here is that despite calculating
the 10,000 term of Fibonacci, this algorithm is nearly 400 times
faster than the recursive algorithm when calculating the 30th term of
Fibonacci.
# Closed Form Definition
It is actually possible to calculate Fibonacci in constant time using Binet's Formula.
It is actually possible to calculate Fibonacci in constant time using
Binet's Formula.
$$
F_n = \frac{(\frac{1+\sqrt{5}}{2})^n-(\frac{1-\sqrt{5}}{2})^n}{\sqrt{5}}
@ -351,8 +374,9 @@ def fibClosedFormula(n):
## Derivation of Binet's Formula
Similar to when we were calculating the time complexity of the basic recursive definition
, we want to start by finding the two roots of the equation in terms of exponents.
Similar to when we were calculating the time complexity of the basic
recursive definition , we want to start by finding the two roots of
the equation in terms of exponents.
$$
a^n = a^{n-1} + a^{n-2}\\
@ -362,15 +386,15 @@ $$
a = \frac{1 \pm sqrt(5)}{2}\\
$$
Since there are two roots to the equation, the solution of $F_n$ is going to be
a linear combination of the two roots.
Since there are two roots to the equation, the solution of $F_n$ is
going to be a linear combination of the two roots.
$$
F_n = c_1(\frac{1 + \sqrt{5}}{2})^n + c_2(\frac{1 - \sqrt{5}}{2})^n
$$
Fact: $F_1$ = 1
Fact: $F_1$ = 1
$$
F_1 = 1\\
@ -378,8 +402,7 @@ $$
= \frac{c_1}{2} + \frac{c_2}{2} + \frac{c_1\sqrt{5}}{2} - \frac{c_2\sqrt{5}}{2}\\
$$
Let $c_1 = \frac{1}{\sqrt{5}}$,
Let $c_2 = \frac{-1}{\sqrt{5}}$
Let $c_1 = \frac{1}{\sqrt{5}}$, Let $c_2 = \frac{-1}{\sqrt{5}}$
$$
F_n = \frac{1}{\sqrt(5)}((\frac{1+\sqrt{5}}{2})^n-(\frac{1-\sqrt{5}}{2})^n)\\
@ -388,8 +411,9 @@ $$
## Time Complexity
Since we managed to find the closed form of the fibonacci sequence we can expect to see constant performance.
Since we managed to find the closed form of the fibonacci sequence we
can expect to see constant performance.
## Measured Performance
![FibPower Performance](media/fibonacci/ConstantTimeComplexity.png)
![FibPower Performance](media/fibonacci/ConstantTimeComplexity.png)

Loading…
Cancel
Save