I moved my blog again. This time to GitHub Pages.
Happy coding!!
Saturday, April 1, 2017
Sunday, February 19, 2017
Substituting polymorphism for if/else or switch/case - Example #1 - Shapes
This is Example #1 of the series of examples I'm going to give on "Substituting polymorphism for if/else or switch/case statements".
It's your first day at work. You are very excited to be involved in a real-world project.
Your team lead tried to explain to you the purpose of the project you are involved in.
You have to implement this method:
(Because I used C# for many years, I'm going to display C# in these posts. But I will also write these examples in Python and maybe other OO languages in the future. You can view them here.)
The codebase of the project you are involved in already have these classes:
Then after a few hours of hard work, you pushed your code to the repository, waiting for your team lead's comments.
Your team lead's comment came in.
Now I understand what you want me to do with drawing shapes.
Let me be the one to refactor my code, please. I think I already know what to do.
(Please go to the GitHub repository to view the complete refactoring.)
MTGOTB, TCOTU, BGWML
You have a new task
It's your first day at work. You are very excited to be involved in a real-world project.
Your team lead tried to explain to you the purpose of the project you are involved in.
"Here at Hugis Inc., we strive to be the best drawer of shapes."After an hour, he gave you your first task.
You have to implement this method:
(Because I used C# for many years, I'm going to display C# in these posts. But I will also write these examples in Python and maybe other OO languages in the future. You can view them here.)
The codebase of the project you are involved in already have these classes:
- a base Shape class,
- classes for Circle, Square, and Triangle that derives from the Shape class.
The Evil code
This task is so easy!!! (you say to yourself)You then started typing on the keyboard. Click! Click! Click!
Then after a few hours of hard work, you pushed your code to the repository, waiting for your team lead's comments.
The Good Code
Your team lead's comment came in.
"Good job!"Wow!
"But there is a better way of doing this.You then went to his table and watched him refactor your code.
"We want to put the function drawCircle() inside the Circle class, and the function drawSquare() inside the Square class, because we want to have an easy access them anywhere in the system.
"Come over here. I'm going to show you how I will do the changes."
"Because we want to be able to draw each Shape that we have, we will create an abstract method named draw() in our base Shape class.No.
abstract public void Draw();
"Do you know what an abstract method is?"
"An abstract method is a method definition that has no implementation -- like the getArea() method in the Shape class.Ahh! The Shape class did not provide an implementation for getArea() because different shapes has different formulas for getting the area! Great!
"Notice that getArea() does not have an implementation inside the Shape class. But any class that inherits from the Shape class is required to provide an implementation for getArea()"
Now I understand what you want me to do with drawing shapes.
Let me be the one to refactor my code, please. I think I already know what to do.
"Ok! Go Ahead!"You went back to your machine and started refactoring your code.
(Please go to the GitHub repository to view the complete refactoring.)
MTGOTB, TCOTU, BGWML
Saturday, February 18, 2017
Substituting polymorphism for if/else or switch/case - Introduction
A few weeks ago I saw this post from a facebook friend:
He is saying jokingly something like "Programming is like love... don't switch() because it will end up with a break... LOL"
I then asked him if his alternative to switch/case is polymorphism. He said no; and that he does not yet know what polymorphism is.
So after a few days, I thought of creating a blog post where I will teach how to replace if/else or switch/case statements with polymorphism.
But did you know that, if you are using an object-oriented language such as Java, C# or Python, codes like those ones above are sometimes considered evil?
But I did not say that they are always evil. I said that they are sometimes evil. ("Sometimes evil" because I only have a few years of programming experience. "Often evil" when I have more :D . I'm just joking.)
They are evil because they might make modifications in the future much harder than they should be.
I found this great explanation by Steve Guidetti about polymorphism from code.tutsplus.com:
Then after that, go back here because I'm going to give you a number of examples on how to convert your if/else and switch/case statements into polymorphic code.
(Another reason why I delegate the explanation to others is because I'm not very good at explaining things using the English language :) )
It's only that I read an article a few months ago which claims that giving students lots of examples of a problem and their solutions can help them easily spot similar occurrences of that problem and can help them easily solve those kinds of problems. (But I already forgot where that article is located. Maybe I took a note of it somewhere but I'm not able to find it. I will just update this post when I will find it in the future)
Here are the examples:
1. Drawing Shapes
2. to be posted
3. to be posted
4. to be posted
Examples from other people:
https://sourcemaking.com/refactoring/replace-conditional-with-polymorphism
Have fun coding!!!
MTGOTB TCOTU BGWML
He is saying jokingly something like "Programming is like love... don't switch() because it will end up with a break... LOL"
I then asked him if his alternative to switch/case is polymorphism. He said no; and that he does not yet know what polymorphism is.
So after a few days, I thought of creating a blog post where I will teach how to replace if/else or switch/case statements with polymorphism.
I'm going to try to teach you how to replace your if/else with polymorphism
Have you seen code like this one below? If (typeOfShape is Circle)
drawCircle()
Elseif (typeOfShape is Square)
drawSquare()
Elseif (typeOfShape is Triangle)
drawTriangle()
Or this one? Switch (typeOfShape)
Case Circle:
drawCircle()
Case Square:
drawSquare()
Case Triangle:
drawTriangle()
If you have been programming for a few years already, I believe you have seen lots of code that looks like those.But did you know that, if you are using an object-oriented language such as Java, C# or Python, codes like those ones above are sometimes considered evil?
Evil? (you might say).Yes! EVIL!
But I did not say that they are always evil. I said that they are sometimes evil. ("Sometimes evil" because I only have a few years of programming experience. "Often evil" when I have more :D . I'm just joking.)
They are evil because they might make modifications in the future much harder than they should be.
(you might be asking…) How else am I going to do conditional constructs like that? If/else and switch/case are the only ones available!There is actually another method available to us on how to do conditions in OO languages. It is called polymorphism.
I found this great explanation by Steve Guidetti about polymorphism from code.tutsplus.com:
Polymorphism is a long word for a very simple concept.There are already lots of available resources on the web about polymorphism. [The] Google [search engine] is your friend. Ask your friend to teach you polymorphism. But I recommend you to start with that explanation from code.tutsplus.com I linked to above, or from stackoverflow.
Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.
The beauty of polymorphism is that the code working with the different classes does not need to know which class it is using since they're all used the same way.
A real world analogy for polymorphism is a button. Everyone knows how to use a button: you simply apply pressure to it. What a button "does," however, depends on what it is connected to and the context in which it is used -- but the result does not affect how it is used. If your boss tells you to press a button, you already have all the information needed to perform the task.
Then after that, go back here because I'm going to give you a number of examples on how to convert your if/else and switch/case statements into polymorphic code.
(Another reason why I delegate the explanation to others is because I'm not very good at explaining things using the English language :) )
Why are you going to give me lots of examples? I think one example will do. 'You think I'm dumb?No. I do not think you are dumb.
It's only that I read an article a few months ago which claims that giving students lots of examples of a problem and their solutions can help them easily spot similar occurrences of that problem and can help them easily solve those kinds of problems. (But I already forgot where that article is located. Maybe I took a note of it somewhere but I'm not able to find it. I will just update this post when I will find it in the future)
Here are the examples:
1. Drawing Shapes
2. to be posted
3. to be posted
4. to be posted
Examples from other people:
https://sourcemaking.com/refactoring/replace-conditional-with-polymorphism
Have fun coding!!!
MTGOTB TCOTU BGWML
Saturday, February 4, 2017
Hints for Nand2Tetris Chapter 1 Exercises
I have already done Chapters 1 to 8 of Nand2Tetris last 2013. But I want to finish it. I have decided to do everything all over again.
I am not allowed to put online my solutions to the Nand2Tetris exercises. So what I'm going to do instead is to give some hints on how to solve them.
Here are the hints for the Chapter 1 Exercises:
1. Not gate - look at the Nand truth table; notice the output when both a and b are the same
2. And gate - use your newly created Not gate (and the Nand gate of course)
3. Or gate - we can use the idea from the Canonical Representation presented on page 9. But instead of focusing on the 1 outputs of the Or function, let's focus instead on the 0 output.
The Or function has only one 0 output.
This means that we can be able to create an Or gate without using an Or gate. haha
We can solve this using the And and Not gates
"We will Not the And."
4. Xor gate - we can now use the Canonical Representation from page 9.
5. Multiplexor (Mux) - same as #4; use the Canonical Representation from page 9
6. Demultiplexor (DMux) - use truth table to determine when a and b will be 1; then use the Canonical Representation
7 to 10. Multi-Bit gates (Not16, And16, Or16, Mux16) - read "A.5.3 Busses" of the Appendix to know more about how to solve these.
Do something like this, for example, for the Multibit Not gate:
Not(in=in[0], out=out[0]);
Not(in=in[1], out=out[1]);
...
Not(in=in[9], out=out[9]);
12 Multi-Way/Multi-Bit Multiplexor
12.a (Mux4Way16) - use Mux16 and temporary internal pins
12.b Mux8Way16 - similar to 12.a but also use Mux4Way16
13. Multi-Way/Multi-Bit Demultiplexor - quite similar to 12.a and 12.b
13.a DMux4Way - Use DMux and internal pins
13.b DMux8Way - same to 13.b but also use DMux4Way
If you have any comments or corrections or ideas on how to make the hints better, please tell me. Thanks!
I am not allowed to put online my solutions to the Nand2Tetris exercises. So what I'm going to do instead is to give some hints on how to solve them.
Here are the hints for the Chapter 1 Exercises:
1. Not gate - look at the Nand truth table; notice the output when both a and b are the same
2. And gate - use your newly created Not gate (and the Nand gate of course)
3. Or gate - we can use the idea from the Canonical Representation presented on page 9. But instead of focusing on the 1 outputs of the Or function, let's focus instead on the 0 output.
The Or function has only one 0 output.
This means that we can be able to create an Or gate without using an Or gate. haha
We can solve this using the And and Not gates
"We will Not the And."
4. Xor gate - we can now use the Canonical Representation from page 9.
5. Multiplexor (Mux) - same as #4; use the Canonical Representation from page 9
6. Demultiplexor (DMux) - use truth table to determine when a and b will be 1; then use the Canonical Representation
7 to 10. Multi-Bit gates (Not16, And16, Or16, Mux16) - read "A.5.3 Busses" of the Appendix to know more about how to solve these.
Do something like this, for example, for the Multibit Not gate:
Not(in=in[0], out=out[0]);
Not(in=in[1], out=out[1]);
...
Not(in=in[9], out=out[9]);
...
11. Multi-Way Or (Or8Way) - use Or gates and internal pins (see A.5.2 of Appendix A for an explanation for internal pins)
12 Multi-Way/Multi-Bit Multiplexor
12.a (Mux4Way16) - use Mux16 and temporary internal pins
12.b Mux8Way16 - similar to 12.a but also use Mux4Way16
13. Multi-Way/Multi-Bit Demultiplexor - quite similar to 12.a and 12.b
13.a DMux4Way - Use DMux and internal pins
13.b DMux8Way - same to 13.b but also use DMux4Way
If you have any comments or corrections or ideas on how to make the hints better, please tell me. Thanks!
Monday, August 8, 2016
I'm reviewing data structures and some graph algorithms using Stanford's CS106X
A few weeks ago, I wanted to be able to solve some problems on UVA Online Judge that requires some knowledge of graph algorithms. So I thought of trying to do again the assignments for Stanford's CS106B that I did last 2011.
The problem was that the assignment files that I have requires Visual Studio 2005. I tried to find ways to make it work on VS 2015 but I failed.
So I went to the latest CS106B website to download their latest assignment files (maybe they are using Visual Studio 2015 now?).
... Toinks! I needed to login to download the files. But I'm not a Stanford student! So I was not able to download the files.
Luckily, I found the latest website of CS106X and the files are downloadable. I thought to myself that the problems for CS106X might be more difficult than CS106B's but I think I can be able to do this now because I already experienced solving problems similar to these before.
The handout on the Course Information says that uploading my code to GitHub is a violation to the Honor Code...
... so I'm not going to put my code on GitHub or anywhere where anyone can download it. (I placed my solutions online last 2011 when I did CS106B but I already removed them.)
What I'm going to do instead is to put screenshots and the finished executable files of my solutions online just to give proof that I solved the exercises.
You can see the screenshots and executable files of my solutions on my GitHub.
Here is the screenshot of the first problem that I did:
The problem was that the assignment files that I have requires Visual Studio 2005. I tried to find ways to make it work on VS 2015 but I failed.
So I went to the latest CS106B website to download their latest assignment files (maybe they are using Visual Studio 2015 now?).
... Toinks! I needed to login to download the files. But I'm not a Stanford student! So I was not able to download the files.
Luckily, I found the latest website of CS106X and the files are downloadable. I thought to myself that the problems for CS106X might be more difficult than CS106B's but I think I can be able to do this now because I already experienced solving problems similar to these before.
The handout on the Course Information says that uploading my code to GitHub is a violation to the Honor Code...
The following four activities are among the many considered to be Honor Code violations in this course:
1. Looking at another student's code.
2. Showing another student your code, or making your code public so that it's searchable and easily discovered online or elsewhere.
3. Discussing assignments in such detail that you duplicate a portion of someone else's code in your own program.
4. Uploading your code to a public repository (e.g. github.com or bitbucket.com) so that others can easily discover it via word of mouth or search engines. If you'd like to upload your code to a private repository, you can do so on bitbucket or some other hosting service that provides free-of-charge private hosting.
... so I'm not going to put my code on GitHub or anywhere where anyone can download it. (I placed my solutions online last 2011 when I did CS106B but I already removed them.)
What I'm going to do instead is to put screenshots and the finished executable files of my solutions online just to give proof that I solved the exercises.
You can see the screenshots and executable files of my solutions on my GitHub.
Here is the screenshot of the first problem that I did:
Thursday, August 4, 2016
The Angular 2 "Tour of Heroes" tutorial has a missing part
I think there is something missing in the "Routing" part of the "Tour of Heroes" tutorial -- after the "Make the router available" section and before the "Router Links" section.
The <router-outlet> needs "directives: [ROUTER_DIRECTIVES]". But the code for that is given way below of the tutorial.
The <router-outlet> needs "directives: [ROUTER_DIRECTIVES]". But the code for that is given way below of the tutorial.
I got confused. But I was able to see the error and found a fix for it.
Maybe you got confused also.
Here is the link to what I think should be placed in that missing part. I'm not a native English speaker so my English might not be 100% correct but I believe you can be able to understand it.
Happy coding!
Here is the link to what I think should be placed in that missing part. I'm not a native English speaker so my English might not be 100% correct but I believe you can be able to understand it.
Happy coding!
Sunday, July 31, 2016
What is the purpose of "imports" in project.json of .NET Core apps?
I was doing the tutorial "Building Your First Web API with ASP.NET Core MVC and Visual Studio" and after I finished it, I thought of trying to see if Moq will work with .NET Core.
Then I changed the content project.json file with the JSON below whose significant parts came from the "Testing your Console App" section of the tutorial "Getting started with .NET Core on Windows/Linux/macOS using the command line":
Then I tried to remove the "imports" part of the project.json file because I do not know what it was for. But this error pops up in Visual Studio:
... and errors like this in the Output window:
So I tried to look for the purpose of this "imports".
I found the docs for project.json but I do not understand what it is trying to say.
Then I tried to google for using this:
Happy coding!
Then I changed the content project.json file with the JSON below whose significant parts came from the "Testing your Console App" section of the tutorial "Getting started with .NET Core on Windows/Linux/macOS using the command line":
... and errors like this in the Output window:
Package xunit.assert 2.1.0 is not compatible with netcoreapp1.0 (.NETCoreApp,Version=v1.0). Package xunit.assert 2.1.0 supports:
- dotnet (.NETPlatform,Version=v5.0)
- portable-net45+win8+wp8+wpa81 (.NETPortable,Version=v0.0,Profile=Profile259)
So I tried to look for the purpose of this "imports".
I found the docs for project.json but I do not understand what it is trying to say.
Will cause other packages targeting portable-net45+win8 to be usable when targeting netcoreapp1.0 with the current project.What does that mean?
Then I tried to google for using this:
more explanation of "imports": "portable-net45+win8"Google shows only one result which came from StackOverflow which led me to an article from the EF docs. It says this regarding EF:
Some of EF Core’s dependencies do not support .NET Standard yet. EF Core in .NET Standard and .NET Core projects may require adding “imports” to project.json as a temporary workaround.That is a much better explanation! Even though I do not know what PCL is :) .
The workaround is to manually import the portable profile “portable-net451+win8”. This forces NuGet to treat this binaries that match this profile as a compatible framework with .NET Standard, even though they are not. Although “portable-net451+win8” is not 100% compatible with .NET Standard, it is compatible enough for the transition from PCL to .NET Standard. Imports can be removed when EF’s dependencies eventually upgrade to .NET Standard.
Happy coding!
Sunday, July 10, 2016
My first graph problem solved: "10928 - My Dear Neighbours"
[UPDATE (July 27, 2016): I remember that this is not really the first graph problem I solved. It is, rather, the first graph problem on UVA Online Judge that I solved. I was already able to solve a graph problem when I took the free Stanford course named CS106B last 2011. But I already forgot how I solved it.]
I am so excited!!!
I solved my first graph related problem: the UVA Online Judge's problem #10928 "My Dear Neighbours".
This might just be a very simple problem but at least I am able to get started with solving graph problems.
Here is my solution:
My actual solution is actually here.
Happy coding!!!
I am so excited!!!
I solved my first graph related problem: the UVA Online Judge's problem #10928 "My Dear Neighbours".
This might just be a very simple problem but at least I am able to get started with solving graph problems.
![]() |
| Picture taken from http://uhunt.felix-halim.net/ |
Here is my solution:
My actual solution is actually here.
Happy coding!!!
Sunday, May 1, 2016
What does laptop repair shops mean by "replacement" battery?
(I believe na may kulang sa info na ibinibigay ng SST Laptop about sa ibinibenta nilang battery. Wala akong balak na siraan ang SST Laptop. Parang constructive criticism lang ito. Gusto ko lang sanang next time ay i-explain nila nang mabuti kung ano ang ibig sabihin ng "replacement" -- na yung "replacement" battery ay hindi talaga galing sa manufacturer ng laptop, para ma-weight ng customer kung bibili ba siya o hindi :) )
Last April 1, 2016, pumunta ako sa SM City (Ecoland, Davao) branch ng SST Laptop para mag-tanong kung dumating na ba yung inorder kong Toshiba laptop battery.
Sabi nung nagbabantay doon ay dumating na daw. Dalhin ko na lang daw yung laptop ko para ma-test yung battery.
So umalis ako at kinuha ko yung laptop ko.
Pagbalik ko sa shop nila, kinuha na niya yung battery. Nang nakita ko ang battery na-disappoint ako dahil hindi pala galing sa Toshiba yung battery.
Nagreklamo ako kung bakit hindi galing sa Toshiba yung battery. Sabi nung nagbabantay ay "replacement" lang daw itong battery so hindi talaga katulad ng original.
Ito yung picture ng original (nasa itaas) at nung "replacement" (nasa ibaba):
At ito yung picture ng resibo para naman hindi sasabihin ng mga nagbabasa na nagsisinungaling ako:
Gusto ko sanang hindi na lang itutuloy yung pag-purchase. Pero dahil may 6 months warranty naman daw e sabi ko na lang sa sarili ko na titingnan ko na lang kung ok ba ang performance ng battery.
So dinala ko na lang yung battery.
Sa first 3 days, palaging 100% yung battery status na nirereport sa screen ko kahit sobra ng 30 minutes nang hindi naka-charge.
Plano ko sana na ito yung gagamitin kong dahilan para ibalik ang battery at makuha ko yung ibinayad ko.
Pero dahil nawala naman after 3 days e binalewala ko na.
Pero hindi umaabot ng 4 hours or 3 hours yung battery ay nade-drain na. Parang 1.5 hours lang yata drained na.
Yun lang :)
I just hope hindi makakasira nga laptop itong battery na nabili ko. hehe
Ang nirereklamo ko lang ay yung pag-gamit ng term na "replacement. "Replacement" din yung ginamit na term noong time na nag-order ako about a month before dumating yung order ko. Akala ko naman yung meaning ng "replacement" ay "tulad ng original".
Gusto ko lang sanang magrequest sa mga laptop repair shops na i-explain na hindi talaga galing sa manufacturer ng laptop ang "replacement" battery na ipinagbibili nila para makapag-decide nang maayos ang customer. :)
Update:
Last April 1, 2016, pumunta ako sa SM City (Ecoland, Davao) branch ng SST Laptop para mag-tanong kung dumating na ba yung inorder kong Toshiba laptop battery.
Sabi nung nagbabantay doon ay dumating na daw. Dalhin ko na lang daw yung laptop ko para ma-test yung battery.
So umalis ako at kinuha ko yung laptop ko.
Pagbalik ko sa shop nila, kinuha na niya yung battery. Nang nakita ko ang battery na-disappoint ako dahil hindi pala galing sa Toshiba yung battery.
Nagreklamo ako kung bakit hindi galing sa Toshiba yung battery. Sabi nung nagbabantay ay "replacement" lang daw itong battery so hindi talaga katulad ng original.
Ito yung picture ng original (nasa itaas) at nung "replacement" (nasa ibaba):
At ito yung picture ng resibo para naman hindi sasabihin ng mga nagbabasa na nagsisinungaling ako:
Tapos nung nilagay na yung battery sa laptop, hindi fit, medyo maluwang. Parang nagba-bounce-bounce.
Gusto ko sanang hindi na lang itutuloy yung pag-purchase. Pero dahil may 6 months warranty naman daw e sabi ko na lang sa sarili ko na titingnan ko na lang kung ok ba ang performance ng battery.
So dinala ko na lang yung battery.
Sa first 3 days, palaging 100% yung battery status na nirereport sa screen ko kahit sobra ng 30 minutes nang hindi naka-charge.
Plano ko sana na ito yung gagamitin kong dahilan para ibalik ang battery at makuha ko yung ibinayad ko.
Pero dahil nawala naman after 3 days e binalewala ko na.
Pero hindi umaabot ng 4 hours or 3 hours yung battery ay nade-drain na. Parang 1.5 hours lang yata drained na.
Yun lang :)
I just hope hindi makakasira nga laptop itong battery na nabili ko. hehe
Ang nirereklamo ko lang ay yung pag-gamit ng term na "replacement. "Replacement" din yung ginamit na term noong time na nag-order ako about a month before dumating yung order ko. Akala ko naman yung meaning ng "replacement" ay "tulad ng original".
Gusto ko lang sanang magrequest sa mga laptop repair shops na i-explain na hindi talaga galing sa manufacturer ng laptop ang "replacement" battery na ipinagbibili nila para makapag-decide nang maayos ang customer. :)
Thank you!
I hope hindi kayo magagalit :)
Isinulat ko lang ito para kung sakaling itong battery ang magiging dahilan ng pagkasira ng laptop ko tulad ng nasa mga picture sa article na "Danger: Why You Shouldn’t Buy Cheap Third-Party Batteries For Laptops or Smartphones" ay may masisisi ako hahahaha.
I hope hindi kayo magagalit :)
Isinulat ko lang ito para kung sakaling itong battery ang magiging dahilan ng pagkasira ng laptop ko tulad ng nasa mga picture sa article na "Danger: Why You Shouldn’t Buy Cheap Third-Party Batteries For Laptops or Smartphones" ay may masisisi ako hahahaha.
Update:
Well, mabilis umiinit yung battery. After a few months, bigla na lang namamatay yung fan ng laptop ko, at of course bigla din namamatay yung laptop.. tapos napansin ko may bukol yung battery. Pina-tingnan namin sa technician. Sabi ng technician, sira yung board. :(
Sunday, April 17, 2016
My first TDD Kata - String Calculator in C#
I heard about TDD a few years ago but I only appreciated its value after reading some of Robert Martin's blog posts in the past few weeks (and also after having experienced writing post-development unit tests at work).
So today I decided to start doing katas for TDD...
This is my first TDD Kata: https://github.com/jboyflaga2/ProgrammingExercises-CSharp/tree/master/TDDKatas/StringCalculator
There are some things in the specs that I did not include in the implementation. I will just do them next time (really?!).
I found the "specs" for this kata in "Learning Test Driven Development with TDD Katas" by Gaurav Kumar Arora. (But the original author of this kata is Roy Osherove)
This is written in C#.
I used Visual Studio 2015 Community Edition to create a .NET Core project for this kata.
I first planned to use just the Visual Studio Code text editor for this but I was having an error with restoring xUnit. The error was "The dependency xunit.abstractions 2.0.0 does not support framework dnxcore".
I hope this error will be fixed soon.
Let's all learn TDD!!! Happy coding!
So today I decided to start doing katas for TDD...
This is my first TDD Kata: https://github.com/jboyflaga2/ProgrammingExercises-CSharp/tree/master/TDDKatas/StringCalculator
There are some things in the specs that I did not include in the implementation. I will just do them next time (really?!).
I found the "specs" for this kata in "Learning Test Driven Development with TDD Katas" by Gaurav Kumar Arora. (But the original author of this kata is Roy Osherove)
This is written in C#.
I used Visual Studio 2015 Community Edition to create a .NET Core project for this kata.
I first planned to use just the Visual Studio Code text editor for this but I was having an error with restoring xUnit. The error was "The dependency xunit.abstractions 2.0.0 does not support framework dnxcore".
I hope this error will be fixed soon.
Let's all learn TDD!!! Happy coding!
Thursday, March 31, 2016
Functional Programming for the Object-Oriented Programmer: My solution to the exercises of the sample chapter I found
I read about the book "Functional Programming for the Object-Oriented Programmer" and Clojure on Uncle Bob Martin's blog.
I am interested in learning about functional programming now because Uncle Bob says in his blog that a functional programming language will be the solution of creating software for a processor with many cores.
I am so excited about learning FP and Clojure so I'm going to post my solutions to the exercises of the sample chapter of the book mentioned above.
(I omitted some parts of the questions. Please download the sample chapter if you want to see the whole questions)
Exercise 1: Given what you know now, can you define a function second that returns the second
element of a list?
(def second (fn [list] (nth list 1)))
Exercise 2: Give two implementations of third, which returns the third element of a list.
(def third (fn [list] (nth list 2)))
(def third (fn [list] (first (rest (rest list)))))
Exercise 3: Implement add-squares.
(def square (fn [n] (* n n)))
(def add-squares (fn [& list] (apply + (map square list))))
Exercise 4: The range function produces a sequence of numbers:
Using it and apply, implement a bizarre version of factorial that uses neither iteration nor recursion.
(def factorial (fn [n] (apply * (range 1 (+ n 1)))))
I did not do Excercise 5 :)
Exercise 6: Implement this function:
(prefix-of? candidate sequence): Both arguments are sequences. Returns true if the elements
in the candidate are the first elements in the sequence:
(def prefix-of?
(fn [candidate sequence]
(= candidate
(first (partition (count candidate) sequence)))))
Exercise 7: Implement this function:
(tails sequence): Returns a sequence of successively smaller subsequences of the argument.
(def tails
(fn [sequence]
(map
drop
(range 0 (+ 1 (count sequence)))
(repeat (+ 1 (count sequence)) sequence))))
Exercise 8: In the first exercise in the chapter, I asked you to complete this function:
Mag-create siya ug list with one element inside which is also a list.
(after executing it on the command line)

