Thinking like a programmer

secrets of breaking down codes and finding a solutions to them4 min


Have you been looking to master how to think and break down problems and how to convert your pseudocodes to actual working codes? We all are

Advertisements

I’ve been solving some code challenges at codewars and Hackeranks and I found out that even the ugliest and deadly looking code problems are nothing but something that can be solved with the combinations of the basic programming knowledge that you already have.

We will solve so many challenges to get you acquainted with how to think and solve problems like a programmer that you already are.

FIRST STEP

Please stop getting scared and thrown out by code problems like how can you confront and defeat something you are scared of?. The mightiest codes are nothing but small fragments of codes joined together. Imagine combining your array knowledge and your string knowledge to change the content of an array etc. That’s just what it is.

SECOND STEP

The next step is gathering our amour because why not? We need to be ready to throw in any of the various methods in existence to defeat the problem easily rather than implementing them from scratch. Imagine trying to reverse an array and implementing it from scratch when you could have called the .reverse() method?

I use the Mozilla doc whenever I am working on code problems because that is where everything I need can be found.

Arrays and every method pertaining to it can be found HERE
Strings and every method pertaining to it can be found HERE
Objects and every method pertaining to it can be found HERE

With that in place, we can attempt and conquer every lab and code problems

LAB ONE

Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 integers. No floats or empty arrays will be passed.

For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7.

[10, 343445353, 3453445, 3453545353453] should return 3453455.

How do we break the code down? Think about it before proceeding!

This seems straightforward I hope. You are asked to return the sum of the two smallest numbers which we can easily see but how do we get the program to run that effectively?

We can loop through the array and add the smallest numbers together

We can add the smallest number to a new array and sum them when we are done

Trust me, these are really long and stressful way of accomplishing a very small task

Have a look at our array arsenal at Mozilla, you will notice that there is an armour called sort() which sorts just like the name, arrays in either ascending or descending order.

When we sort the arrays let’s say in ascending order, we can get our two smallest values at the first and second index and booooom, that’s it. We go ahead and sum them and the problem is solved.

function sumTwoSmallestNumbers(numbers) {  
  let total = 0;
  let newArr = numbers.sort((a, b) => a - b);

  total = newArr[0] + newArr[1];

  return total;
}

I declared and initialised my total variable to 0 as expected, created a new array which I called newArr which now contains the sorted array from the sort() method.

I now added the first index [0] and the second index [1] which obviously have the smaller and next numbers in them now and that’s it. Return your total and that’s all.

Advertisements

LAB TWO

create a functions that takes in an array and a number "num" and then returns a new array containing the numbers in that array that is completely divisble by "num"

Understanding the question is key. First, look at what the question is asking you to return because that would give u a good idea of what direction to follow. In this case, we are returning an array….. keep that in mind.

Next, we should have observed that the function would take in two parameters which we represent with a parameter or argument as thus function functionName(parameter1, parameter2).

We should take one parameter as the array and the other as the number which according to the problem, asked us to call or represent as “num”.

With the structure in our hand, we are faced with the logic now. How does one get a number that is completely divisible by a number? Well, we use the modulus operator(%) to find that. The logic is that any x % y === 0 means that y can divide x completely leaving no remainder as % is more concerned with the remainder in a division.

Finally, with that at hand, we will loop through the array one after the other, checking with our if statement, whether the number can be divided by our divisor and if it can, we should push it to the array we hope to return at the end

function canDivide(arr, num){
  let newArr = [];

  for(let i = 0; i<arr.length; i++){
    if(arr[i] % num === 0){
      newArr.push(arr[i]);
    }
  }

  return newArr;
}

LAB THREE

Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.

For example:

uniqueInOrder('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
uniqueInOrder('ABBCcAD')         == ['A', 'B', 'C', 'c', 'A', 'D']
uniqueInOrder([1,2,2,3,3])       == [1,2,3]

The lab above is looking for a function that will return elements that do not have the same element after it but can have that element again provided that two similar elements are not close to each other.

Think of how to implement this. Looking at the examples provided, some are arrays, some are strings….. this looks hard

Crazily, it isn’t because array and string can really be iterated through using the same methods so we need not worry about that and we can also index arrays and strings the same way.

The idea is to loop through the elements and check for whether the next array is similar to the current array and if it is, we do nothing, else we push it to our new Array that we have initialised like always when we need to return an array.

function uniqueInOrder(str){
  let newArr = [];

  for(let i = 0; i<str.length; i++){
    if(str[i] !== str[i+1]){
      newArr.push(str[i])
    }
  }
  return newArr;
}

While we didn’t use much of our armoury, we would need it anyway most of the times. It is best to look at it, understand what each does but not necessarily cramming them as you can always look at it whenever you feel like.

Thinking like a programmer requires you to be able to break problems down in your language and understanding and then choosing from your bank of methods, ways to solve the problem.

If you enjoy the content of our website, please consider registering as a member and begin contributing and sharing what you know to people who may need them. Also join our programming telegram channel where programmers are constantly discussing and solving programming related issues.

Advertisements

Like it? Share with your friends!

Nnaji Victor

Legend

DecaDev, Full-stack developer in training, Gamer, Techie and weirdly cool. I love writing new stuffs that I just discovered and playing around on the net. Check my socials or email me.

What's Your Reaction?

Wow Wow
4
Wow
love love
4
love
hate hate
0
hate
geeky geeky
1
geeky
win win
1
win

0 Comments

Choose A Format
Trivia quiz
Series of questions with right and wrong answers that intends to check knowledge
Poll
Voting to make decisions or determine opinions
Story
Formatted Text with Embeds and Visuals
List
The Classic Internet Listicles
Countdown
The Classic Internet Countdowns
Open List
Submit your own item and vote up for the best submission
Ranked List
Upvote or downvote to decide the best list item

Send this to a friend