The Little Prince [Solution | Javascript] - Computational Thinking 101 | Beginner
Wahid Abduhakimov
Posted on January 27, 2021
Earlier I posted a Computational Thinking problem at this link. In this post, I am going to explain a solution written in Javascript.
A Javascript solution
- Let's get first input
N
for test cases and spin-up a loop which runsN
times for all test cases. Also, includecrossings
variable which counts number of crossings for each test case.
// assume user enters valid value only
test_cases = prompt('')
while(test_cases)
{
let crossings = 0;
test_cases--;
}
- Now, we are going to read start and destination points.
// start and end points
let points_input = prompt('').split(' ');
let start = { x: points_input[0], y: points_input[1] };
let end = { x: points_input[2], y: points_input[3] };
- Read
M
for number of planetary systems and make a loop which runM
times. All the hard work happens inside that loop.
// M planetary systems
let M = prompt('');
while(M)
{
// do something nice for each planetary system
M--;
}
- Let's talk about the main Algorithm now! The Little prince has to enter or exit any planetary system, if and only if the start point OR destination point (only one of them) is inside the planetary system.
Let's find out if he has to cross THIS planet, and if so increase the count.
let planet_input = prompt('').split(' ') // x, y, r -> center and radius of a planet
let planet = { x: planet_input[0], y: planet_input[1], r: planet_input[2] };
if(hasToCross(planet, start, end))
{
crossings++;
}
- We need to use logical
XOR
to check if ONLY start or end is in planetary system.
function hasToCross(planet, start, end)
{
// simulated logical XOR
// (start in planet) XOR (end in planet)
if( (isInPlanet(planet, start) || isInPlanet(planet, end))
&& !(isInPlanet(planet, start) && isInPlanet(planet, end)) )
{
return true;
}
else
{
return false;
}
}
For any point to be in a circle, distance between the point and circle center must be less than the radius of the circle.
- Now, you know from middle school that you need pythagorean theorem to detect distance between points.
function isInPlanet(planet, start)
{
let a_squared = Math.pow(planet['x'] - start['x'], 2);
let b_squared = Math.pow(planet['y'] - start['y'], 2);
let distance_to_center = Math.sqrt(a_squared + b_squared);
return distance_to_center < planet['r'] ? true : false;
}
- Finally, we just need to print
crossings
after we process the 'planets loop'.
console.log(crossings);
Source code
Try copying and pasting the below input into repl!
2
-5 1 12 1
7
1 1 8
-3 -1 1
2 2 2
5 5 1
-4 5 1
12 1 1
12 1 2
-5 1 5 1
1
0 0 2
💖 💪 🙅 🚩
Wahid Abduhakimov
Posted on January 27, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript The Little Prince [Solution | Javascript] - Computational Thinking 101 | Beginner
January 27, 2021