r/dailyprogrammer • u/Elite6809 1 1 • Jun 14 '14
[6/14/2014] Challenge #166b [Easy] Planetary Gravity Calculator
(Easy): Planetary Gravity Calculator
Welcome to this week's rebooted challenges. While this challenge is very simple at its core (which I think gives it an Easy rating), it gives me a chance to teach a bit of physics while I'm at it, so I may as well!
Newton's Law of Universal Gravitation says that:
Any two objects in the universe attract each other gravitationally...
With a force that's proportional to the product of their masses, and...
Inversely proportional to the square of the distance between them. (distance is measured from the center of the object - so if you're standing on Earth, you are about 6353 km away from it.
Because this is only a proportionality (not an equality), you will need a constant multiplier - this is called G, the gravitational constant.
This gives us the remarkably simple formula:
mass of first object × mass of second object
force = G × --------------------------------------------
(distance between objects)²
This force is applied on both objects equally and in opposite directions, toward each other. The value of G is currently known to be about 6.67e-11 which is why gravity is so weak - you can overcome the force of the entire planet just by jumping!
These 4 simple rules were used to describe gravity in nearly its entirety before Albert Einstein found out it was incomplete and discovered Special and General relativity - which you won't need today! Anyway, this is the only bit of physics you'll need for today's challenge - the rest is basic maths.
We're going to assume all planets are perfect spheres. This means you can find the volume of a planet, given its radius, with the fomula V = 4/3 × π × radius³ like a normal sphere. We'll also assume they are made of a material which has the exact same density everywhere - so a handful of material from one bit of the planet weighs the same as any other. This means, given a density (in kilograms per cubic metre), and using the volume you worked out, you can compute the mass of the planet with the formula mass = volume × density. Assume the units you are using are kilograms and metres. Sorry, imperial folk!
Now, in case you are new to physics, you may need to know a little bit about forces. Forces are measured in Newtons (N) and measure, essentially, how hard an object is pushing another object. The object could be pushing physically - eg. pushing a lawn mower - or via an elementary force, such as Earth's gravity pushing you toward it. They can all be measured in Newtons. The force of a planet on something due to gravity is called weight - which is not to be confused with mass, which is measured in kilograms and is a measure of how much matter something contains. As we saw before, the more mass two objects have, the greater the force they exert on each other. As gravitational force is dependent on the product of the masses of both objects, an object will weigh more if either the object itself, or the planet, is heavier - which is why you weigh less on the Moon!
Anyway, after that lengthy backstory, the challenge for you today is, given the dimensions of several planets and an object's mass, calculate how much force is applied on the object at the surface of the planet. Pretend the object is quite small for simplicity of your caluclations.
This is certainly a lot of physics to get your teeth into, so if you need any help, leave a comment and either I or someone else should be happy to help you out.
Formal Inputs and Outputs
Input Description
You will be given a number M which is the mass of an object in kilograms, on its own line, for example:
100
Followed by a number N:
4
You will then, on separate lines, be given a list of N planets. This will be given as its name, its radius (in metres), and its average density (in kilograms per cubic metre), like so:
Mercury, 2439700, 5427
Output Description
Print the weight (in Newtons) of the object if it were at the surface of each planet, like so:
Mercury: 314.623
Example Inputs and Outputs
Example Input
100
4
Tantalus, 3104500, 5009
Reach, 7636500, 4966
Circumstance, 4127000, 4132
Tribute, 2818000, 4358
Example Output
Tantalus: 434.467
Reach: 1059.536
Circumstance: 476.441
Tribute: 343.117
Challenge
Challenge Input
75
9
Mercury, 2439700, 5427
Venus, 6051900, 5243
Earth, 6367445, 5515
Mars, 3386000, 3934
Jupiter, 69173000, 1326
Saturn, 57316000, 687
Uranus, 25266000, 1270
Neptune, 24553000, 1638
Pluto, 1173000, 2050
Expected Challenge Output
Mercury: 277.442
Venus: 664.886
Earth: 735.845
Mars: 279.124
Jupiter: 1922.011
Saturn: 825.103
Uranus: 672.382
Neptune: 842.741
Pluto: 50.388
(These values are all very nearly exact!)
Notes
You have a chance to utilise some OOP here. If your programming language supports it, you may want to create a Planet object.
3
u/Elite6809 1 1 Jun 14 '14
My solution in Ruby. If the description left you a bit stumped, this may help you out a bit.
4
u/JamesC1337 Jun 14 '14
My solution in AutoIt.
Btw, your formula for the volume is wrong (it says '
4 *' instead of '4/3 *').2
u/Godspiral 3 3 Jun 14 '14 edited Jun 15 '14
In J, is it possible Mercury example is wrong? Or I don't have enough precision for pi (3.14159)
2439700 ([ weight 100 , mass) 5427
369.922
edit: its not pi precision... don't know why its off.
2
u/uprightHippie Jun 14 '14
C#
This is my first submission so any feedback would be appreciated. I'm only submitting the Planet class; the main program just reads the input file, instantiates a planet object with radius and density and then does a writeline with planet name and the results of gravitationalForce
14
u/Edward_H Jun 14 '14
COBOL:
9
u/The_Pierce Jun 15 '14
My solution in Swift! It's not very pretty because I really don't know much about the language – this is my first foray into it at all! (Started ~3 hours ago.) Comments are appreciated. :)
Solution:
Challenge Output:
5
u/thestoicattack Jun 14 '14 edited Jun 14 '14
bash:
EDIT: planet names can now have spaces, but not tabs.
4
u/Danooodle Jun 14 '14
My solution in Batch. Batch doesn't have floating point numbers and is limited to mere 32 bits integers, so precision and some accuracy were lost. After lots of rearrangement:
Output for Example:
Output For Challenge:
4
u/aminb Jun 15 '14
First time submitting anything in this sub. Feedbacks welcome and really appreciated!
Python 3
1
u/[deleted] Jun 15 '14 edited Jun 15 '14
Python 2
First time submitting a solution. Hope I ididn't screw up the format for submitting.
Anyway, tried an OOP approach. Don't really do OOP in python, thought it would be fun.
3
u/Lurker378 Jun 14 '14
Rust 0.11 master
3
u/salonabolic Jun 14 '14
C++
3
u/CMahaff Jun 14 '14
Haskell
Question for Haskell pros. The last line was essentially a guess by me. When I had asked for help another time, the code sample provided used
mapM_instead offmapon aputStrLn. Usingfmapgenerates an error, complaining aboutStringandIO String. Can anyone help me understand why that is?3
u/ooesili Jun 14 '14
Haskell solution:
3
u/[deleted] Jun 14 '14 edited Jun 14 '14
My solution in Lua:
Output on ideone.
3
u/HyperAnthony Jun 15 '14 edited Jun 15 '14
Powershell
As a note, this is intentionally obtuse for Powershell in order to stick rigidly to the prompt's input/output requirements. A more natural input for powershell would be to pipe a collection of planet objects to Get-GravitationalForce, and allow it to use the radius and mass properties of an N number of input planets.
Code: (on Pastebin)
Execution:
3
u/chunes 1 2 Jun 15 '14 edited Jun 15 '14
Java:
3
u/_M1nistry Jun 15 '14 edited Jun 15 '14
C#:
First Submission here, late and after my calculations were coming out odd (accidentally used 3 in the force formula) my code was very similar to other examples already posted.
3
u/dancole42 Jun 15 '14 edited Jun 15 '14
Python
I've only been programming for a few weeks, Python is my first language, and I'm self-taught, so feedback is extremely appreciated!
I wasn't sure if I was supposed to convert the challenge input by hand to something like a dictionary or leave it "as-is," so for the added practice I went with the second option. I've also included a Class called "Units" to make it easier to convert the output to something other than Newtons.
Output
ETA: Output.
4
u/bretticus_rex Jun 14 '14 edited Jun 16 '14
Python 2.7
I am curious if there is a better way to enter each planet instance besides typing it in the way I did. Tried find a way to just copy and paste the input from the challange into an input string, that would be parsed to set M and to create each planet instance. I got stumped and just did it manually.I figured it out! Pretty proud of my noob self. Version 2 is below.
Refactored Version
Output:
2
u/[deleted] Jun 14 '14 edited Jan 02 '16
2
u/nullmove 1 0 Jun 14 '14 edited Jun 14 '14
Haskell:
Output:
2
u/flamingsushi Jun 14 '14
Here's my Haskell version:
I'm still learning the basics of Haskell, so any tips are extremely welcome!
EDIT: didn't really need the
deriving(Show)with the Planet data type.2
u/LyndonArmitage Jun 14 '14
My first time posting an answer here (although I have done one or two on my own).
I used JavaScript and node.js for this. I haven't use node.js in a while so feel free to suggest improvements:
Output Example (I didn't round the output):
2
u/dmv1975 Jun 16 '14 edited Jun 19 '14
Here's my Python answer. I copied the challenge input to a file called planet_list.txt and read from it. Halfway through coding, I remembered Pluto is not a planet, but I didn't go back to change the file name. I'm puzzled as to why my output is going to seven decimal places when I limited it with '%f3' because I wanted my output to be identical to the expected output. I have only a little experience with programming at a hobby level. Any criticism (constructive or otherwise) is very welcome.
EDIT: I realize now, I should have put '%.3f'. Fixed.
Output:
2
u/flyingpancake Jun 18 '14
Small python solution. The only notable point is it factors out the coefficient 4/3 * pi * G * m
2
u/Raduknight Jun 19 '14
C# - First post into here, suggestions most welcome if you see anything worth changing. Figured this is a good way to keep skills up during time off school. Automated input because i'm lazy, though it could be easily adjusted to accept keyboard input, Regex should continue to work.
2
u/mva Jun 19 '14 edited Jun 19 '14
Many days late but I have to learn C for work so I figured doing some of these challenges is a good way to start. I put the challenge information in to a file and read from there.
Output:
Also a quick one in python3 (although nothing python3 special about it). Wanted to write one which does not use classes.
Outputs:
3
u/poeir Jun 14 '14 edited Jun 15 '14
Here's my solution (in python). It's short enough to paste here.
2
u/pau101 Jun 14 '14
Solution in Java
1
u/PrintfReddit Jun 15 '14
PHP, also tells the acceleration due to gravity on surface of the planet.
1
u/OnceAndForever Jun 16 '14
Lua 5.2
Usage:
Output
I really liked deorst's solution too. I didn't think it could be condensed that much. I also feel like I should be using an iterator here, but I couldn't get it to work properly. Any tips would be appreciated!
1
u/etnoatno Jun 16 '14
PHP:
my first submission, still getting the grasp of using OOP
1
u/np- Jun 16 '14
Sorry, I am late to the party, I was busy travelling in time. Submitting for the first time. It is Python 3
1
u/Kalthose Jun 16 '14
This is the first time I have posted in one of these threads, but I have been doing them for the last month. Just wanted to take the time to thank the people who put these together. Time to share the garbage code. :D
input:
I had to change the whitespace because for some reason String.split wouldn't pick up white space, I'm going to look into it further.
output:
Program.java
Planet.java
I'm pretty late (I didn't know the post was getting posted sooner then usual), but any help/criticism would be greatly appreciated.
1
u/swingtheory Jun 16 '14
My Tkinter Gui Planetary Grav Calculator!
1
u/dnerd Jun 16 '14
c# with linq and regular expressions - missed the part about creating a "Planet" class
1
u/1nvader Jun 16 '14 edited Jun 16 '14
Python 3:
1
u/[deleted] Jun 17 '14 edited Jun 17 '14
My shot at OO Perl. Feedback is welcomed!
program:
Module :
1
u/VerifiedMyEmail Jun 18 '14
Python 3.3
1
u/jnazario 2 0 Jun 18 '14
fsharp, basically a port of the haskell solution from /u/ooesili. i suspect there's a more FP-ish way than a loop with an unused counter
output for basic input:
and for challenge input:
usage: % fsharpi challenge.fsx < /tmp/input
1
u/spfy Jun 18 '14 edited Jun 18 '14
I recently learned a bit about databases. I thought it would be fun to utilize them in some challenges! Here's my Python 3 attempt, utilizing a Mongo database I created for this exercise.
First, I created a text file following this format:
Then, I used this load program to get my text file into the database:
Here's what it looks like from inside Mongo:
Once the database is loaded, this program lets the user enter as many planets as they want, querying the database each time. It prints out all of the different weights once the user quits.
Running:
1
u/harrychin2 Jun 19 '14
My C++ solution
1
u/mortenaa Jun 19 '14
Sorry for the late submission (my first ever) I've done it in Javascript/Node, as I'm trying to learn that language. Feedback is welcome!
1
u/dailyRubyProgrammer Jun 19 '14
RUBY: I've learned a lot about splat operators and maps on this one. The previous solution in Ruby helped me coalesce a lot of ideas I had but couldn't put together. Feel free to comment/recommend improvements!
1
u/BryghtShadow Jun 20 '14 edited Jun 27 '14
SWI-Prolog v6.6.6:
I thought this would be easy task in Prolog, but turns out I'm doing something wrong. Feedback would be useful.Edit: Figured out what I was doing wrong! "6.67 * e - 11" is not the same as "6.67e-11".
Usage:
?- main('filename here').?- main.Input values should not be wrapped in quotes or dot-terminated.
Code:
Outputs:
1
u/dohaqatar7 1 1 Jun 22 '14
I'm late to posting my answer for this one because I've been out of town for 8 days. If you're, I would appreciate it if you left to comments because I'm new to haskell.
Haskell
1
u/marcelliru Jun 22 '14 edited Jun 22 '14
A first try in Racket. I am grateful in advance for your comments. One of the problems it the output: it has a strange line of "#<void>".
Output:
1
u/bruntonspall Jun 23 '14
Python 2.7 with a class for the planet (rather than a tuple which was my instinct):
1
u/ccmetz2020 Jun 23 '14
Hey guys, this is my first post here and since I'm learning javascript I decided to post a solution with it. Please give me some constructive criticism if you see any code that can improved/changed! I just hard-coded in mercury to test it. I'm not quite sure how to do user input in javascript yet.
1
u/FaithOfOurFathers Jun 27 '14
Java
https://gist.github.com/anonymous/62936cc55c7f46fd574a
I tried to best utilize the object class, the data comes out right, would love if there's any advice to make my code cleaner or anything.
1
u/nalexander50 Jun 29 '14
This is my first time really using the Python language. I found out that we have to learn it over the summer for my Data Mining course in the fall, so I figured that I would work some of these challenges. I know this is kind of old, but I would still appreciate any feedback.
1
u/dp_account Jul 02 '14
Python3:
1
u/Potato2k4 Jul 03 '14
My solution in python 3.4 :D
1
u/mdlcm Jul 03 '14
Used R!
read data
format data
calculate force (unit: newton)
Output
1
u/russjr08 Jul 05 '14
My "home language" is Java, but I thought I'd spice it up with C++11 (Just started learning it, definitely an interesting language!) It could've been trimmed obviously.
1
u/[deleted] Jul 15 '14
Python 2.7 - Could someone please take a look at my code and explain why this isn't giving me the expected output? It's returning:
Mercury: 208.081379199 N
1
u/golanga Jul 24 '14
Go:
1
u/[deleted] Jul 29 '14
Here's mine! Done in python, I'm pretty new to programming in general. Here's the pastebin link: http://pastebin.com/ucn3gg7Q
1
u/p44v9n Jul 31 '14
Scala solution. Still new to all this. Cheers to Lawrence for holding my hand through this one. Would greatly appreciate any comments or criticisms or suggestions.
1
u/yoho139 Jun 14 '14 edited Jun 14 '14
A nice and short (it's rare I get to say that, given the language!) solution in Java. Output is as expected (thanks for pointing out that mistake, /u/yaynick).
I didn't do any unnecessary cubing (write out the formula and cancel, you'll see why), which should eliminate some imprecision.
JAVA:
Apologies for the long line; I know the code formatting doesn't like it!
1
u/Okawi Jun 14 '14 edited Jun 14 '14
First submission here in Java :
InputOutput :Tell me if there is something to improve !
1
u/heckler82 Jun 14 '14
Coded in Java
1
u/YouAreNotHere Jun 14 '14
Here's my answer in Java. This is my first submission so if you have any critiques to make, it would be much appreciated!
1
u/Strykker2 Jun 15 '14
Python,
Output:
1
u/staffinator Jun 15 '14
Java:
1
u/mtko Jun 15 '14
C#:
0
u/[deleted] Jun 15 '14
[deleted] — view deleted comment