Showing posts with label Beginner. Show all posts
Showing posts with label Beginner. Show all posts

Wednesday, October 24, 2018

Beginner's Guide: Some Useful Machine Learning Websites(Part 2)

In the previous tutorial (Part 1) I've talked about adventures-in-machine-learning.com. Today I will talk about another online resource that comes in handy when one needs to quickly implement neural network models without going through all the hassle of the theories. As a result, I recommend this AFTER you've gone through the articles in  adventures-in-machine-learning.com. So, today we're going to talk about python-programming-dot-net.

When I was doing my thesis, I at first went through the theories and step by step implementation  in adventures-in-machine-learning.com. When I had a better grasp about the topics in neural networks, I started following this website. They have tutorials on various topics. But I'm going to focus on machine learning tutorial which starts from this link.

Here the tutorial for a particular topic( i.e. regression, neural network)  spans several articles. I found the articles fun to read and the code easier to understand(since I've already studied  adventures-in-machine-learning.com ). I recommend you implement the code in your own computer/laptop as well rather than just watching the implementation in the videos. The tutorial topics are laid below in order:


  • Regression: Regression is taught in any ML course in the beginning. Many even include assignments to implement this. In my thesis I also had to use regression to figure out the relation among some variables. It also helps one to ease into ML course before moving onto more difficult topics. So definitely check it out. The vlogger notes the important points to implement this in python. So you won't miss much in the case of implementation. But I also recommend studying the theories a bit before watching the tutorial for better grasp.
https://medium.com/@amarbudhiraja/ml-101-linear-regression-tutorial-1e40e29f1934
Linear regression
  • The next topic is K-nearest neighbor starting from here. I only had to study the theory for my academic course. But you can check it out.
  • After K-nearest neighbor comes SVM. Some of my classmates had to implement this in their thesis. So you may have to as well. SVM is also given as homework/assignment in many varsities. So this series of articles may come to your aid when you are given work to do using SVM.
  • Now comes clustering. Like K-nearest neighbor, I studied the theories only so I didn't go through the articles here. I recommend you study these articles, if you have to do specific tasks in academia that requires them. 
  • After clustering comes deep learning tutorial in TensorFlow. This part has greatly helped me when I was just beginning to learn the implementation of neural network in Python. It begins with using a multi-layer neural network on MNIST data-set. The explanations of the codes are quite easy to understand and so very suitable for beginners. The second example is positive/negative sentiment analysis of text data. So there's one example with image data-set and one example with text data-set. Most of the data-sets, one deals with while learning machine learning, are either text data or image data. Short tutorials are also provided for Recurrent Neural Network( RNN)  and Convolutional Neural Network( CNN). RNN is used when the data samples are related to one another( sequential data) and CNN is used for image data-sets because of its efficient feature extracting abilities. Their implementations are given in TensorFlow. The implementation can be used for your academic or professional work with ease and understanding. I highly recommend you go through this section if you are interested in deep learning.
  • Another important section of this website is the 'Natural Language Processing' tutorials. Many CS students, taking up machine learning courses or theses, may have to study NLP and implement NLP. Here too the website has created simple yet comprehensive tutorial to learn the implementation of NLP in Python. I do recommend some prior theoretical study before diving in. The tutorial is long but it's totally worth it!! It will let you grasp the basic coding skills you need to perform NLP-related tasks with ease. Before copy-pasting the code, do go through what the article says about its code so that you don't get confused while writing down the code.
That's it for today. These are the sources that helped me most to learn about the wonderful world of deep learning. Do let me know what you think in the comment section and follow me on Google+ to get more updates in my blog.

Friday, October 12, 2018

Beginner's Guide: Some Useful Machine Learning Websites(Part 1)

I have been away for quite some time now. The reason is I was quite busy with my academic thesis and general academic pressure. Now I do feel I can regularly post in my blog.

So today's topic that I choose is Machine Learning. I have done my thesis on neural networks. There were also 2 optional courses( Machine Learning and Pattern Recognition) I undertook for better understanding machine learning as a whole. Machine learning is a hot topic of research these days. All the top varsities are doing extensive studies and research on various aspects of machine learning. Some are exploring its application in real life situations while others are delving deep into the mechanisms of the algorithms.

When I first started doing my undergraduate thesis, I hardly knew anything about machine learning. As a result I had to search through internet for websites that would easily and extensively explain the basic mechanisms of machine learning, specifically neural networks.

I found 2 sources quite helpful in understanding how machine learning works and how to implement them into python code. I was able to read research papers with greater understanding after going through the contents of these 2 websites. It also helped me in my academic studies. I will describe first one for today's post.

Adventures In Machine Learning:

I think before mindlessly coding for machine learning models, one must learn the theory to understand what one is actually coding. Adventures in machine learning is one of the best sources out there to introduce newbies to the vast world of machine learning. The articles also come with basic implementation of the theories. It helps greatly with both academic courses and thesis activities.

Some of the articles I had to study extensively are given below. They helped me build a strong basis in learning about machine learning for both my academic course and my thesis.

  • Neural Networks Tutorial – A Pathway to Deep Learning: This is the first article of this source I studied. The articles are rather large and does require quite a bit of your time and effort. For the first timers this may even seem overwhelming. So I advise you bookmark the article and read it part by part. Trying to read the whole article at once will only hurt your brain. You may feel frustrated and at the end of reading the whole article at one go you may not even learn anything. Too much information will just jumble up everything. That's why you need to read it part by part taking your time. And do read it multiple times for clear understanding. Reading it only once may not convey much information.
    So this article deals with the basics of neural networks and an example step by step implementation in python. It describes at length both the feed forward and back propagation methods with necessary theories to help with your academic studies. I found the back-propagation portion quite useful because it clarified many confusion about back-propagation algorithm when studied the academic materials. The python implementation also clears ones understanding of implementation and will help you code your first neural network model with comfort. After reading this article, if you sit to code a neural network model, you will know why you're coding, what you're coding. You won't be just blindly copy pasting stuff from github or any other sources :P
    Neural network with 1 hidden layer
    Neural Network with 1 hidden layer, 2 output and 3 input nodes

  • Stochastic Gradient Descent: This article talks about 3 types gradient descent algorithms at length. The discussion includes their characteristics and  their advantages/disadvantages. A detailed python implementation is provided to understand the algorithms step by step. These greatly helped clear many confusions I had about this seemingly difficult algorithm. I suggest you read the first article mentioned above before jumping into this article. The first article gives you an expressive idea about neural networks and this one discusses an algorithm to improve the performance of neural network.
  • NOTE: So now you may feel exhausted reading 2 previous VERY big articles. It may take some time to both finish reading them and understanding the concepts of neural networks. But I assure you it's worth it. In academia, you always have to spend time and effort on such large and detailed articles. You may want to take some time off before moving on to other articles so that the knowledge you learned here will sit with you in future. You may also want to revise them( I suggest you do) to keep the knowledge fresh in memory.
  • Improve Neural Networks: So let's dive in further into the vast world of neural networks. For beginner models you will see high performance BUT as you start learning more complex models, accuracy becomes a BIG issue. You then feel frustrated because the performance isn't improving. In most cases the reason behind low accuracy of the model for beginners can be attributed to lack of implementing some basic concepts. 2 such concepts have been included in this articles. Their definition, description and expressive implementation in python have been provided for our convenience. It also discusses about the process of choosing better variables to improve neural networks along with a step by step implementation. This article is shorter than the other 2. So hopefully, reading it won't exhaust you :p
  • Neural Networks and TensorFlow: If you read the previous 3 articles and understand them, you get a pretty good idea about various aspects of neural networks. Till now the codes are given in python without using any special library for neural network so that the readers can view the step by step implementation of neural network for better understanding. However, if you want to use neural networks in projects, assignments and thesis, coding in simple python is quite time consuming and as the size of the code grows due to the increasing complexity of the model, the chances of making mistakes increase dramatically. Hence special python libraries for using neural networks are used. One such example is TensorFlow. This article is a general, detailed and easy-to-follow guideline of using TensorFlow to implement neural nets. The number of codes becomes much smaller and easier. So this article is a must, if you wish to code neural nets for real life projects/ assignments.
  • Convolutional Neural Network in TensorFlow: The previous neural networks you learned do not perform well when you're using large 2D/3D colored image data-sets. In such a case CNN is a must. This article talks about the basic theory about CNN at length. This helped me greatly when I had to study about CNN for both my thesis and academic course. Then comes step by step detailed implementation in TensorFlow. So this article is like  a full package to know all the important things about CNN. Since this article is quite long and there are many new things to learn, I suggest divide the article and read part by part taking time and effort to better understand. Do revise the article so that you don't forget the mechanism of this wonderful neural network.
  • CNN in Keras: You have learned TensorFlow and CNN. If you understand them, this article would be a piece of cake. This is the last article from this website, I'm going to talk about. Now you may think why I should recommend you this article since this article is about implementing CNN using another python library. You may think, "isn't TensorFlow enough to implement neural networks?" My answer to your thought is: "Yes." BUT Keras implements neural networks using fewer code than TensorFlow. This come in handy when you have to make many NN models and work with them. In such a case, you may find working with TensorFlow rather annoying. In my thesis, I have to use NN for many datasets. I found Keras truly convenient. Then you may ask 'why learn TensorFlow at all?' My answer would be:'The course teacher may want you to implement something in TensorFlow because Keras might be too short and your teacher may not allow it.' In many of my academic courses, I had to implement code in C++ even though I could have easily used Java/Python. The same goes for using TensorFlow instead of Keras. Other than that you can simply jump to learning Keras. Also Keras has given code to include a diverse array of dataset in your code but in TensorFlow you have to include dataset using your own written code.

That's it for today. In the next article (Part 2) I'm going to review another of my favorite online resource regarding neural networks.

Wednesday, November 29, 2017

CodeForces: Xenia and Ringroad(339B) Solution in Java for Beginners

  Xenia and Ringroad(339B) Problem Link:

Since this is a beginner's problem, I suggest you try it out yourself first.

Java programming topics you need to have knowledge of ->

  1. Loops from geeksforgeeks
  2. Conditional operators in Java from w3resource 
.
.
.
.
.

Explanation of Solution:

After taking the necessary input in an array (the house numbers), we assign the variable result (the total time) a[0] - 1: this is the time to go to the 1st house (from house 1 to that house).

We enter a for loop now to traverse all the houses/array elements one by one. In each iteration, if the current element/house number under consideration is greater than the element before, it is in front of the previous house. In this case, we just add the difference of the house numbers.
In the 'else' case, we see the house number is less than the previous one meaning we go to that house after completing the rotation. So we apply the rotational equation n - (a[i-1] - a[i]). 
Accumulating the results like this, we get our final solution.

Wednesday, August 30, 2017

CodeForces: New Year Transportation(500 A) Solution in Java for Beginners

 New Year Transportation(500 A) Problem Link



The solution is found in the problem, so I suggest you try it by yourself.
If you need a quick reminder for while loop, check out this youtube video of newBoston.
You can find a tutorial for if-else, on this tutorialspoint page about if-else.

.
.
.
.
.

New Year Transportation(500 A) Solution Link

If you are facing problems solving this,  you can come here for the solution. So after taking the necessary input, you begin from the first index (currentIndex - set to 1). Then you enter a while loop. Here on every iteration, you check whether you've reached your destination, on which case done variable will be true. If currentIndex > destination, you'll never get to destination since you can't travel backward. In this case, you just break out of the loop. The loop will terminate once you've traversed the whole array.

Finally, you check whether done is true (you've reached your destination) or false(otherwise).


Check out my other codeforces solutions under the codeforces label.



Tuesday, August 22, 2017

Codeforces: Pangrams 520A Solution in Java

Problem link of 520A

Solution link in github

The problem is a simple one. If you learn Java Strings, it'll be a piece of cake. I suggest you try the problem yourself before proceeding. As a quick reminder, check out this short java string tutorial from tutorialspoint  as a guide to this problem.

When taking input, in line 13 I've written an extra sc.nextline(), because when taking a string input before an integer input, omitting line 13 would cause erroneous input. So line 13 works as buffer to correctly take a string input after a numerical input.

The 'frequency' integer array will count the occurrence of each character in the input string. frequency[0] refers to  the count of 'a', frequency[1] refers to  the count of 'b' and so on. For convenience I've converted the whole string into lowercase. To determine index into this array for a particular character just subtract 'a'. For example index for count of 'c' is 2. So if we encounter 'c' just subtract 'a' from 'c' to get the index 2.

Next we check for the number of elements in the frequency array that have non-zero values. If it's 26 we output 'YES', since all the characters in the alphabet are present. Otherwise print "No".

Hope you find this useful. Check out my Hackerrank Solutions in Java. Don't forget to share and follow :) 

Monday, August 21, 2017

CodeForces: Ultra Fast Mathematician-61A Solution in Java

Ultra Fast Mathematician-61A Problem Link

Solution Link in Java

The problem is a simple one. If you learn Java Strings, it'll be a piece of cake. I suggest you try the problem yourself before proceeding. As a quick reminder, check out this short java string tutorial from tutorialspoint  as a guide to this problem.

Now let's come to our solution. After taking the input, we enter a for loop with range from 0 to n-1 , where n is the length of the input string(both strings have the same length). We extract one character from each string and put them in two character variable a and b.

We now check whether they are the same character or not. If they are the same, we output 0. Otherwise, we print out 1 since a and b are not same characters.

After the loop is finished, we get the desired output binary string.

If you face any problem or have any other suggestion, feel free to post a comment.

Don't forget to share and subscribe.

Thursday, July 13, 2017

Beginners Guide: Google Ranking. Tips for Improvement In Ranking

What is Google Page Rank:

Page ranking by Google follows an algorithm called PageRank (PR). The purpose of this algorithm is to rank websites to display in Google search engine and use this resultant rank to order websites in that search engine to put the more popular pages to the front. The basics of the algorithm is to calculate the a website’s quality by determining the number of links of various other websites pointing to the website and also the quality of the aforementioned links. In simple mathematical terms, if a page provides quality content, it is considered more important to a wider population of internet users. As a result, it will get a higher number of links from other websites.
When Google first launched its search engine, this algorithm was used. It is the best-known algorithm so far, though other algorithms have been developed since that time.
If you want a comprehensive description and analysis of PR algorithm, check out the wikipedia page for Google PR.

For bloggers interested in SEO(search engine optimization), this term comes up sooner or later because they want to put their blog or website at the front pages of google or any other search engine. This blogpost discusses the factors to use this concept for one’s benefit i.e. to make one’s website rank higher in the search engine.

WHY Does Google Page Rank (For SEO) Matter:
Many believe Pagerank is dead- a propaganda spouted everywhere. This is incorrect. This is a very important algorithm that will always be used to rank websites. Many SEO practitioners don’t understand it well and may say it’s not important. But it would be wise not to pay heed to such ill advice. Many think so because Toolbar PageRank is indeed dead. So what is Toolbar PageRank? It is a webtool to determine the rank of a page by analysing search information from Google’s database.
It used to help SEO bloggers since the tool was updated several times but now according to this source, Google has now decided to remove this tool.  On their part it’s a considered as a ‘smart’ business decision to stop the manipulation of search results.
The real algorithm, however, is still running but the visual tool used by the bloggers is now taken out. Since the algorithms is running behind the curtain to influence the search results, it is still relevant for bloggers to pay attention to this, if they want to bring their pages forward in the search engine. Thus Google PageRank still matters, though we may not have a visual of the results.
What Should A Blogger Do To Improve Google Page Ranking:
  1. Post  Quality Content:  At first plan what to write and do some research. Writing relevant and informative content is the most important thing for any blogger before thinking about any other SEO strategy. Creating posts for a specific group increases the probability of increased site traffic. Try to think from a reader’s perspective. What do they want in your article? Are you, the poster, providing enough information to satisfy the need of the reader? What will the reader search about in the google search bar to get to your website? All these questions should come to your mind before heading to write a post. For example check out this blog-post (Best Programming Websites for Beginners) from A Programmer’s Experience where the article is targetting beginner programmers and their confusion about where to learn and practice programming. They wanted to see a compiled list of websites ready for them to browse through along with information to let them know what they can expect from each link. They frequently search the web for “programming websites for beginners” and such. Some may fill their posts with keywords but that will ruin the quality of the post and the popularity of the website will eventually decrease. So you must be careful of that.

  2. Frequent Update:  Many feel lazy after a while and start delaying their posts. This is a big no-no especially for the beginner bloggers. Google checks the regularity of websites. Websites that are updated regularly are considered to be more important by PageRank algorithm. Infrequent updates or posts is a leading cause for websites to slowly lose their viewership.

  3. Metadata: Metadata is the information about the page. You can see this youtube video about the definition of metadata. It is very important since search algorithms use this to analyze the popularity of search keys and relevance of pages. They can be added to titles and description. Descriptive metadata should be like an advertisement since they are shown below the link to a page in the search results. For example in the blog-post for Beginner's Guide: Discrete Mathematics And Programming Contests. A descriptive metadata has been added-“It's a Beginner's guide to discrete mathematics and its importance for and  relation to programming contest”. And this is shown in the search result in the following figure





  1. Links to Relevant Websites: If links to other websites are added, be sure the websites you are linking to are popular websites and the links work properly. These not only help the linked websites to rank better but also help you get more viewers since the PR algorithms recommend your websites to have a higher rank. But there is small but important trick here. Rather than writing “click here” or “here” or “this website”, spell out the website name or a keyword referring to that website.

  2. “Descriptive” Images:  Alt tags or alternative text descriptor are highly recommended to be used when inserting images or videos in your blog posts. This alt tags help Google to locate and rank a page which is the most important factor for any page/post. Learn more about alt tag in Accessibility’s article about Alt Tag.

  3. Social Networking:  Whenever a new post is written, share it on various social platforms. Some of the popular ones are facebook, twitter, pinterest , google+, youtube and quora. They help you get instant views. The increase in viewership will obviously be noted by the PageRank algorithm for better ranking. Also posting in these platforms, the links to your website will also increase internal count variables of the algorithms which are used to determine page ranks. They can also be used as advertising platforms.



There are so many other advice out there in the internet but these are considered to be the most important for any blogger to follow.



If you are interested in programming problem solutions, reviews of programming websites and useful articles for beginners, feel free to check out A Programmer’s Experience.





Saturday, July 1, 2017

Beginner's Guide: Discrete Mathematics And Programming Contests

As a student of CSE, one must complete a course on Discrete mathematics. Many then become confused why they should even learn this mathematical subject. Discrete mathematics is a vast topic, but here are some essential things that you should know to be able to solve programming contest problems:
  • Counting : You are going to see a lot of problems like "Count the number of ways to do X". In most of the cases, enumerating all possible ways is simply not going to work, and you are expected to use some kind of dynamic programming. To be able to solve counting problems properly, you need to have a good understanding of certain topics such as:
    • Recurrence relations : Ubiquitous in counting problems. In particular, learn to come up with recurrences for counting. Also, learn to convert recurrences of high complexity to lower complexity
    • Matrix exponentiation : In the case of recurrences that have constant coefficients, it is possible to express the final state vector as the product of the power of a matrix and the initial state vector. A good example is calculating Fibonacci numbers using matrix multiplication. This trick helps to reduce the complexity of finding Nth term of some recurrences from O(N) to O(Log N)
    • Binomial coefficient : Many counting problems with symmetries can be reduced to finding a few cases and multiplying them with some binomial coefficients. So learn to calculate these efficiently depending on the type of problem. There are different kinds of precomputations one does. Also, try to learn the properties of binomial coefficients modulo primes.
    • Pigeonhole principle : More of a proof-aid technique rather than something that you directly apply. But I have used this in cases where I was required to find two cases which share some property. Birthday attack can be thought of as the probabilistic variant of pigeonhole principle, but it is not that commonly used.
    • Inclusion–exclusion principle : How to formalise dealing with double counting. It is sometimes so much easier to double count in the beginning and use inclusion-exclusion later than to try some double counting avoiding recurrence
    • Subsets and Permutations : Learn to generate subsets of a set and permutations of a sequence. There are some counting problems where you are expected to sum up quantities over permutations or subsets. DP over subsets is something that you should learn too in this regard.
    • Indistinguishable and distinguishable objects : Learn the difference, and learn how counting changes between the two cases.
    • Lattice problems : Counting the number of ways to go between two points on a lattice with various kinds of restrictions is a very common problem. Learn the basic method, and how things like binomial coefficients and Catalan numbers appear in the solutions.
    • Counting on graphs : The questions of this type that I have seen commonly include tree DPs. Counting problems on non-tree graphs are usually hard. You see problems coming up based on Kirchhoff's theorem once in a while too.
    • Pólya enumeration theorem : I have seen this coming up in contests only a couple of times. But learn this and if something comes up, it should be easy for you.
  • Learn to work with moduli : Most of the times, you are asked to do the counting mod some big prime (most favourite is 10^9 +7). Learn to do the calculations without overflow, and learn some basic properties of primes from group theory which help solve some problems.
  • Probability and Expectation value : Here are the basic things you should know:
    • Calculating probabilities as ratios of counting problems : Do this and you can calculate things to very good accuracy
    • Recurrences for probabilities and expectation values : In a lot of cases, even when you can count and take ratios to get probabilities, it is much easier to find a recurrence directly in terms of probabilities. Taking care of double counting can be a pain though
    • Linearity of expectation value : Learn to use it right (I can't) and many expectation value problems should be cakewalks for you
    • Random walk : Modified random walk problems come up very often as probability/expectation value problems, so learn the basic results
    • Coin toss problems : Another set of practically overused problems

Wednesday, June 28, 2017

Is The Graph Connected or Not? (Implementation of BFS)

Today we are going to solve a very important problem of graph theory. It is to determine whether a given graph is connected or not. We use a very popular and important algorithm to solve this challenge called BFS(Breadth First Search) 

Problem Statement:

Given a graph with V nodes and E edges, we must find out whether it is connected or not.
From wikipedia: "A graph is connected when there is a path between every pair of vertices. In a connected graph, there are no unreachable vertices. A graph that is not connected is disconnected. A graph G is said to be disconnected if there exist two nodes in G such that no path in G has those nodes as endpoints."

Link To a Broader Description of Graph Connectivity

If you feel more comfortable learning the concept from a video, you can watch this youtube video:

BFS:

In order to solve this problem, we use BFS (Breadth First Search) algorithm. BFS is one of the most important and basic algorithms in graph theory.


You can also watch this youtube video to understand the graph path finding algorithm more clearly.


I will take help of  the Java code for BFS provided in geeksforgeeks.com. You can see the code in their website in this link.

I hope you clearly understand graph connectivity and BFS algorithm now. If you do, we can proceed to the solution building section.

Solution Approach:


If the graph is connected, BFS will traverse the whole graph i.e. all the nodes in a graph will be visited. But what if we encounter a disconnected graph. Suppose we have a graph of 5 vertices numbered 1,2,3,4,5. We suppose 1,2 and 3 are connected (component no. 1) and 4 and 5 are connected (component no. 2). The 2 components are disconnected. In this case, if the BFS starts from 1/2/3 it'll only traverse component 1 and if   the BFS starts from 4/5 it'll only traverse component 2. 
So in the algorithm to determine connectivity, we traverse all the nodes in a loop and start BFS every time we find a non-visited node. This ensures we can reach all the components. Also starting BFS from every non-visited node in the loop means, we have encountered a new component. 


In the code n is the number of vertices while m is the number of edges. The next m lines consists of u and v - the 2 vertices of edge (the edges are bidirectional here.). Vertices are number from 1 to n here.

Then we call the BFS function to determine the number of components / clusters. Here we have for loop from 1 to n referring to all the vertices. If we find a non-visited node , we have reached a new cluster and so we increment clusterNumber (number of components). This variable is returned to main and it's determined if it is equal to 1 or not. If it is 1, we have only one component meaning the graph is connected , otherwise, disconnected.



Monday, June 26, 2017

Java Game: Console Based Choice Game for Beginner

As a CSE, we had to do a homework of making a console based text game. So I made this game.

You need to learn Java if-else and loops to make this game. Here are some tutorials for that

If - else statement:

loop:



Game Description:



You are a person that has taken up an adventure beset with monsters. There are 4 types of monsters here: Skeleton, Zombie, Assassin and Warrior. At each turn you'll face a monster. When facing them , you can attack (you'll receive damage as retribution), you can run away from that monster or you can drink potion. If your health reaches below 1 (from 100) , the game is over. After defeating each monster, you may get a bonus health potion. Finally you have the choice to continue further into the adventure or leave (quit ) the game.

Project Link

Code Explanation:

Variables:

At first, we initialize the necessary variables, a string array (enemies) naming the enemies, enemyAttackDamage( the damage enemies causes the player), maxEnemyHealth( maximum health the enemy can have initially). For the player we have, health(initial health), attackDamage(the damage the player causes to the enemy), numHealthPotion (number of health potions to use), healthPotionAmount( how much a potion can recover the health) , healthPotionDropChance( used to determine the probability whether the player will get an extra potion after defeating an enemy. More on this later)

Main Loop:

1. We choose the enemy health randomly by using maxEnemyHealth
2. Similarly, we choose an enemy from the 'enemies' array randomly

Now the gaming loop begins and it'll continue until either the player or the enemy is defeated. After printing out the health status, the game offers 3 choices for the player to choose: 
1.Attack
2.Drink Potion
3.Run 


After taking the player's input from the console, if the player chooses option 1 we calculate damageDealt(the damage the player did to the enemy) by randomly picking a number by using attackDamage .Similarly, damageTaken is calculated from enemyAttackDamage. damageDealt is subtracted from enemyHealth and damageTaken is subtracted from health. 

Now if health is less than 1, the game is over and the gaming loop will break.

If option 2 is chosen, we check whether there is any potion left. If there is, we check whether the health is 100 in which case no potion is taken. Otherwise, healthPotionAmount is added to health while numHealthPotion is decremented. If there were no potion left, output the message to the console.

If we choose to run away(option 3), we just jump to the GAME label before the while(running) line to start with a new enemy through the 'continue GAME;' statement.

After Defeating an Enemy:

After the enemy health is less than 1, the gaming loop stops. Now the probability for getting a new potion is calculated. We choose a random number within 100 and if it is less than healthPotionDropChance , the player gets a new potion. if healthPotionDropChance's value is decreased , the probability for getting a new potion is also decreased.

The player is presented with 2 options, he/she can continue or quit. We take input from console and if the player decides to quit, we just break from the main loop.

Remarks:

This is a great practice to learn if-else and loops. :)



















Sunday, June 25, 2017

Beginners' Confusion: Why Should I Learn C++?



1. Games:
C++ overrides the complexities of 3D games, optimizes resource management and facilitates multiplayer with networking. The language is extremely fast, allows procedural programming for CPU intensive functions and provides greater control over hardware, because of which it has been widely used in the development of gaming engines. For instance, the science fiction game Doom 3 is cited as an example of a game that used C++ well and the Unreal Engine, a suite of game development tools, is written in C++.
2. Graphics User Interface (GUI) based applications:
Many highly used applications, such as Image Ready, Adobe Premier, Photoshop and Illustrator, are scripted in C++.
3. Web Browsers:
With the introduction of specialized languages such as PHP and Java, the adoption of C++ is limited for scripting of websites and web applications. However, where speed and reliability are required, C++ is still preferred. For instance, a part of Google’s back-end is coded in C++, and the rendering engine of a few open source projects, such as web browser Mozilla Firefox and email client Mozilla Thunderbird, is also scripted in this programming language.
4. Advance Computations and Graphics:
C++ provides the means for building applications requiring real-time physical simulations, high-performance image processing, and mobile sensor applications. Maya 3D software, used for integrated 3D modeling, visual effects and animation, is coded in C++.
5. Database Software:
C++ and C have been used for scripting MySQL, one of the most popular database management software. The software forms the backbone of a variety of database-based enterprises, such as Google, Wikipedia, Yahoo, and YouTube etc.
6. Operating Systems:
C++ forms an integral part of many of the prevalent operating systems including Apple’s OS X and various versions of Microsoft Windows, and the erstwhile Symbian mobile OS.
7. Enterprise Software:
C++ finds a purpose in banking and trading enterprise applications, such as those deployed by Bloomberg and Reuters. It is also used in the development of advanced software, such as flight simulators and radar processing.
8. Medical and Engineering Applications:
Many advanced medical pieces of equipment, such as MRI machines, use C++ language for scripting their software. It is also part of engineering applications, such as high-end CAD/CAM systems.
9. Compilers:
A host of compilers including Apple C++, Bloodshed Dev-C++, Clang C++ and MinGW make use of C++ language.

Tuesday, June 20, 2017

Hackerrank Solution: Repeated String

Problem Link

Solution Link

Explanation:

This is a simple string manipulation problem. At first, we count the number of a's in the given string and the number is saved in countA variable. We just subtract the number of non- a characters from the string length to find that out. Since we are taking an-length part from an infinite-repeating string, the n-long part will have several occurrences of string s. The variable chunk determines the number of occurrences. So chunk*countA represents the number of a's in chunk number of s strings. We may have a remainder string portion for which we used a separate for loop to count the number of a's there. Last we print out the result.
Runtime: O(n) We used a single loop.

Note: Here n is long type variable because of the constraint 1<=n<=10^12. In Java integer range is -2,147,483,648 to 2,147,483, 647    .And  the range for long is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

so we have chosen a long type variable for n.

You can learn more about Java's variable type ranges from this article by cs-fundamentals.



Monday, June 19, 2017

Beginner's guide: Best Programming Websites for a Novice

There are tons of websites that cater to learning and practicing programming. While some are suitable for beginners, many others are for a bit mature programmers. Here is a list that I use. I recommend these websites to beginner programmers. These are fun, good-looking websites and It won't disappoint you when it comes to guiding you to learn to programme better.


Hackerrank.com :    I have already written a review about this great and fun website in another blog post. Check it out   http://aprogrammersexperience.blogspot.com/2017/05/review-hackerrank-1-great-site-for.html

codeforces.com: It regularly arranges contests where the problems are set by gradual difficulty levels. The problems are later stored in an archive along with their discussions. This is a great website for those who have already learnt the syntax of C, C++ and Java.

codechef.com :   It is also like codeforces with a cute looking interface. But here, the problems come along with subtasks. It means you will receive partial points if the solution passes some of the test cases. This feature is absent in codeforces.com. So I recommend trying out codechef first before proceeding to codeforces.

devskill.com :   This is similar to codeforces but the problems are a little bit easier.

hackerearth.com : This is an interesting website. It has the features of codechef. It also has a fun challenging arena where you duel with another programmer to solve problems as quickly as possible. It regularly arranges various hackathons and idea competitions too. Competing in these hackathons/idea competitions will really broaden your coding horizon.

geeksforgeeks.com: This is not a website for competitions. It is about teaching you about algorithms and their solutions. It is a great guide for your algorithm courses. It explains the solutions of many important, easy and hard algorithms.

tutorialspoint.com: This is a great website to learn a language quickly. They provide numerous examples when explaining an aspect of a programming language. It is your one-stop whenever you need to know something about a programming language. Whenever I find myself confused about syntax or can't remember the syntax I just search through the extensive examples of this website and I am sure to find my answer explained in an easy way.




Saturday, June 17, 2017

Beginner's Guide: Best Programming Languages

As a student who is studying C.S(Computer Science), he/she wants to optimize the usage of his/her time learning the most useful/popular programming languages. I will share my advice in this regard.

C and C++

When you first begin programming, it is recommended to learn how logic works behind coding to solve problems and such. C and C++ are the first 2 languages to learn to build a strong basis of logic and coding. While C is needed to practice the skill of logical thinking at the most basic level, C++ gives you the basic idea of Object Oriented Programming (OOP). In many other high-level languages you have inbuilt functions for many activities but in C you may have to build it yourself. Though this may irritate you sometimes, you will also build a strong knowledge about the logic behind the functions. I have written a separate blog post about the importance of learning C++.

Java

After learning C and C++, you have the knowledge about logic and OOP. As a result learning Java won't be too difficult. Using Java you'll find it easier to write solutions to algorithmic problems since you have a basic grasp of logic learning C and also you can make beautiful and useful projects for your college/university with the OOP knowledge of C++. Java gives you the opportunity to learn the basics of building various programming projects involving database, GUI etc.

Python

Currently, python is a widely used, especially in machine learning and data analytics. It's an easy-to-handle high-level language with the benefits of OOP. Many things which were hard to do in C, C++ and Java have become easier with the emergence of Python. You can also use Django to build projects with more comfort than PHP. As a result, Django is slowly taking over PHP regarding the development of backends of website building.
Here is a link to learn more about python's usefulness: Why Learn Python

HTML & CSS

These are the 2 languages that form the basis of making the front end of many projects as well as creating beautiful websites. The other ones mentioned above don't really provide such comfortable tools as these 2 to design GUI, interface , user-control etc. for your projects. While HTML builds the backbone / basic structure of the interface, CSS beautifies it.

Javascript

JavaScript is very easy to learn. No setup is required. JavaScript is used in web browser (Angular, React) and server-side (Node). JavaScript dominates in web development because it’s the native language of the web browser. Node is super popular. There are over 30,000 NPM packages available! There are lots of high-paying jobs for JavaScript developers. There are lots and lots of JavaScript job postings. And all of them are related to front-end web development or Node. JavaScript is an incredibly expressive and powerful language.


If you complete learning these languages, you don't need to worry about building a career in CS. Even if you have to learn new languages, the knowledge you have earned won't cause much difficulty.





Thursday, June 15, 2017

Hackerrank Solution: Sock Merchant (a more optimal solution)


Problem Link 

Solution Link

Link to previous less efficient solution

Algorithm : linear array mapping

Explanation:
It is a programming problem for beginners. The problem is about array manipulation. In many array related programming problems array mapping of integers is used to keep track of the frequencies of the elements in the array of a test case. This helps reduce runtime like it does for the current challenge. In many problems of character arrays, this technique is also used to keep keep track of the frequencies of alphabets.

In this problem the range of element value is from 1 to 100. So we initialized a frequency array of 100 elements with 0 because we have not counted any element yet.

Then we traverse the given array and use the elements as indices in frequency array. We increment an element in the frequency array using the elements as indices until we reach the end of given array.
So now the frequency array holds the information of the number of distinct values in the given array.
Next we traverse the whole frequency array and if it is not 0 (the index is present as an element in the given array) we divide the value by 2 to determine the number of pairs of that value and add it to our answer.

Runtime : O(n) (due to traversing a one-dimensional array)
Required Space : O(n) (Using one dimension array)

Hackerrank Solution: Sock Merchant in Java for Beginners



Problem Link 

Solution Link

Algorithm : Brute Force

Explanation:
It is a programming problem for beginners. The problem is about array manipulation. I have used a nested  for  loop to compare every possible pair. If they have the same value they are assigned -1 and the count is incremented. Here of course, you need to check whether any element is -1 before comparing for equality, otherwise, if both are -1, the count variable will be incremented.

Runtime : O(n^2) (due to the second order nested for loop)
Required Space : O(n) (Using one dimension array)

NOTE: I will try to post a more efficient solution with less run-time in near future.

Sunday, June 11, 2017

Hackerrank Solution

Problem Link: The Hurdle Race

Solution Link: Here

This is a very easy problem. You just need to find the maximum height and subtract from it 'k'. This result shows the minimum beverages you need. But if the maximum is less than k: congratulations!!! you don't need any beverages.
Solution of : Viral Advertising(problem link)

solution link

At first we initialize three variables m, liked and total with values 5,2(floor(5/2)) ,2 respectively. Here m is the total number of people.  As you can see this simulates the first day.
So the loop must simulate from the 2nd day to nth day. Hence it is initialized with i=2.
Each iteration simulates a day. At first we calculate the total number of people exposed to advertisement i.e. m = liked*3;
next we divide the value of m by 2 to get the number of people that liked the
ad. This is equivalent to floor(x/2). The result is then added to the total number of likes.

After getting out of the loop we just print the total as desired. :)
#HappyCoding




Interview Questions at Enosis(Part 3)

In Part 2 , I have discussed 3 coding problems out of 6. Here we will talk about the next 3 coding problems. Problem 4: Write a function...