Photo by Chris Liverani on Unsplash
Code Wars - Cockroach Speed.
Breaking down code war challenges in a simple and understandable way.
The Problem Statement
The cockroach is one of the fastest insects. Write a function that takes its speed in km per hour and returns it in cm per second, rounded down to the integer (= floored).
For example:
1.08 --> 30 Note! The input is a Real number (actual type is language-dependent) and is >= 0. The result should be an Integer.
Analysis - Breaking Down The Question
We are asked to write a function that converts the km to cm per second and round it to the nearest integer.
Before we jump into the solution, it is important to understand the math here. The equation to convert kmph to cm/sec is to multiply the kmph by 5/18. It looks like (1.08x5/18)x100 -refer to the above example.
The Solution
Let's create a simple function that takes the cockroach's speed in kmph as shown below
function cockroachSpeed(s) {
}
Suppose, the cockroach's speed is 2km/hr then the calculation will be like this - (2x5/18)x100 = 55.555555. Let's see this in the function.
function cockroachSpeed(s) {
var speed = (s*5/18)*100;
console.log(speed) //55.5555555 if the s =2
}
cockroachSpeed(2)
But we want it to be rounded down to the nearest integer i.e; 55. For that, we can use Math. floor().
function cockroachSpeed(s) {
var speed = Math.floor((s*5/18))*100;
console.log(speed) // 55
}
cockroachSpeed(2)
We can return the speed as follows
function cockroachSpeed(s) {
var speed = (s*5/18)*100;
console.log(speed) //55.5555555 if the s =2
return speed;
}
cockroachSpeed(2)
We can simplify the solution even more and write it in one line.
// Instead of writing 5/18*100 we can reduce this value to 27.777777778
// And instead of storing the value in variable speed, we can return it directly.
// One line code
function cockroachSpeed(s) {
return Math.floor(s*27.777778);
}
Final Words
Hope you liked this tutorial and if you did, subscribe to my newsletter and never miss my upcoming articles.
Thanks for reading this article.