Mike Griffiths

Tag: problem

An Interesting Problem

by Mike on May.07, 2009, under Web Development

Myself and another developer have begun work on a new project that will integrate into Twitter. It’s quite a novel idea and I’m very surprised it hasn’t been done already, but there will be more on that once it’s ready for public use.

But enough on that, this post is about a problem we came across when building it. Basically we wanted to create a block of 100 cells, each numbered, but the rows are to go in a zigzag fashion, starting in the bottom left at 0 and ending in top left with 100, and obviously this isn’t to be done manually. Find an example below:

100 99 98 97 96 95 94 93 92 91
81 82 83 84 85 86 87 88 89 90
80 79 78 77 76 75 74 73 72 71
61 62 63 64 65 66 67 68 69 70
60 59 58 57 56 55 54 53 52 51
41 42 43 44 45 46 47 48 49 50
40 39 38 37 36 35 34 33 32 31
21 22 23 24 25 26 27 28 29 30
20 19 18 17 16 15 14 13 12 11
1 2 3 4 5 6 7 8 9 10

Here is what I came up with (PHP):

$i=99;
for ($x = 100; $x > 0; $x--)
{
        echo $x . ' ';
        if($i%10==0) {
                // Display new line
                echo "\n";
                // Loop through 10
                for($y = ($x-10); $y < ($x); $y++){
                        echo $y . ' ';
                        if($y%10==0) echo "\n";
                }
                // Add ten onto $x and $i
                $x = $x-10;
                $i = $i-10;
        }
        $i--;
}

Although this is relatively efficient, I'm sure there must be a better way of doing it. Any ideas? Leave a comment.

11 Comments :, more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post.