Ahh I was wrong... "list" is a keyword (or a name of a function)
I googled the error -- I was wrong again -- the reason is because the the literal list is being used as a function. We cannot cast a literal list (I'm not sure if that is how we call it) into a function.
I am interested in learning about functional programming now because Uncle Bob says in his blog that a functional programming language will be the solution of creating software for a processor with many cores.
I am so excited about learning FP and Clojure so I'm going to post my solutions to the exercises of the sample chapter of the book mentioned above.
(I omitted some parts of the questions. Please download the sample chapter if you want to see the whole questions)
Exercise 1: Given what you know now, can you define a function second that returns the second
element of a list?
(def second (fn [list] (nth list 1)))
Exercise 2: Give two implementations of third, which returns the third element of a list.
(def third (fn [list] (nth list 2)))
(def third (fn [list] (first (rest (rest list)))))
Exercise 3: Implement add-squares.
(def square (fn [n] (* n n)))
(def add-squares (fn [& list] (apply + (map square list))))
Exercise 4: The range function produces a sequence of numbers:
Using it and apply, implement a bizarre version of factorial that uses neither iteration nor recursion.
(def factorial (fn [n] (apply * (range 1 (+ n 1)))))
I did not do Excercise 5 :)
Exercise 6: Implement this function:
(prefix-of? candidate sequence): Both arguments are sequences. Returns true if the elements
in the candidate are the first elements in the sequence:
(def prefix-of?
(fn [candidate sequence]
(= candidate
(first (partition (count candidate) sequence)))))
Exercise 7: Implement this function:
(tails sequence): Returns a sequence of successively smaller subsequences of the argument.
(def tails
(fn [sequence]
(map
drop
(range 0 (+ 1 (count sequence)))
(repeat (+ 1 (count sequence)) sequence))))
Exercise 8: In the first exercise in the chapter, I asked you to complete this function:
Mag-create siya ug list with one element inside which is also a list.
(after executing it on the command line)
Ahh I was wrong... "list" is a keyword (or a name of a function)
I googled the error -- I was wrong again -- the reason is because the the literal list is being used as a function. We cannot cast a literal list (I'm not sure if that is how we call it) into a function.
Sunday, October 11, 2015
Frustration during college: solving programming contest problems
During first year in
college, I was picked to be part of a team to join a programming competition.
During the
competition our team was able to solve only one problem because the problems
were hard. They were very much harder that what we were used to solving at
school. The judges (or maybe one of the judges) accepted our answer as correct
even though our solution did not pass all their test cases. It only passed the
sample test case given on the problem. The formatting of our output was even
wrong.
Of course the judges
did not tell us that our solution did not pass all the test cases but I'm sure
it did not. Maybe they accepted our solution so we will not be frustrated and
will still join the programming competition the next year.
That experience made
me very interested in finding out how to solve those kinds of programming
problems.
During my search, I
found out that I need knowledge on data structures, algorithms and discrete
mathematics, among others, to be able to solve those problems.
Algorithms
was hard
So I started reading
a book on algorithms in the library. I was able to finish only a few pages.
It was hard,
especially when no one is guiding you. And I don’t have a strong background in
mathematics.
My algorithms and
discrete math classes in college were also of no help because we were still
solving simple problems in those classes. (If you want to have an idea on why
these classes didn't help, you can read this.)
But I am still thankful for the experiences of joining a programming contest because it exposed me to the hard kind of problems that computer science attempts to solve (it's okay with me for now even if I do not know how to solve them).
I was able to join
two more programming contests after the first one, but still the problems that
our team was able to solve are the simple ones -- the kind of problems called
"ad hoc" like the "3n + 1 problem".
Focused
on Business Applications
During my later
years in college, I decided that I will concentrate on studying how to create
business applications rather than solving algorithmic problems because I was
thinking that I will not be solving algorithmic problems with the kind of job
that I am expecting to have in the future.
Now that I already
have a job, I have come to enjoy John Sonmez's blog. In one of his blog posts I read
that solving programming contest problems can help enhance problem solving
skills.
John
Sonmez's blog rekindled my desire to solve algorithmic problems
So I started solving
some algorithmic problems again using the UVA Online judge. I was able
to solve some "ad hoc" problems and problems that require knowledge
on some basic data structures like the stack and queue. (See my User Statistics here)
Recently, reading
John Sonmez's blog lead me to the article "Solving Problems, Breaking it down" where I discovered Codility.com.
Codility:
FrogJmp problem
I followed his
advice on solving the problem manually and creating a set of test cases.
This is the
screenshot of my manual solution and test cases for the problem
"FrogJmp".
My solution to
"FrogJmp" can be viewed in https://codility.com/demo/results/trainingTRB9A9-Z7Z/
Codility:
TapeEquilibrium problem
"TapeEquilibrium" is actually the first problem I solved on Codility.
("FrogJmp" is the second and "PermMissingElem" the last)
First attempt: https://codility.com/demo/results/training2FDSGB-ZK7/
- Score: 50%
- some incorrect answers and time complexity is O(n^2)
Second attempt: https://codility.com/demo/results/training59H87G-5EE/
- Score: 66%
- correct answers but time complexity is still O(n^2)
Third attempt: https://codility.com/demo/results/trainingX95N7D-W2Z/
- Score: 100%
- time complexity is now O(2n) or O(n); we don't have to compute sum over and over again
Here is
the screenshot of my manual solution. Notice that I did not create test cases.
That is the reason why on my first attempt I got some incorrect answers.
Codility:
PermMissingElem problem
First
attempt: https://codility.com/demo/results/trainingNH78M7-968/
- Used C
Second
attempt: https://codility.com/demo/results/trainingSK8DBT-TK6/
- Used C# instead of C because I thought that the cause of the error is the small size of int in C… but I still get the same results -- wrong answer
Third
attempt: https://codility.com/demo/results/training54MQEW-G3C/
- I gave up with my previous method. Here, I created another array with the size of (A.Length + 2).
Some lessons learned
1. Be sure to create test cases when solving programming problems
2. Write your solution on paper first
I hope my knowledge on data structures, algorithms, and discrete mathematics will increase so that I can be able to solve the harder algorithmic problems.
Happy coding!
PS: Please pardon my
English.
Subscribe to:
Posts (Atom)














