5

So I have a float[,] heightmap, and as part of my river generating algorithm I want to select two points so long as they are part of one of the edges of the array. This seems a simple task, but I can't seem to come up with a solution that doesn't involve way too many if statements. Is there a way to select from the edges of a 2d array? (IE, x = 0 or x = max, or y = 0 or y = max)

t1w
  • 1,408
  • 5
  • 25
  • 51
  • Do you want a random point? – JasonD Dec 30 '12 at 19:36
  • 2
    How many is way too many? – Matti Virkkunen Dec 30 '12 at 19:37
  • Any random point so long as its on one of the edges. EDIT: I'm going to be choosing two total points, if that's relevant. – user1938413 Dec 30 '12 at 19:39
  • You could do with a single `switch` statement. – John Dvorak Dec 30 '12 at 19:41
  • What's a total point? You mean you will only ever select two points and not more? – John Dvorak Dec 30 '12 at 19:42
  • No I meant two in all, for use with the algorithm... but I don't think that's relevant anyway. A switch statement would work, I'm not sure what I was hoping for. – user1938413 Dec 30 '12 at 19:45
  • Are you looking for performance or nice programing style? – Felix K. Dec 30 '12 at 19:49
  • Nice style mainly, I don't think performance is that big an issue considering this operation will only be performed twice and then forgotten about. But I think your solution seems an elegant as well as reusable one. – user1938413 Dec 30 '12 at 19:53
  • I would advice, i did something like this a while ago ( http://stackoverflow.com/questions/9140877/calculating-normals-between-2-meshes-ending-up-in-seams ), to create a class for this. I ended up doing it after several tries to get the nicest solution. – Felix K. Dec 30 '12 at 19:55

2 Answers2

2

You could make a array with all edge-indicies like (0,10) and put all of them in one array, now you could simply select one or more of them.

Felix K.
  • 5,963
  • 2
  • 33
  • 67
  • One thing which isn't related to the question: You archive better results on random if you stretch the random range to N times of the array length and use modulo to get a point in range. I normaly use 7 as multipicator. – Felix K. Dec 30 '12 at 19:44
2

Just for novelty, here's a way of doing it which doesn't involve storing all the indices, or any if() blocks:

    static void randPoint(int width, int height, out int x, out int y, Random r)
    {
        int[] dim = {width,height};
        int[] res = new int[2];

        res[0] = r.Next(0, 2) * (width - 1);
        res[1] = r.Next(0, 2) * (height - 1);
        int hv = r.Next(0, 2);
        res[hv] = r.Next(0,dim[hv]);

        x = res[0];
        y = res[1];
    }
JasonD
  • 15,840
  • 2
  • 28
  • 42