r/dailyprogrammer • u/nint22 1 2 • Sep 17 '13
[09/17/13] Challenge #138 [Easy] Repulsion-Force
(Easy): Repulsion-Force
Colomb's Law describes the repulsion force for two electrically charged particles. In very general terms, it describes the rate at which particles move away from each-other based on each particle's mass and distance from one another.
Your goal is to compute the repulsion force for two electrons in 2D space. Assume that the two particles have the same mass and charge. The function that computes force is as follows:
Force = (Particle 1's mass x Particle 2's mass) / Distance^2Note that Colomb's Law uses a constant, but we choose to omit that for the sake of simplicity. For those not familiar with vector math, you can compute the distance between two points in 2D space using the following formula:
deltaX = (Particle 1's x-position - Particle 2's x-position)
deltaY = (Particle 1's y-position - Particle 2's y-position)
Distance = Square-root( deltaX * deltaX + deltaY * deltaY )Author: nint22
Formal Inputs & Outputs
Input Description
On standard console input, you will be given two rows of numbers: first row represents the first particle, with the second row representing the second particle. Each row will have three space-delimited real-numbers (floats), representing mass, x-position, and y-position. The mass will range, inclusively, from 0.001 to 100.0. The x and y positions will range inclusively from -100.0 to 100.0.
Output Description
Print the force as a float at a minimum three decimal places precision.
Sample Inputs & Outputs
Sample Input 1
1 -5.2 3.8
1 8.7 -4.1Sample Output 1
0.0039Sample Input 2
4 0.04 -0.02
4 -0.02 -0.03Sample Output 2
4324.3279
16
u/JavaWarlord Oct 12 '13
Where is the next challenge??????
14
u/remram Sep 20 '13
Python solution:
11
u/thisguyknowsc Sep 17 '13 edited Sep 17 '13
Simple C solution:
17
u/MusicalWatermelon Sep 17 '13 edited Sep 17 '13
Just here to say: Coulomb's Law works with charges, not masses
EDIT: In Java (Can someone explain me how I can extract two rules of text, and then convert them to floats, instead of needing to input float per float...)
15
u/battleguard Sep 17 '13 edited Sep 22 '13
C# Solution
15
u/j03 Sep 17 '13
In Python:
7
u/[deleted] Sep 23 '13 edited Jul 28 '14
I posted nothing...
6
u/SweetScientist Sep 18 '13
Haskell:
5
u/dunnowins Sep 17 '13 edited Sep 23 '13
Ruby solution:
Edit: Added an Awk solution. Haven't figured out how to round to 4 digits yet:
5
u/jrl5432 Sep 18 '13
If you want a harder challenge, try graphing the field lines of the electromagnetic field from a plate magnet 5cm long along the xy plane. Even harder? Try it in 3 dimensions now as a 5cm by 5cm square.
5
u/[deleted] Sep 18 '13
Simple Ruby solution:
Pardon my variable naming. Usually they are pretty descriptive.
8
u/rent0n86 Sep 17 '13 edited Sep 17 '13
My solution using R, as usual.
4
u/Mr_Dionysus Sep 17 '13
Quick and Dirty C++:
4
u/killedbythegrue Sep 18 '13
In Erlang
I took a simplified approach with the input using formatted read. This requires that the numbers be entered as floats but saves the steps of breaking up the string and converting to floats.
4
u/[deleted] Sep 18 '13
Because there isn't a Perl solution yet...
You could undoubtedly make it shorter, but golf was never my thing.
EDIT: just noticed my code gives a subtly different answer to the specimen output for the second set of input:
The discrepancy creeps in around the 7th significant figure, i.e. 3rd decimal place. I suspect a rounding bug in the spec introduced while sqrt-ing the distance and squaring it again, but I'm open to being told it's actually my bug!
4
u/7f0b Sep 19 '13
Needlessly-verbose solution in PHP:
4
u/Atlos Oct 03 '13
Hey, I'm a Java programmer trying to learn some Python. Could somebody look my solution over? I see some people did it here in just a couple of lines lol, so my solution may not be as pythonic as it could be. Would love some tips even though it's so short.
https://github.com/trevor-e/DailyProgrammer/blob/master/9-17-13.py
4
u/[deleted] Nov 01 '13
/u/nint22 we miss you buddy! Come back!
3
u/Edward_H Sep 17 '13
My solution in F#:
3
u/jimauthors Sep 17 '13
Simple Golang
http://play.golang.org/p/WXClmM9cGX
3
u/[deleted] Sep 17 '13
Solution in java.
/* RepulsionForce.java */
/* RepulsionForceCalc2D.java */
/* Particle2D.java */
3
u/TweenageDream Sep 18 '13
My very straight forward ruby solution... I do have a bit of a rounding difference using this method, in both python and ruby i have a slightly different output for 2...
ouput:
did anyone else have slightly different answer for 2?
3
u/[deleted] Sep 18 '13 edited Sep 18 '13
A basic solution in C++. I'm only beginning, so there's bound to be a few inefficiencies.
*Fixed up some syntax.
3
u/5900 Sep 19 '13 edited Sep 19 '13
JS/Node.js. For some reason my answer to input 2 is only right up to the hundredths place.
Edit: Smalltalk solution added
3
u/CarnivalTears Sep 20 '13
Quick Javascript I threw together:
3
u/Quasimoto3000 1 0 Sep 22 '13 edited Oct 03 '13
Some very tight clojure code. I always love advice from the lisp gurus.
(find-force [1 -5.2 3.8] [1 8.7 -4.1])
; => 0.003912056959549332
3
u/SuperBeaker Sep 24 '13
Oracle PL/SQL
3
u/camdroid Sep 25 '13
C++
3
u/[deleted] Oct 04 '13
My solution in Common Lisp:
5
u/Delocaz Sep 24 '13
I did in Python 2, object-oriented style:
6
u/wckdDev Sep 18 '13 edited Sep 18 '13
The question above is not properly defining Coulomb's law. Coulomb's law deals with the charges that particles hold and has NOTHING to do with their masses. The formula above (even if we forget the fact that it's missing a very important constant) calculates nothing that I am aware of as being important in the world of physics.
Sorry, but just because it is a challenge labeled easy, it doesn't need to be dumbed down to the point of destroying its meaning.
2
u/Cjones3107 Sep 17 '13
Python solution. 1st time posting to here, feedback appreciated!
2
u/zupeRad Sep 17 '13
My Java soultion:
2
u/[deleted] Sep 17 '13 edited Sep 17 '13
A solution in Xtend (using Property annotations for getters/setters and a couple of extension methods):
2
u/pmpmp Sep 17 '13
Python. Very new & welcome feedback. Is there a more efficient way to convert the input data from string to floats?
2
u/taterNuts Sep 18 '13
I'm learning ruby and wanted to do something verbose for this one, in case this needed to be a re-usable piece of code. I wanted to be clever with the initialization/usage of the class but will re-visit in the morning.
Anyways, Ruby (class only):
2
u/serejkus Sep 18 '13
My solution using boost::spirit. Actually, you don't need to compute square root - anyway, you'll have to make a power of 2 of it later, when computing force. Things to improve in my solution: make checks for mass and points range, make check for zero division error.
2
u/d_j_s Sep 18 '13
My first ruby post, would appreciate any feedback
2
u/[deleted] Sep 18 '13
My Python OOP approach -
Input:
Output:
2
u/Dutsj Sep 18 '13
I like this idea, but I decided to do something completely different with this challenge.
I wrote a Java program where it calculates the forces between two points where you click with your mouse, in terms of elementary charge. It allows for removing points (quadruple click), charges that can be increased and decreased with left and right mouse buttons and it draws circles where you click on the screen. It's the first time I've written a project this big, it will still have some bugs in it and I have never shared anything using git before, so for myself it's a great accomplishment. Here it is: CoulombForce.
2
u/winged_scapula Sep 18 '13 edited Sep 18 '13
Python
2
u/thisisnotmypenis Sep 18 '13
[C++] #include <iostream> #include <cmath>
2
u/[deleted] Sep 19 '13
Not really sure if this works. I had a hard time with this one, with the negative numbers. Help is greatly appreciated.
2
u/ninjasquad Sep 19 '13
My python solution:
2
u/[deleted] Sep 19 '13
Very readable Golang solution:
2
u/lethargilistic Sep 19 '13
A C++ solution. I just read about friend functions in my book, so I decided to use one.
2
u/[deleted] Sep 19 '13
A bit long but it does the job
2
u/dante9999 Sep 20 '13
Nice one, here's my try in Python
2
u/Kyrela Sep 20 '13
In VB.NET:
and Partical.vb:
Output (not rounded / formatted because then the value can be put into further calculations): 0.00391205695954933 4324.32432432432
2
u/chunes 1 2 Sep 21 '13
Java:
I took liberties with the input because I am lazy.
2
u/antoniocs Sep 21 '13 edited Sep 21 '13
My solution in C:
2
u/toph83 Sep 21 '13
trying to learn python :)
https://gist.github.com/anonymous/6652173
2
u/Davess1 Sep 22 '13 edited Sep 24 '13
Took forever to make because I suck at vim (python)
2
u/[deleted] Sep 24 '13 edited Sep 24 '13
I did this in python using numpy because I'm stuck on an array problem for a personal project and thought this would get my mind in the zone for it. The first file is the actual code:
Now here's the file it reads from, allowing for easy addition of data by the user (the extra comments regarding format is to help me learn array "grammar"):
Thanks for taking a look! :)
EDIT: Forgot to cut off trailing decimals -- fixed!
2
u/GrandChestnut Sep 25 '13
My verbose Chicken Scheme solution, using simple lists as the data structure for the particles:
2
u/troxxer Sep 26 '13
readable OOP python approach (with input part shamelessly stolen from /u/remram):
2
u/trance_with_me Sep 27 '13
C++. I tried using setprecision from <iomanip> but just wasn't getting consistent results. printf works just fine.
2
u/xToxikx Sep 27 '13
Here's my c++ solution. Could anyone point me in the right direction towards a more OOP approach?
2
u/optimistic_outcome Sep 27 '13
My Implementation in C++
2
u/mahonii Sep 27 '13
First time posting for the dailyprogrammer..practicing in Java..using the sample input I'm getting the wrong calculation? (Feel quite proud enough that I actually nearly done one of these challenges) I also feel that my code could be optimised quite a lot.
public class RepulsionForce {
}
2
u/nightmares_in_wax Sep 27 '13
Python3 solution. Open to suggestions, I couldn't figure out how to make input line shorter/more readable.
2
u/TheQuack45 Sep 27 '13
I'm still not great with Java, so I think this may not seem ideal to some, and I also wasn't able to have the masses, x-positions, and y-positions for each particle be on the same line, but...
Java:
http://pastebin.com/YfKKt0ae
2
u/pisq000 Sep 28 '13
my solution in python
2
u/farmer_jo Sep 28 '13
Ruby solution
2
u/TimeCannotErase Sep 28 '13
Simple R solution:
2
u/skyangelisme 0 1 Sep 29 '13
Python2. Matches the requirement of "minimum 3 decimal places."
2
u/farsidesoul Sep 29 '13
My Ruby solution
2
u/johnnydiamond08 Sep 30 '13
I can't seem to get it to work for the second sample input. Any ideas? Written in C++
2
u/jh1997sa Sep 30 '13
Here's my attempt in C++
2
u/TheFlyingDharma Oct 01 '13
Readable C# solution. I feel like I probably could have got the input and parsed it into floats all on one line instead of four, but I'm not quite sure how. Suggestions welcome!
2
u/Lksaar Oct 01 '13
Wrote it in lua:
Also wrote a solution which uses the data provided by a textfile:
2
u/BERLAUR Oct 01 '13
Not very elegant but here is my beginners Python solution!
2
u/northClan Oct 01 '13 edited Oct 04 '13
My Java Solution
I'm working in a 64 bit environment, so I hope you don't mind that I used doubles instead of floats
I'm so happy to have found this subreddit, it should keep me entertained for quite a while!
Edit: changed instance variables from public to private. Not sure why they were public in the first place.
2
u/[deleted] Oct 02 '13
Basic Java code using Objects.
public class Particles{
2
u/leeman726 Oct 02 '13
First time posting, I would appreciate any feedback, especially on formatting and layout! I'm new to programming as well.
Also, I made my answer as a function, not sure if this is the correct way to go about it.
Python 3.3
2
u/Taunk Oct 03 '13
My first C++ submission. Please critique. I'm trying to form good habits.
2
u/KTheRedditor Oct 03 '13 edited Oct 03 '13
Clojure
2
u/h3ckf1r3 Oct 04 '13 edited Oct 15 '13
Not the prettiest solution, but it was the shortest I could come up with. If anyone has suggestions, I'd love to hear them.
EDIT: oh and it's ruby :)
2
u/dithcdigger Oct 04 '13
c++
2
u/stop_dis Oct 06 '13 edited Oct 06 '13
My first attempt at ruby golf
it currently reads the input from the pipe. I hope that counts, too.
it can be executed like:
any feedback is appreciated.
EDIT: made shorter with this
2
u/bushcat89 Oct 07 '13
Solution using python:
2
u/Meow85 Oct 19 '13 edited Oct 19 '13
A solution in Java:
2
u/godzab Oct 19 '13
}
2
u/Rekvijem Oct 26 '13
Solution in scala:
https://gist.github.com/Catalyst-/7165393
2
u/alabomb Oct 28 '13
Was an amateur/hobbyist programmer in high school and freshmen year of college, haven't touched it in several years. Came across this sub and decided to get back into it! If anyone has any tips/recommendations for my code please feel free to say so. I couldn't figure out how to use Math.sqrt with a float so I went with a double and then float-ified it after the fact.
Java:
And here's the sample output:
2
u/versaceblues Oct 29 '13
Shouldnt this be with charges and not masses? Unless I am missing something
2
u/Nonuplet Nov 01 '13
2
u/[deleted] Nov 02 '13 edited Nov 02 '13
Verbose Java? Verbose Java!
Controller.java
Particle.java
2
u/Hanse00 Nov 03 '13
Simple Python 2.7 solution
2
u/Scenter101 Nov 03 '13 edited Nov 03 '13
My solution in Java
EDIT: Couldn't quite get the formatting down.
2
u/dee_bo Nov 04 '13
Python - I am new to Python and would love feedback on general Python form as well as general programming principles
2
u/[deleted] Nov 04 '13
Ruby. I don't know if my solution is wrong or if there are some weird rounding issues, but the second sample input returns 4324.3243 (instead of the expected 4324.3279).
On GitHub: https://github.com/wildlyinaccurate/r-dailyprogrammer/tree/master/138_easy_repulsionforce
2
u/pirate_platypus Nov 05 '13
I also got the result that doesn't agree with the sample.
Python 2:
2
u/kate_katie_kat Nov 06 '13
Ruby:
2
u/pitkali Nov 07 '13
Playing with some Racket:
2
u/LostxinthexMusic Nov 13 '13
Probably not the best, but a simple Python solution:
2
u/luizpericolo Nov 18 '13
My python submission.
2
u/CountingCats Nov 26 '13
C++ Undergrad Style
2
u/thetdotbearr Nov 29 '13
C++
2
u/Augustus_v2 Dec 09 '13
Well, as a Physics student I cant do what you asked... fine.
Following your equation:
Using Actual Coulombs Law:
I know that Beta Decay is in atoms but.... go along with it... please? I was just having some fun with that and checking charges and masses and positions.
Neutrons are ignored since... why do you need to measure forces between electrons/protons and neutrons? You are just weird... and probably wear shoes with toes and cant survive a raptor attack.
Comment Please! I mean this was relatively easy but any recommendations would be nice! :D
2
u/tet5uo Dec 10 '13 edited Dec 10 '13
Not sure I know what I'm doing when it comes to using math in JS with floating point numbers.
My result matches the test-case for the first example but the decimals are not the same for my results in the second test case.
2
u/chunes 1 2 Dec 11 '13
My first real Golang program:
Feedback is welcome.
2
u/[deleted] Dec 31 '13
C++, any feedback is appreciated:
3
u/ooesili Sep 18 '13
Haskell solution. I stole the printf bit from SweetScientist. Love those monads.
2
u/[deleted] Sep 17 '13
My long (but hopefully readable) C# solution:
2
u/Elite_Monkeys Sep 17 '13
My first C# solution:
2
u/farsidesoul Sep 18 '13
Java - Just starting to try out the challenges, help greatly appreciated for my improvement.
1
u/roddz Oct 08 '13 edited Oct 08 '13
my java
1
u/jimauthors Oct 09 '13
Clojure
1
u/sup_reddit Oct 09 '13
Scala:
1
u/[deleted] Oct 10 '13
Just began programming, and this is my first post! C++:
1
u/ThirdWaveSTEMinism Oct 11 '13
Haskell (kinda cheating as I don't know how to do stuff with command-line args in Haskell yet):
1
u/jhartwell Oct 12 '13
Here is my first attempt in D
I know there isn't exceptions or anything and this is a fragile solution but it is my first attempt using D.
1
u/finsternacht Oct 12 '13 edited Oct 12 '13
Another Python3 solution. I wanted to try operator overloading in python. So I made a tiny Vector class.
1
u/EndlessQuestions101 Oct 12 '13 edited Oct 12 '13
My JAVA soultion, I didn't do the input format listed in the challenge because;
a) I'm super noob
b) It was late
To repent for this lack of input formatting I added the use of the full equation for Coulomb's Law including the permittivity of the medium which the charges are in... And the user cannot enter 0 as one of the charges because that would just give a force of 0.
1
u/MercenaryCoder Oct 13 '13
Python import sys from math import sqrt def particles( *args ): class particle : def init(self, strpx , strpy , strmass): self.px , self.py , self.mass = float(strpx) , float(strpy) , float(strmass) def sub(self, P2): return ( self.px - P2.px, self.py - P2.py) def mul(self, P2): return (self.mass * P2.mass) Plist = [] for arg in args : Plist.append(particle(*arg)) return( Plist )
def E_Force( arg ): if len(arg) == 6 : P = particles(arg[:3] , arg[3:]) Delta = P[0] - P[1] Dist = sqrt(Delta[0]**2 + Delta[1]2) print("the force is %.3f" % float( P[0] * P[1] / Dist2) ) else: print("Wrong number of arguments, you entered %d" % len(arg))
if name == "main": E_Force(sys.argv[1:])
1
u/SensationalJellyfish Oct 14 '13 edited Oct 14 '13
I have just started taking a course in functional programming, so here is my fumbling attempt solving it in OCaml.
Edit: Removed the unnecessary square root.
1
u/davanger Oct 14 '13
First time posting here, trying to learn Ruby right now.
Here's my solution:
1
u/PolloFrio Oct 15 '13
I made mine use an input string instead of raw input.
In python 3,
I just learnt how to use list inside a list so I decided that I'd totally do it like this.
1
u/pbl24 Oct 15 '13
Python, making use of a few lambda.
1
u/[deleted] Oct 15 '13
Python solution
1
u/[deleted] Oct 16 '13
I did coulombs law so much during the last year at school. Some simple F# code, but I feel like It could have been written better.
1
u/killmefirst Oct 16 '13
C:
1
u/hamc17 Oct 16 '13 edited Oct 16 '13
First submission here, my Java solution. Not sure why, but I get a slightly different answer for Sample Input 2...
Also, a question on formatting the input. Using .nextLine() works well when the input is all on the one line, but if the text is separated with both whitespace and new lines, i.e.
1 -5.2 3.8
1 8.7 -4.1
instead of 1 -5.2 3.8 1 8.7 -4.1, how could I process the input the same way with .split() as if there was only whitespace?
Critique is appreciated.
edit: formatting
1
u/martypowell Oct 24 '13
First Time Posting and Working with Ruby. I did not include retrieving the input. Feedback appreciated.
1
u/Elias_The_Thief Oct 28 '13
1
u/aron0405 Oct 28 '13
18 lines of Java:
1
u/Jade__Dragon Dec 09 '13
This is my first real attempt at Java programming. I have some other language experience but that was a few years ago so i am just now picking programming back up. I tried to use constructors to encapsulate the variables but could not seem to either remember or correctly understand how to implement it with the method i was using. Everything works as near as i can tell. Would anyone mind giving me some critique on the code or advice on how i might structure the code to incorporate encapsulation? Thanks.
edit: two words
1
u/lets_see_exhibit_A Sep 18 '13
java solution with input cleansing:
import java.util.Scanner; public class Easy138 {
1
u/vape Sep 19 '13
My Python 3 solution. I wanted to get a feel for classes in Python, so I created a Particle class even though it would have been simpler without it.
1
u/miguelgazela Sep 19 '13
My oop python solution
1
u/relarmane Sep 19 '13
Simple Java solution.
Output 1
Output 2
I had a discrepancy with the second set of data, but it appears that others had the same issue so I am assuming it is a sample issue not my bug.
1
u/kokushozero Sep 22 '13 edited Sep 22 '13
My Java solution - I'm still new to it
1
u/dr_jonez Sep 23 '13
In Java:
1
u/mentalorigami Sep 23 '13
My not so clever Java solution:
1
u/inerg Sep 25 '13
Not my favourite work but I'm sure I'll improve been a year since I was last programming. Formatting is a bit off to get it all hidden
1
u/[deleted] Sep 30 '13
First time posting here, my solution is in Java.