Thread: dogs chasing cats up trees

  1. #31
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Look again at Itsme86's post (#3 in this thread)

    Use the distance formula: distance = sqrt( (x1-x2)^2 + (y1-y2)^2) )

    Good old Pythagoras!

    Using your sample data I was able to whip up a quick program that spit this out:
    Code:

    Cat is at: (2,2)
    Dog is at: (1,1)
    There are 4 trees: (0,1) (1.5,1.5) (2.5,2.9) (0,0.5)
    The closest tree to the cat is: (1.5,1.5)
    The dog is 1.4142135623731 units from the cat.
    The cat is 0.707106781186548 units from the closest tree.
    The cat will not escape from the dog.

    Since I wrote it in C# because this is the C# forum, but you need to write it in C, I guess there's no harm in posting the code to see how I did it:
    Code:
    (In C#)
        class Program
        {
            struct Point
            {
                double X;
                double Y;
    
                public Point(double x, double y)
                    : this()
                {
                    X = x;
                    Y = y;
                }
    
                public double DistanceFrom(Point other)
                {
                    return Math.Sqrt(Math.Pow(X - other.X, 2) + Math.Pow(Y - other.Y, 2));
                }
    
                public static Point FromLine(string line)
                {
                    string[] parts = line.Split(' ');
                    return new Point(double.Parse(parts[0]), double.Parse(parts[1]));
                }
    
                public override string ToString()
                {
                    return "(" + X + "," + Y + ")";
                }
            }
    
            static void Main(string[] args)
            {
                TextReader reader = new StreamReader("..\\CatAndDog.dat");
    
                Point cat = Point.FromLine(reader.ReadLine());
                Point dog = Point.FromLine(reader.ReadLine());
    
                int numTrees = int.Parse(reader.ReadLine());
                Point[] trees = new Point[numTrees];
                for (int i = 0; i < numTrees; ++i)
                    trees[i] = Point.FromLine(reader.ReadLine());
                reader.Close();
    
                Console.WriteLine("Cat is at: {0}", cat);
                Console.WriteLine("Dog is at: {0}", dog);
                Console.Write("There are {0} trees:", trees.Length);
                foreach (Point tree in trees)
                    Console.Write(" {0}", tree);
                Console.WriteLine();
    
                Point closestTree = trees.OrderBy(t => t.DistanceFrom(cat)).First();
                Console.WriteLine("The closest tree to the cat is: {0}", closestTree);
                Console.WriteLine("The dog is {0} units from the cat.", dog.DistanceFrom(cat));
                Console.WriteLine("The cat is {0} units from the closest tree.", cat.DistanceFrom(closestTree));
                Console.WriteLine("The cat will{0} escape from the dog.", (cat.DistanceFrom(closestTree) * 2 < dog.DistanceFrom(cat)) ? "" : " not");
            }
        }
    Then work to figure out the distance between two points, using the distance formula. That's really the key part to this.

    After that, put the other points (the locations of the cat and trees and dog, into a small array of struct point {int x; int y;}, and find all the distances you need of cat to the trees, to get to the smallest distance.

    You need a little algebra to work with the distance formula, and a little programming skill to get the array of structs, but that's not all that hard. Work it through by hand with a calculator, and you'll see what I mean.

    Once you get the above done, the actual "can the dog catch the cat?" question, is easily answered with
    Distance = rate * time

    and we can help you with that, if you need it.
    Last edited by Adak; 03-26-2011 at 10:05 AM.

  2. #32
    Registered User
    Join Date
    Mar 2011
    Posts
    10
    Code:
    ]int main()
    {
    
    FILE *fp;
    
    if((fp = fopen("CatAndDog.dat","r")) == NULL)
           printf("File could not be opened\n")
                        
           fscanf(fp, "%f %f", &cat_X_coord, &cat_Y_coord);
           fscanf(fp, "%f %f", &dog_X_coord, &dog_Y_coord);
           fscanf(fp, "%d", &number_of_trees);
           
           for (i=0; i<=number_of_trees; i++)
           {
                fscanf(fp, "%f %f", &x, &y);
                XTree [i] = x;
                YTree [i] = y;
                }
     fclose(fp)
    
    
    
        typedef struct {
        double x;
        double y;
        } Point;
        Point catLocation;
        Point dogLocation;
        Point currentTreeLocation;
        int numberOfTrees;
        int currentTreeNumber;
    Thst'd what i have done untill now, can someone make it work?

  3. #33
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by sadam View Post
    Code:
    ]int main()
    {
    
    FILE *fp;
    
    if((fp = fopen("CatAndDog.dat","r")) == NULL)
           printf("File could not be opened\n")
                        
           fscanf(fp, "%f %f", &cat_X_coord, &cat_Y_coord);
           fscanf(fp, "%f %f", &dog_X_coord, &dog_Y_coord);
           fscanf(fp, "%d", &number_of_trees);
           
           for (i=0; i<=number_of_trees; i++)
           {
                fscanf(fp, "%f %f", &x, &y);
                XTree [i] = x;
                YTree [i] = y;
                }
     fclose(fp)
    
    
    
        typedef struct {
        double x;
        double y;
        } Point;
        Point catLocation;
        Point dogLocation;
        Point currentTreeLocation;
        int numberOfTrees;
        int currentTreeNumber;
    Thst'd what i have done untill now, can someone make it work?
    Ummm... that's your problem... don't write crap and then ask us to fix it...

  4. #34
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Start off your program right, with the include files:
    #include <stdio.h>

    for one. Then, you need to include a file to handle the square root. What include file would that probably be?

    Add it.

    Next would be the struct point prototype, so add that.

    Then, int main(void) {

    and inside main() you'll want an int for iterating around the loops - i, and another one to "catch" any return value. Let's make that a float, and call it distance or d maybe.

    Add in the other variables you have, into main() as well. Declare an array of struct point points[6] - are there 4 trees? I've forgotten. Anyway, leave room for the cat and dog.

    Then read in the data from your file, and check that it's good.

    Once you have that, use a for loop to calculate your distances:
    dog to cat:
    cat to tree1:
    ~~~~~through
    cat to tree4;

    which should nicely fit into one single for loop, and using one array (points)

    And you're off to the races.

  5. #35
    Registered User
    Join Date
    Mar 2011
    Posts
    10
    does anyone know how am i able to pick up the closest tree to the cat and show me only that tree??

  6. #36
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    That's not what you want to do - yes, it can be smartly optimized, but that's a higher level of understanding of the math.

    And trust me, you're not there.

    Is this still your program?
    Code:
    int main() 
    {
    
      FILE *fp;
    
      if((fp = fopen("CatAndDog.dat","r")) == NULL) 
           printf("File could not be opened\n")
    
       fscanf(fp, "%f %f", &cat_X_coord, &cat_Y_coord);
       fscanf(fp, "%f %f", &dog_X_coord, &dog_Y_coord);
       fscanf(fp, "%d", &number_of_trees);
           
           for (i=0; i<=number_of_trees; i++)
           {
                fscanf(fp, "%f %f", &x, &y);
                XTree [i] = x;
                YTree [i] = y;
                }
     fclose(fp)
    
    
    
        typedef struct {
        double x;
        double y;
        } Point;
        Point catLocation;
        Point dogLocation;
        Point currentTreeLocation;
        int numberOfTrees;
        int currentTreeNumber;
    let's give it a few tweaks. Same input data from #1 post:
    2.0 2.0 <== cat
    1.0 1.0 <== dog
    4 <== trees
    0.0 1.0
    1.5 1.5
    2.5 2.9
    0.0 0.5

    Code:
     //888888888888888888888888888888888888888888
    
    #include <stdio.h>
    #include <math.h> 
    
    #define MAX 10
    
        typedef struct {
        double x;
        double y;
        } Point;
    
    
    int main() {
      int i;
      double distance = 0.0;
      FILE *fp;
      Point cat;
      Point dog;
      Point tree;
      Point trees[MAX];
      int numberOfTrees;
      
    
      if((fp = fopen("CatNdog.dat","r")) == NULL) {
        printf("File could not be opened\n")
        return 0;
      }                
    
      fscanf(fp, "%f %f", &cat.x, &cat.y);
      fscanf(fp, "%f %f", &dog.x, &dog.y);
      fscanf(fp, "%d", &number_of_trees);
    
      printf("\n\n");       
      for (i=0; i<=number_of_trees; i++)
      {
         fscanf(fp, "%f %f", &trees[i].x, &trees[i].y);
         printf("%lf,  %lf\n", trees[i].x, trees[i].y); //check input
    
         //calculate part will be called or done, here.
    
      }
      fclose(fp)
      printf("\n\n\t\t\t    press enter when ready");
      (void) getchar();
      return 0;
    That's a bit more how I think it should be approached in C. Study that. If you have any code to calculate the distance from cat to tree, post it up.

  7. #37
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    This thread will end with someone doing all the work for him...
    To hell with the board rules right?
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  8. #38
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by Mario F. View Post
    This thread will end with someone doing all the work for him...
    To hell with the board rules right?
    Did Sadam post up code for this, or not? Yes he did.

    Is he stuck on calculating the distances in C and completing this program? Yes, indeed.

    Unlike yourself, I have no idea whether he's not had the benefits of a first rate education, is inexperienced, or just being lazy.

    I have asked you repeatedly for the loan of your crystal ball with the all-knowing eye in it.

    I'm proceeding slowly, so it's no slam-dunk code by 11p.m. kind of thing.

    What do you suggest we do, in this instance?

  9. #39
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    I've seen these types since school. Lazyness is deeply ingrained in me as one of the most detestable traits. What this person is doing, because I do prefer (I will never claim to be a fair person) to see the worst in people like this, is taking advantage of the goodwill of others and bending the board rules by baking half-assed attempts that are nothing more than verbatim copies of previously shown code, and that instantly turn into complete and valid code by someone else. Step by step this lazy arse is getting his way amidst "do it for me" posts.

    But you are probably right. It's none of my business. Happy coding.

    Over and out.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  10. #40
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by Mario F. View Post
    This thread will end with someone doing all the work for him...
    To hell with the board rules right?
    By "someone" you of course mean Adak. He will gleefully provide anyone with the full code to any question they ask, without requiring any effort on their part.
    Quote Originally Posted by Adak View Post
    Did Sadam post up code for this, or not? Yes he did.
    No he didn't! Read the thread!

    Honestly, if it was up to me, I would ban people for doing homework for others. He didn't do anything in this thread. But it doesn't matter, and it doesn't matter how many times we yell at Adak, he's still going to do their entire program for them. Every single time. (Yes, Adak, that means you. I would have perma-banned you the first week you were here, because no matter how many times we tell you to knock it off, you ignore the homework policy, and do everyone's work for them EVERY SINGLE TIME.)


    Quzah.
    Hope is the first step on the road to disappointment.

  11. #41
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    I changed my mind - this thread is the bloated going nowhere thread.

    Further replies and actual help (no spoon-feeding) here please.
    The cats, dogs and trees game
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can you Microwave Regular Hot dogs?
    By Kleid-0 in forum A Brief History of Cprogramming.com
    Replies: 38
    Last Post: 01-11-2005, 01:53 AM
  2. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  3. A Miracle has occurred in the realm of Hot Dogs
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 11
    Last Post: 05-08-2004, 03:18 PM
  4. Cats vs. Dogs
    By LouDu in forum A Brief History of Cprogramming.com
    Replies: 44
    Last Post: 03-14-2003, 09:22 PM

Tags for this Thread