Mike Hildner - 4 months ago 43

C# Question

I've got a number of controls (charts in this case) that's determined at runtime. I'd like to put these in a grid with the proper number of rows and columns. For example,

- 4 items = 2 x 2
- 8 items = 4 x 2
- 9 items = 3 x 3
- 20 items = 5 x 4
- 11 items = 4 x 3 (I don't care about an empty cell)

Sorry, I don't really have any code to show my attempts. I started playing with determining if the square root is an integer, if the number is evenly divisible by 2 etc. and realized I'm not sure how to attack this problem. But this is what I'm thinking:

- If the square root is an integer, use the square root for the number of rows and columns (no problems there)
- If not, make sure the number is even (add one if you have to - no problems there)
- Find the highest two integers that produce the number. e.g. If I have 20 controls, the grid should be 5 x 4 and not 10 x 2 (not really sure the best way for this)

I'd appreciate it if someone could point me in the right direction - or suggest a different algorithm if I'm way off base.

Answer

Idea: If square root is not integer, floor it, then divide whole number by this, ceil it.

```
int columns = (int)sqrt(number);
int lines = (int)ceil(number / (float)columns);
```

Example: 21 => columns = 4, lines = 6.

UPDATE: bonus, it also works when sqrt(number) is integer. No rounding occurs anywhere, and values are correct.