Posts

Showing posts with the label problem solving

How to Solve a Problem 6: Smallest Common Multiple

 Recently, I came across this question on /r/learnprogramming Question: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? Well, how would you write a program to figure this out?  The answer is not that difficult, but it involves a lot of prime numbers.  The short version: we can "construct" the number by starting from 1 and work our way up to 20.  1 is obviously 1 2 is obviously 2 3 however, will be 6, as it needs to be divisible by 2 and 3 4 however, is NOT 24, but 12,  5 is 60 6 is 60 because 60 is already divisible by 6 7 is 420  8 is 840 (remember, factors) 9 is 2520 10 is still 2520.  Do you see a pattern?  Let's say you need to calculate smallestMultiple of X.  To get it, you need the PREVIOUS smallestMultiple. i.e. smallestMultiple(X-1). For simplicity, let's call it "prevSM" If that ...

Let's Make Dice Wars, Part 3

Image
We have previously created the skeletons of the game in part 1, and completed the game in part 2. We now add some "chrome" to the game, to make it look better, prettier, and so on.  And there are a LOT of things we can do, but we may need to rewrite a part of the program to accommodate the changes. This is normal and a part of the learning process.  Let's try making some simple changes. I am not going to show you ALL the changes as you can easily figure out the exact syntax with the steps I described. You can see the source code at the end. This is what it will look like: Change the Button Colors When you think about it, War button should be red, and maybe the reset button should be blue... and maybe rename it "Peace" as a joke?  Well, that's easy enough, with Bootstrap. btn-danger is red, and btn-primary is blue, so we just swap that around.  Keep a "log" of previous battles To clarify, we are adding ANOTHER field called "battle log" whe...

Let's Make Dice Wars, Part 2

Image
Previously, we have created a basic HTML page, with a simple dice rolling logic, and simple UI, with Bootstrap and jQuery, so we have the beginnings of a web-based version of Dice Wars.  In this part, we will complete the "game", where you roll the dice for two players, determine who won, adjust scores accordingly, and declare winner or loser after X points. There will also need to be a "reset" button so we can start again.  You will learn in this segment: Very simple Bootstrap grid layout, centering, and so on Simple DOM manipulation with jQuery on multiple DOM elements How to write JavaScript function with parameters so it can be reused How to write make one function call another function Create a properly working, if simple, game We will set the starting points to 5, and first player to hit 0 is the loser, and the other is the winner. Keep in mind later, we may want this to be variable so we can setup variants of the game.  Setup Two Players Right now, let's ...

Let's Make Dice Wars: Part 1

Image
Creating a project is not easy, but it is essential to demonstrate your worth as a developer. Mainly for grins, I'll start a simple project, and keep adding to it.  We'll create "dice wars", a pretty simple game. We'll start simple, but we'll embellish it until it looks really darn good. The rules for "dice wars" are available here .  I am best with JavaScript, so we'll start there. Please note that you need to have SOME fundamental knowledge of JavaScript to follow along at a normal speed. This is NOT a JavaScript tutorial, though it can be treated as a project sample.  You will learn in this segment: Very simple Bootstrap Very simple DOM manipulation with jQuery How to use the random number generator How to write a message to JavaScript console with console.log How to write JavaScript function, and how to call it from elsewhere How to click a button and make it run a function Initial Planning For the first step, w...

Are You Solving the Right Problem? (i.e. the XY Problem)

Ever heard of the XY problem? No? Those of you in tech support may have seen it without knowing its name, but it actually happens quite often in programming and tech support.  Here is an example from xyproblem.info , albeit rewritten for JavaScript n00b> How do I get the last 3 letters of the filename?  feline> If it's in a variable, you can slice it like str.slice(-3) feline> Wait, why are you asking?  What do you really want?  feline>Do you want the extension (of a file)?  n00b> Uh, yes?  feline>There's no guarantee that every file name will have a three-letter extension, so blindly grabbing three characters does not solve the problem. With that said, here are three ways to get it , using regex, split, or slice+lastIndexOf  See the problem? noob asks for X (last 3 characters of string), but actually wanted to solve Y (get file extension). What if there was no extension? What if the extension is MORE THAN 3 letters?  S...

