From: Riccardo Cecolin Date: 2010-03-14T01:37:55+09:00 Subject: Re: Newbie Help : Object Jerome David Sallinger wrote: > Hello, > > This question may be more to do with my understanding of OOP that the > actual contructs of Ruby so please be patient with me. > > I am interested in visualizing data so am teaching myself to Programming > using Ruby via computer graphics. I am steadily building up my knowledge > and experience by writing by and executing rudimentary code around the > new thngs I learn. Now I'm stuck so i'll make the question as simple as > I can: > > I create a window of Ball objects based on a Ball class that I have > written. Each Ball object is instantiated at a randon x,y location on > the screen and has random speed. > > Each Ball object is able to reverse its driection (bounce) if it hits > the edge of the window. > > If I have two balls and I want to detect whether they instersect with > each other as they move around the screen this is simple enough; the > ball class has an intersect() method which i can use to pass in a > reference to the other ball object. But what if there are are random > number of balls. How do I make it such that any Ball object would be > aware of the location of any other Ball object without having to resort > to nested for loops where I check the location of each Ball against > every other Ball? > > Any ideas > You could set an array of n "Ball"s, check one against each other element of the array then pop it out and repeat with remaining elements. So the amount of intersect() methods you will call will be \sum_{k=1}^{n-1} k instead of (n-1)*(n). Feel free to correct me if i'm wrong. Riccardo