<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ankur Ingale on Medium]]></title>
        <description><![CDATA[Stories by Ankur Ingale on Medium]]></description>
        <link>https://medium.com/@ingaleankur10?source=rss-f83f92aab877------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UyeM5nlqbO_TRP8bkXY4WA.png</url>
            <title>Stories by Ankur Ingale on Medium</title>
            <link>https://medium.com/@ingaleankur10?source=rss-f83f92aab877------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 12:29:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ingaleankur10/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Legendary Myths Of IITs]]></title>
            <link>https://medium.com/@ingaleankur10/the-legendary-myths-of-iits-4c04ba3d2366?source=rss-f83f92aab877------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c04ba3d2366</guid>
            <category><![CDATA[truth]]></category>
            <category><![CDATA[iit]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[myths]]></category>
            <category><![CDATA[medium]]></category>
            <dc:creator><![CDATA[Ankur Ingale]]></dc:creator>
            <pubDate>Sat, 15 Dec 2018 14:06:29 GMT</pubDate>
            <atom:updated>2019-01-15T10:13:18.387Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Know the truth about IITs.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JaDJnW9AKWyEgRGsBHWdGA.jpeg" /><figcaption>Let’s demystify!</figcaption></figure><p>Long time no see!</p><p>Recently, I watched a video(link <a href="https://www.youtube.com/watch?v=Ag9xvij2HxQ&amp;t=161s">here</a>) on YouTube starring Kalpit Veerwal, Jee Mains Topper in 2017 and currently studying in IIT Bombay Computer Science and Engineering(obviously), wherein he have kinda revealed all the salaries and packages that people get in IIT Bombay and spoke against the myths outsiders, like coaching classes and media, spread among the aspirants and their parents.</p><p>Being an IITian myself, I felt this is a major issue as many parents after hearing these big number salaries, force their students into JEE coaching and expect the same from them. I am not trying to demotivate you guys. IITs are awesome! But their images are unclear to the people, especially the JEE aspirants, and it needs to be clear for them to take the right step.</p><p>Aeeeee! Enough of this boring lecture! Let’s dive into it:</p><h4>Myth 1: Getting into IIT is an achievement. Life is set.</h4><p>Indeed, it is an achievement. But is your life ‘set’? I don’t think so. IIT is a place where all school and college toppers, extraordinary or “out-of-the-box” thinkers and very, very hardworking students come and compete against each other in various different fields. In short, it’s just getting started now. The real fun begins once you enter. (smiling from a distance :-))</p><h4>Myth 2: You will get world class professors who will teach really well.</h4><p>Not at all! Just go and ask any IITian you know. The teachers might be the geniuses in their fields. But most of them don’t know the art of teaching. They enter the class, blabber shit and leave the class. That’s why lecture halls are much more effective than a lullaby. But it’s not always true. Some professors are excellent teachers and some may not be good at teaching, but still are good mentors/advisors. But overall, I would say a big NO!</p><h4>Myth 3: Everyone is placed with a salary of 30 lakh per annum and above.</h4><p>Media plays a big role in spreading such rumors. Examples: IITians get 1 cr plus salaries; average salaries exceed 50 lpa, etc. But I still couldn’t figure out the source of their information (guess its ‘SUTRON KE ANUSAAR’- according to the sources).</p><p>Reality is just the opposite. There will be at max 1–2 students out of the entire graduating batch who will get offers of 1 crore or equivalent. And those guys are exceptional in their skills and performance. For the remaining, an average salary is around 20–25 lpa. But let me remind you, not everyone gets placed. Only around 70% of students get placed, with some accepting offers as low as 4 lpa.</p><h4>Myth 4: You will get a good hostel with well-furnished rooms, coolers/ACs</h4><p>Just a FAN, nothing more than that. The rooms are not that good, especially in the old hostels of the old IITs. A cheap table, a plastic chair which you see in almost every party, one small almirah and a bookshelf. That’s it. Summers are horrible in such rooms but we don’t have a choice. But you will eventually love your room no matter what! And this can’t be explained; for that, you have to be there in that room :)</p><h4>Myth 5: You will become a good ‘X’ engineer if your branch is ‘X’ engineering.</h4><p>Firstly, many people go for non-core jobs. Meaning, they work in some field other than the degree which they pursued. Like a chemical guy in software development. Secondly, even if your branch is one of the topmost branches in your IIT, so are the others in that branch. The competition is at a much higher level and you just have to keep running. You will learn the hard truth about Indian Education System and life in general:</p><blockquote>Sab moh maya hai. <em>Everything is a SCAM</em></blockquote><h4>Myth 6: You will never drink/smoke in IIT life. Not even once.</h4><p>Parents should take a note of this. Almost everyone does it. I don’t have numbers with me but it will be around 70–80% of the campus or even more. Drinking is natural here(I haven’t done it yet… so don’t judge me). But what worries me and parents should worry about is smoking and drugs. Although very few people do it (still a lot in such big campuses), chances of their life being ruined are very high.</p><h4>Myth 7: You are an IITian, you must have everything sorted out in life.</h4><p>This time, you have to read the news. Almost every IIT, especially “TOP” IITs, have 1–2 suicides per year. What do you think shall be the reason for their suicides if everything is sorted? Lack of counseling, peer pressure, not getting an intern, not getting placed, and several other reasons keep haunting us day and night. Yes, depression exists. Suicides happen. Many can’t figure out what they want from life till their final years. This is a bitter truth of IITs with everyone from professors to parents and friends play the role.</p><p>That was sad. Wait, demotivated already? No worries! IITs still have a lot of things that make your 4 years worth it.</p><ol><li>Outstanding facilities like the computer center, central library, sports, and other buildings.</li><li>Various clubs which organize various events. Just join them and learn something new apart from your academics.</li><li>College fests are the best. Just imagine Mood Indigo in almost every IIT! Yaay!! The better part is being in the organizing committee of these fests.</li><li>Inter-hostel competitions wherein the entire hostel unite and show their legacy to the other hostels.</li><li>Inter-IIT wherein you showcase your skills against other IITs as well.</li></ol><p>To conclude, IITs are awesome. But my motive was to bring out the correct news about IITs to the JEE aspirants and also to the parents who want their child to be an IITian just for the sake of a big number salary.</p><p>If you are interested to read more of such demystification, click <a href="https://www.quora.com/What-are-the-myths-and-realities-of-IITs">here</a>. Thank you, <a href="https://medium.com/u/3853f85f7d5e">Quora</a> for such beautiful answers :-P. Make sure you hit that clap button 50 times if you loved this blog.</p><p>Until next time…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c04ba3d2366" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make Simple Game Series: MineSweeper]]></title>
            <link>https://medium.com/@ingaleankur10/make-simple-game-series-minesweeper-55e8cfc096a9?source=rss-f83f92aab877------2</link>
            <guid isPermaLink="false">https://medium.com/p/55e8cfc096a9</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[Ankur Ingale]]></dc:creator>
            <pubDate>Thu, 23 Aug 2018 03:52:23 GMT</pubDate>
            <atom:updated>2019-01-15T10:15:27.991Z</atom:updated>
            <content:encoded><![CDATA[<h4>It’s time for some recursion!</h4><p>Hey there! It’s been a while.</p><p>In this blog, we will be learning to apply one of the most important yet interesting concepts of programming — recursion. How? By making the legendary MineSweeper game! But before we start, let me introduce you to recursion.</p><p>The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using a recursive algorithm, certain problems can be solved quite easily. For example, the following code will return the factorial of a number( factorial of a number N is N! = N x (N-1) x … x 2 x 1 , hence 5! = 5 x 4 x 3 x 2 x 1 = 120). Firstly, we will implement it using <em>for</em> loop:</p><pre>int fact(int n)<br>{<br>    int p = 1;<br>    for(int i = 1;i &lt;= n;i++)<br>        p *= i;<br>    return p;<br>}</pre><p>A similar <em>recursive </em>implementation would look like this:</p><pre>int fact(int n)<br>{<br>    if (n &lt; = 1) // base case<br>        return 1;<br>    else    <br>        return n * fact(n-1);    <br>}</pre><blockquote>Loops or iterative structures become really tedious sometimes. But recursion shortens the code and makes it as simple as possible.</blockquote><p>Like for Fibonacci series, the for loop is way too long as compared to its recursive alternative (see the difference <a href="https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/">here</a>). In this game itself, you will notice the use of recursion and be relieved from the pain of implementing the same using loops. Want to see it? Let’s start!</p><p>MineSweeper is one of the best and simplest game ever made. Almost everyone of you would have tried this once on your Windows PC (and I am sure none of you understood the game in the first try :-P). Don’t worry! I’ll give you a brief idea.</p><p>The objective of this game is to hunt down all free spaces. This can be done by not clicking on the tiles containing mines. When you click on a free space, it will either display a number informing the number of mines in its neighbourhood, or open up further free tiles if there is no mine nearby. But never make the mistake of clicking on tiles containing a mine. That’s a GAME OVER! For detailed instructions, visit <a href="http://www.freeminesweeper.org/help/minehelpinstructions.html">this</a> link.</p><p>Let’s start with the variables we need. As mentioned in my first blog, I’ll be writing the code in Java. We need a 2D board i.e. a 2D array. Next, we need a variable to keep track of the number of empty cells/spaces. Lastly, we require a variable to check if the game play is on or not.</p><p>This can be done the following way:</p><pre>int board[][];<br>int emptySpaces;<br>boolean gamePlay;</pre><pre>public void initialisor()<br>{<br>    Random r = new Random();//random number generator<br>    emptySpaces = 25; //number of empty or non-displayed cells<br>    board = new int[5][5];<br>    gamePlay = true; //if game is on or not</pre><pre>    for(int i = 0;i &lt; 5;i++)<br>    {<br>        for(int j = 0;j &lt; 5;j++)<br>        {<br>            board[i][j] = -1;<br>        }<br>    }</pre><p>Here, I made a function named initialisor() to initialise all variables. Next, we initialised all tiles -1 as a check for the free tiles. Next, we need to put 5 mines in random cells. This can be done in the following way:</p><pre>   for(int i = 0;i &lt; 5;i++)<br>   {<br>       int x,y;</pre><pre>       do{<br>           x = r.nextInt(5);<br>           y = r.nextInt(5);<br>         }<br>       while(board[x][y] == 99);</pre><pre>       board[x][y] = 99;<br>   }<br>}</pre><p>With this our function is complete. We chose one location randomly and checked the presence of mine there. If the mine is already present at that location, search for some other location. If the mine is not present at that location, put one in there. The mine is marked with number 99 .</p><blockquote>And again! Many coders use <em>if </em>instead of <em>while/do-while</em>. This is wrong as the random number generator might generate the similar pair <strong>again</strong>. The <em>while</em> loop will repeat until the generated pair is not matching the constraints of the loop. But the <em>if-</em>statement will run the code again only once. If a pair, where the mine is already present, is generated again, it will be ignored this time and the mine will be over-written with another mine. 5 mines in total but not on the board? That’s not what we want.</blockquote><p>Next, I’ll be displaying my board to the user. I’ll be making the board on the console. The following function does our job:</p><pre>public void display()<br>{<br>    System.out.println(&quot;. 0 1 2 3 4&quot;);</pre><pre>    for(int i = 0;i &lt; 5; i++)<br>    {<br>        System.out.print(i);<br>        for(int j = 0;j &lt; 5;j++)<br>        {<br>            if(board[i][j] &gt; -1 &amp;&amp; board[i][j] &lt; 9)<br>                System.out.println(&quot; &quot;+board[i][j]);<br>       <br>            else System.out.println(&quot; +&quot;);<br>        }<br>    System.out.println();<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*HO9JmKdbl8lb4JhzdmsLHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*G8dL_-dy7w44u38TD0FtlA.png" /><figcaption>Initial board and board after playing once.</figcaption></figure><p>This is how it will look like. The first println statement was to print the column numbers. Then I used a nested <em>for</em> loop to print my board. Inside the first <em>for</em> loop, I first printed the row number. Next, I checked if the cell coordinates <em>(i , j) </em>is used or not. Had it been used, the value of that cell would be in the range of 0 to 8. So is my condition in the code above. If the value is -1 or 99, keep the value hidden. That’s where the + sign is used.</p><p>Till now it’s all easy, just initialising and displaying the board. Now, let’s code the brain of the game. Time to see the magic!</p><p>We will make a new function game() wherein we will take user input and send it to another function mineCount() to count the number of mines near it and save that number in the corresponding cell. For the game() function, we need two inputs from the user — row and column. But we will do it in one input using strings. In this way, we give the user a break from hitting enter twice. Enough talking, let’s write now:</p><pre>public void game()<br>{<br>    Scanner s = new Scanner(System.in);</pre><pre>    while(gamePlay)<br>    {<br>        System.out.print(&#39;\u000C&#39;);<br>        display();</pre><pre>        int row,col;<br>        <br>        String input = s.nextLine();<br>        row = input.charAt(0) - &#39;0&#39;;<br>        col = input.charAt(1) - &#39;0&#39;;</pre><pre>        if(board[row][col] == 99){<br>            gamePlay = false;<br>            return;<br>        }</pre><pre>        mineCount(row,col);<br>        <br>        if(emptySpaces == 5)<br>        {<br>            gamePlay = false;<br>            disPlay();<br>        }<br>    }<br>}</pre><p>Remember the gamePlay variable initialised at the start? I’ll be using it here to check if the game is going on or not. This can be done using a <em>while</em> loop. Next, I cleared my screen and displayed the board. Then, I read the user input and extracted the integers from the string.</p><p>Now, we will check the user input. Did he land on a mine? If the cell corresponding to the coordinates given by user has a mine, it’s definitely a GAME OVER! So, just set gamePlay to false and terminate the function.</p><p>What if the user is safe? Give him the number of mines near that cell. The mineCount() function does that job. We haven’t seen it yet it’s the core of this game! Lastly, if the number of non-displayed cells or emptySpaces equals 5 (the number of mines), finish the game. Just to make winning different than losing, I will display the board for the last time.</p><p>Uhhh!! So much just to come here….. but remember, every movie has a climax. And here is ours….</p><p>To count the number of mines in the neighbourhood, we need to check all the cells in the neighbourhood of the given cell. But before that, we need to make sure that the current cell is unused before. Hence, let’s start by making our function and using nested <em>for</em> loops to traverse through the neighbours.</p><pre>public void mineCount(int x, int y)<br>{<br>    int i,j; //loop variables</pre><pre>    if(board[x][y]!= -1)return; //already used</pre><pre>    board[x][y] = 0;//used<br>    emptySpaces--;</pre><pre>    for (i = x-1 ;i&lt;=x+1 ; i++)<br>    {<br>        for(j = y-1 ;j&lt;=y+1 ; j++)<br>        {<br>            </pre><p>Here, the loops will start from top left cell and finish at the bottom right one, all with respect to the current cell. Also, since these two loops are independent, they will consider the current cell also (<em>i = x and j = y</em>). But that won’t matter because we know the mine is not present in the current cell. You can add this condition as a security though. Hence, what we need to code is this: if the cell at coordinates <em>(i , j) </em>has a mine, increment the value of the current cell.</p><pre>if(board[i][j] == 99)<br>{<br>    board[x][y]++;<br>}</pre><p>Here comes one sweet error! <strong>ArrayOutOfBoundsException</strong>. Why you ask? Just look at the previous piece of code. What if the current cell is at a corner or an edge? Let’s say we consider a cell at <em>(0 , 0). </em>Now, when I say i = x — 1 , it means i has a value of -1. Similarly, j is also -1. Now, the latter piece of code will check at coordinates <em>(-1 , -1), </em>which doesn’t exist! Here comes the second condition.</p><pre>if(i &gt;= 0 &amp;&amp; j &gt;= 0 &amp;&amp; i &lt; 5 &amp;&amp; j &lt; 5)<br>{<br>    if(board[i][j] == 99)<br>    {<br>        board[x][y]++;<br>    }<br>}</pre><p>This will take care of corners and edges. Now, let’s close the nested for loops. We have the number of mines in neighbourhood stored in the cell at coordinates <em>(x , y).</em> But what if there were no mines around it? Remember, we have to open it’s neighbours as well.</p><pre>}} //closing the previous loops ;-P</pre><pre>if(board[x][y] == 0)<br>{<br>    for(i = x-1 ;i &lt;= x+1 ; i++)<br>    {<br>        for(j = y-1 ;j &lt;= y+1 ; j++)<br>        {<br>            if(i&gt;=0 &amp;&amp; j&gt;=0 &amp;&amp; i&lt;5 &amp;&amp; j&lt;5)<br>                mineCount(i,j);<br>        }<br>    }<br>}</pre><p>Here, we checked if the count is 0. If true, then go through the neighbours again and count their neighbours. Wait a second! We have to count again that too for each neighbour. Plus we don’t know if a particular neighbour count becomes 0 because if it does, we need to count the number of mines for that cell’s neighbours……</p><p>Ahhhh! It seems there’s no end to it. This is where recursion comes in handy. I’ll simply pass the coordinates of each neighbour to itself which in return will do the same the process on that cell. And the condition to stop it is when you have neighbours with at least one mine or have no neighbours to open. These conditions were already applied: one for mine checking in game()function and one for positive value in mineCount()function. We don’t even have to imagine the process. Just let the function call itself.</p><p>Implementing the same just with loops will be very tedious. But I would suggest you to try it once. Lastly, just create an object of the class in the main() function and run the game() function and enjoy this masterpiece. There is another feature in MineSweeper known as <strong>flags</strong>. Meaning, if you are sure of a mine at a particular cell, you can <strong>flag </strong>that cell. But this is just for the user to remember and has no significance in the logic of the game.</p><p>As mentioned in my previous blog, I have written the code in three languages: Java, C++, and Python. You can view these programs here. Also, try adding GUI to this game or try making something like <a href="http://www.freeminesweeper.org/welcome.php">this</a>. Make sure you hit that clap button 50 times if you loved this blog.</p><p>Till then, see ya!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55e8cfc096a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Random Number Generation In Various Programming Languages]]></title>
            <link>https://medium.com/@ingaleankur10/random-number-generation-in-various-programming-languages-d4a3d8966ad1?source=rss-f83f92aab877------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4a3d8966ad1</guid>
            <category><![CDATA[randomness]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[random]]></category>
            <category><![CDATA[probabilistic-programming]]></category>
            <dc:creator><![CDATA[Ankur Ingale]]></dc:creator>
            <pubDate>Tue, 07 Aug 2018 20:15:56 GMT</pubDate>
            <atom:updated>2019-01-15T10:16:40.572Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey! I am back with another one.</p><p>This blog is a compilation for generating random numbers in my favourite programming languages. My purpose is to have a single source to learn random number generation in the programming language you are currently working on.</p><p>Random number generation is one of the most important aspects of programming. Many card games are played on luck. This luck is nothing but getting a random card. Also, random number generation has applications in statistical sampling, cryptography, gambling and much more. This is the THING which runs the entire Las Vegas!!</p><p>In programming, random number generation is mainly used in basic examples like rolling of dice, flipping of a coin or shuffling a deck of playing cards. In my previous blog I used random numbers to get 3 different colours (link <a href="https://medium.com/@ingaleankur10/make-simple-games-series-mastermind-6d857195445">here</a>).</p><p>Haaa! That’s too much of intro. Let’s begin at once….</p><h3><strong>JavaScript</strong></h3><p>JavaScript is one of the popular programming languages. JavaScript is a universal programming language which shows a great level of flexibility and performance. It is free to use, easy to learn, and easy to implement (both in web and hybrid mobile applications). All these reasons combined make it the perfect cross-platform programming language.</p><p>So how to generate random numbers in this language? The following code does it:</p><pre>var rand = Math.random();</pre><p>Here, the variable rand stores a random value between 0(inclusive) and 1(exclusive). To generate a random number between 1 to N, the following code is used:</p><pre>var rand = Math.floor(Math.random * N) + 1;</pre><p>First, we get a random fraction between 0 and 1. Then, we multiply this random fraction with the upper limit (in this case, it is N). Generated number is a product ranging between 0 and N (0 x N = 0, 1 x N = N).</p><p>Lastly, we floor it i.e. we take the closest whole number which is less than or equal to that product. This floored product is between 0 and N-1. This is because 1 is exclusive. Hence there is no way for N to be selected as a random value in our above product. Finally, the floored product is incremented by 1. The overall equation now comes in the range of 1 to N (both inclusive).</p><h3><strong>Java</strong></h3><p>Java is one of the “slowly dying” programming languages. But even today, it has many applications as compared to others. The key features of Java are speed, safety, and cross-platform applications. The main areas of Java include Android App development, Software development and much more.</p><p>Let’s see how to generate random numbers:</p><pre>double rand = Math.random();</pre><p>Same as JavaScript? The answer is ‘YES’. But is this the only way? Not at all!</p><p>The Random class in java.util package gives us everything we need. This class was implemented in my previous blog. So if you want to see a working example, read my previous blog <a href="https://medium.com/@ingaleankur10/make-simple-games-series-mastermind-6d857195445">here</a>.</p><blockquote>Note: Make sure you import this class before working on ahead.</blockquote><p>Therefore, to get a random number between 1 to N, we use the following code:</p><pre>Random rand = new Random();</pre><pre>int r1 = rand.nextInt(N) + 1;</pre><h3>C++</h3><p>Here’s the trouble! But first, let me introduce this guy.</p><p>C++ is a widely used programming language. It is basically an extension of C and includes features like object-oriented programming. It is much more difficult to learn but consequently gives the programmer more control over his code. Main applications of C++ include competitive programming, video games, and financial applications. In fact, it can be used for almost all purposes.</p><p>How to generate random numbers with C++? The following code will generate a random number between 1 to N:</p><pre>int r = rand() % N + 1;</pre><p>The function rand() returns an integer between 0 and RAND_MAX . By taking the remainder i.e modulus, we are limiting the maximum value the function can return to N-1. Finally, adding 1 to it will give us a random value between 1 to N (both inclusive).</p><p>Did you notice something in your code’s output? Is the random value or the sequence of random values generated always same? I ran the following code many times but got the same result:</p><pre>for (int i = 0; i &lt; 5; i++)<br>   cout &lt;&lt; rand() % 5 &lt;&lt; endl;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*BhYOx1D8X3PLjRlxf58-pg.png" /></figure><p>This is because we never talked about pseudo-random numbers and truly random numbers. The reason is that a random number generated from the rand() function isn’t actually random. It is simply a transformation (click <a href="https://en.wikipedia.org/wiki/Random_number_generation">here</a> to know more on pseudo-random number generation). Every time you call rand() it takes the seed or the last random number(s) generated, runs a mathematical operation on those numbers and returns the result. So if the seed state is the same each time (as it is if you don’t call srand with a truly random number), then you will always get the same ‘random’ numbers out. The following code solves it:</p><pre>#include &lt;iostream&gt;<br>#include &lt;time.h&gt;</pre><pre>using namespace std;</pre><pre>int main() {<br>   srand(time(NULL));</pre><pre>   for (int i = 0; i &lt; 5; i++) {<br>      cout &lt;&lt; rand() % 5 &lt;&lt; endl;<br>   }<br>   return 0;<br>}</pre><p>Now it’s truly random!</p><h3><strong>Python</strong></h3><p>The language of the future is here! Python is a high-level programming language which can be used as a scripting language or for object-oriented programming. Python can do anything. There are so many libraries, both built-in and third-party, which help Python do anything from as simple as writing “Hello World!” in one line to become one of the best language for implementing machine learning algorithms.</p><p>But we are here just for generating random numbers. This can be done as follows:</p><pre>import random<br>print random.randint(0, 5)</pre><p>This will output either 1, 2, 3, 4 or 5. If you want a larger number, you can multiply it. For example, a random number between 0 and 100 can be produced as follows:</p><pre>random.random() * 100</pre><p>Python also has built-in functions for getting a random choice from a list, shuffling a list, and much more.</p><pre>import random</pre><pre>myList = [2, 109, False, 10, “Lorem”, 482, “Ipsum”]</pre><pre>random.choice(myList)<br>#random element from list</pre><pre>random.shuffle(list)<br>#shuffled the list<br>#example = [109, 2, 10, “Loren”, False, “Ipsum”, 482]</pre><p>You can learn more about generating random numbers using python <a href="https://www.pythonforbeginners.com/random/how-to-use-the-random-module-in-python">here</a>.</p><h3><strong>Swift</strong></h3><p>The programming language Swift was developed by Apple to incorporate and improve many features of the programming language Objective-C. Swift is a modern language and an easy tool to use. It is the foundation of iOS development.</p><p>The following code generates random number between 0 and 10 (both inclusive):</p><pre>let number = Int.random(in: 0 … 10)</pre><p>This code will generate random numbers between 0(inclusive) and 10(exclusive):</p><pre>let number = Int.random(in: 0 ..&lt; 10)</pre><p>We also have boolean random generator in Swift. This can be implemented in the following way:</p><pre>let b = Bool.random()</pre><p>Lastly, we can also generate random fractions like this:</p><pre>let number = Float.random(in: 0 ..&lt; 1)</pre><p>Swift, like Python, also has built-in functions for returning a random element from an array or to shuffle an array:</p><pre>let names = [“Ford”, “Zaphod”, “Trillian”, “Arthur”, “Marvin”]</pre><pre>let randomName = names.randomElement()<br>//got a random element from `names`</pre><pre>names.shuffle()<br>//`names` can now be: [“Zaphod”, “Marvin”, “Arthur”, “Ford”, “Trillian”]</pre><p>You can learn more about generating random numbers using swift <a href="https://learnappmaking.com/random-numbers-swift/">here</a>.</p><h3><strong>C#</strong></h3><p>C# is very similar to Java but is much more difficult. It is one of the most advanced and convenient programming languages around. It is used to create Windows applications, XML Web services, client-server applications and database applications.</p><p>The random number generation is just like the Random class in Java. See the code below:</p><pre>Random rnd = new Random();</pre><pre>int month = rnd.Next(1, 13); // creates a number between 1 and 12</pre><pre>int dice = rnd.Next(1, 7); // creates a number between 1 and 6</pre><pre>int card = rnd.Next(52); // creates a number between 0 and 51</pre><p>That was a lot of coding. But with this blog, we were able to learn the different methods of generating random numbers in various programming languages. With this knowledge, you might even start-up your own casino in Las Vegas! Make sure you hit that clap button 50 times if you loved this blog.</p><p>Till then, see ya!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4a3d8966ad1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make Simple Games Series: MasterMind]]></title>
            <link>https://medium.com/@ingaleankur10/make-simple-games-series-mastermind-6d857195445?source=rss-f83f92aab877------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d857195445</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[logical-thinking]]></category>
            <dc:creator><![CDATA[Ankur Ingale]]></dc:creator>
            <pubDate>Tue, 31 Jul 2018 19:19:47 GMT</pubDate>
            <atom:updated>2019-01-15T10:17:03.526Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s decode the game.</h4><p>Hi!</p><p>Myself Ankur. I recently entered this world of programming. But one thing I saw while coding is that many of them know the theory but couldn’t apply those in their programs. If you are one of them, this blog series is for you.</p><p>This series basically plans to help people understand and apply logic to their code by making games. That’s right! Games! Though these games are very easy to code, it will surely help you understand logic and its application. I’ll code all my games in three different programming languages: Java, Python and C++. But as for the content, I’ll code in Java. Lastly, I will give hints for every new step that I am about to code. Let’s go!</p><p>As the title suggests, my first game would be MasterMind. The goal of the game is to find the order in which the coloured pebbles arekept, hidden from you, by judging the number of white flags (pebble present but not in the same location) and black flags (pebble present and in the same location) and predicting the next move. For detailed rules and gameplay, visit this <a href="https://www.wikihow.com/Play-Mastermind">site</a>.</p><p>First, we need to randomly select three pebbles from a list of, let’s say, seven. For simplicity, I’ll use VIBGYOR of the Rainbow (violet, indigo, blue, green, yellow, orange and red). Remember this sequence as it will be repeatedly used. So from VIBGYOR, the computer needs to select 3 colours. For this, we can do the following:</p><pre>Random random = new Random(); //for random numbers<br>Scanner s = new Scanner(System.in); //for inputs<br>char colors[] = new char[]{‘V’,’I’,’B’,’G’,’Y’,’O’,’R’};<br>char c1 = colours[random.nextInt(7)];<br>char c2 = colours[random.nextInt(7)];<br>char c3 = colours[random.nextInt(7)];</pre><p>Seems easy right! We just made an array of colours and then randomly selected three different colours. Can you spot the loophole? The main problem is colours CAN’T be repeated (that’s a rule). So we can get a sequence like “VGG” which is wrong. To solve this problem, the following code can be written:</p><pre>String compSequence=“”;</pre><pre>for(int i = 0;i &lt; 3;i++){<br>   int z;</pre><pre>   do{<br>      z = r.nextInt(7);<br>   }while(colors[z]==’_’);</pre><pre>   compSequence += colors[z];<br>   colors[z]=’_’;<br>}</pre><p>Hmm, what’s all this junk! First, we made an array of colours. Then using a <em>for </em>loop, we added the colours in our string compSequence<em>. </em>Lastly, we removed the used colours by assigning _at that index. If the colour is removed i.e. the character in the array at that index is _, then find another random index until a colour is found.</p><p>Now comes an important part! The user input. We need to take the input 10 times. Since the number of iterations is fixed, a <em>for</em> loop is preferred. Next, we need to initialise the black and white flags’ variables. This can be done as following:</p><pre>for(int i = 0; i&lt;10; i++){<br>   int black=0, white=0;</pre><p>Now we need to take user input. But what if the user accidently hits enter before typing anything. A <strong>BufferedReader</strong> would throw an error. That’s why I used a <strong>Scanner</strong> class (see the difference <a href="https://www.geeksforgeeks.org/difference-between-scanner-and-bufferreader-class-in-java/">here</a>). The following piece of code will do it:</p><pre>String input=””;</pre><pre>do{</pre><pre>   System.out.print(“Chance “+(i+1)+”: “);<br>   input = s.nextLine().toUpperCase();<br>   //s is the scanner object (see above)</pre><pre>}while(input==“” || input.length() != 3);</pre><p>Here, if no input is given or input containing number of characters NOT EQUAL TO 3 (since there are 3 colours) is given, the user is forced to retype the input. Also, we are converting the characters in the input string to upper case.</p><p>One thing to notice is that many coders use <em>if </em>instead of <em>while</em>. This is wrong as the user might commit the same mistake <strong>again</strong>. The <em>while</em> loop will repeat until the constraints are matched. But the <em>if</em> statement will ask the user to retype the input only once. If the user makes another mistake, it will be ignored. For clarification, just swap the <em>do-while</em> with an <em>if-</em>statement and make the mistake twice when the input is prompted. The images below are the respective outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*5qBBPzL-5KXtjkWCqINuyQ.png" /><figcaption>(when <strong>do-while </strong>is used)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*K3Ebk40aJO4p19Ar_VxFkA.png" /><figcaption>(when <strong>if</strong> is used)</figcaption></figure><p>Now comes the black and white flags. We need to display the number of black and white flags. But before displaying we need to count them. To do that we need to go through both the strings and compare each character of one string with that of another i.e. to check if the colours are same. If the two colours compared are same and if their indices are also same, increment number of black flags or else increment number of white flags. Look below:</p><pre>for(int j = 0;j &lt; 3;j++){<br>   for(int k=0; k &lt; 3;k++){ </pre><pre>      if(compSequence.charAt(j) == input.charAt(k)){</pre><pre>         if( j == k ) black++;<br>         else white++;<br>}}}</pre><p>We used nested <em>for</em> loops. Then we compared every character of compSequence with that of input. If same, check indices and correspondingly increment the respective flag.</p><p>Another problem is that the user may purposely give an input with repeated colours. That is fine as long as he wishes to check only two colours. But if the repeated colour is the same as one of the colours in compSequence , the black and/or white flags will add up 2 times. This is because the colours compared will be same 2 times. Can you solve this error? I’ll leave it to you.</p><p>In case you couldn’t, don’t worry. The code for resolving the above error is given in the link at the bottom.</p><p>One last thing! What if the user gets the correct string within 10 chances? That’s right! Stop the loop. This can be done by breaking the loop:</p><pre>if(black == 3)<br>   break;</pre><p>But what if he doesn’t? Then just display the black and white flags.</p><p>Note: reset black and white variables or else they’ll keep adding.</p><pre>   System.out.println(“Black pebbles: “+black+” White Pebbles: “+white);</pre><pre>   black=0;<br>   white=0;<br>}</pre><p>Woah! Such a simple game but so much to explain. But you did it! <a href="https://iitgoffice-my.sharepoint.com/:f:/g/personal/ankur170123007_iitg_ac_in/EjiabvUIW1dNgxKOzLHGxvwBr3dwnS7-D8fVrF2rON1-Cw?e=10y9uG">Here</a> is the link for complete code with errors solved. Now, play with it and send me the best clone of this game. You can also try to make something like <a href="http://www.webgamesonline.com/mastermind/">this</a>. Make sure you hit that clap button 50 times if you loved this blog.</p><p>See ya! Let us make another one soon…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d857195445" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>