Basic Program Logic: Input / Process / Output, and basic Loops

Previously, we had talked about how some people cannot problem-solve . While others take to it like duck to water. They can't see the process of the programing, esp. when it comes to applying if branches or even loops. So let's discuss that a bit.  A very simple program takes some input, process the input, and generates an output.  Get input Process input Display output Simple, right?   Let's Write a Simple Input/Process/Output program Now let's write a very simple calculator in JavaScript. Enter two numbers (with prompt), display the output with an alert box. NOTE: You can do this with command-line arguments and spit the output to the console. Or even use a different language. The idea is the same.   var a = prompt("Enter a",0) // input var b = prompt ("Enter b",0) // input var x=parseInt(a)+parseInt(b) // process alert("Result is "+x) // output You may have noticed I used parseInt. That's because prompt returns a STRING. And when you ...

How to Solve a Problem 5: Horse-Racing Duals and HyperDuals

 Let us take a look at one of the competitors to HackerRank... CodeWars, and one of the puzzles on it. This one is called Horse-Racing Duals, and a harder version called HyperDuals. But one thing at a time.  You can access the problem here:  Link Read the problem very carefully. Noticed that it lists " external resources: Sorting, Lists "? Clearly, you will need to sort the solution.  I am going to do this in JavaScript, which is pretty universal.  First, they did NOT create any data structure(s) for you, so you have to create your own. I simply called mine horses . And I added a line in the readline loop to load the number into the array.  const   N  =  parseInt ( readline ()); var   horses = [] horses . length = N ; for  ( let   i  =  0 ;  i  <  N ;  i ++) {      const   pi  =  parseInt ( readline ());      horses [ i ]= pi } But...

Yet another take on recursion

Recursion is often one of the hardest things to "get" in programming, so when you have your "aha" moment, it's that much more amazing. Conceptually, it's not that hard to see, but how do you actually program one such?  First, realize that " recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem." Let us try something simple. Let's say... I want you to sum up the elements of an arbitrary array, let's call it arr. It can have any number of elements, and each element is an integer. For the purpose of this exercise, let's just say it's [1,2,3,4], but it can be any integer, and the array can be any valid size. And I want to you use recursion, not loop (no for or while or such statements).  Now, remember the definition: "solving a problem where the solution depends on the solutions to smaller instances of the same problem".  Let's call this function rsum (...

How to Solve a Problem 4: Where is the number?

Ran into this problem on reddit , and figure I'd give this a try on how to solve it.  I need to find which line a certain number is, like: First Line - 1 Second Line - 2 3 4 Third Line - 5 6 7 8 9 Fourth Line -> 10 11 12 13 14 15 16 Fifth Line -> 17 18 19 20 21 22 23 24 25 Nth line - (...) 1969 (...) What is N?   Always study the data given, and find the pattern. We need to solve this with a program.  In this case, the pattern is pretty obvious: the line ends in the square of the number. 5th line ends in 25 (5^2).  So to get N, we take the square root of 1969, and it turns out to be 44.something.  44*44 = 1936.  So it's obvious that 1969 is on the NEXT line, N=45.  But how do you do this programmatically? The original question called for Python, but we'll do this in JavaScript, as it's quite simple.  We need to keep testing N and increment N until N^2 is larger than 1969.  let bFound=false let n=1 while (!bFound) {     if ((n^...

How to Solve a Problem 3: Strings - Making Anagrams

 Let us take on another problem. This time, let us do HackerRank's " Making Anagrams " problem.  This is the important part... Given two strings,   and  , that may or may not be of the same length, determine the minimum number of character deletions required to make   and   anagrams. Any characters can be deleted from either of the strings. For example, if   and  , we can delete   from string   and   from string   so that both remaining strings are   and   which are anagrams. Also note the output: Print a single integer denoting the number of characters you must delete to make the two strings anagrams of each other. There are a couple different ways to do this, but let's think about the problem given. Often, the data itself is a clue.  1) We are only solving for anagrams, so the position order does not matter.   2) There are only lower case characters, s...