- #1

Eus

- 94

- 0

Given an input of 5, it is easy to produce the following pattern:

Code:

```
xxxxx
xx x
x x x
x xx
xxxxx
```

But, given an input of 5, how would you produce the following one?

Code:

```
1 7 14 21
2 8 15 22
3 9 16 23
4 10 17 24
5 11 18 25
```

I have implemented the solution below, but I wonder if there is anyone here that can suggest a better algorithm.

Code:

```
if (input > 2)
{
/*
> input = 5
> output =
1 7
2 8
3 9
3 * (3 - 1) / (3 - 2)
1 7 13
2 8 14
3 9 15
4 10 16
4 * (4 - 1) / (4 - 2) = 6
floor (6) = 6
ceil (6) = 6
.0 -> 6
> 1 7 14 21
> 2 8 15 22
> 3 9 16 23
> 4 10 17 24
> 5 11 18 25
5 * (5 - 1) / (5 - 2) = 6.666...
floor (6.66...) = 6
ceil (6.66...) = 7
.666... > .5 -> 6 7 7
1 8 15 23 31
2 9 16 24 32
3 10 17 25 33
4 11 18 26 34
5 12 19 27 35
6 13 20 28 36
6 * (6 - 1) / (6 - 2) = 7.5
floor (7.5) = 7
ceil (7.5) = 8
.5 == .5 -> 7 7 8 8
1 9 17 25 34 43
2 10 18 26 35 44
3 11 19 27 36 45
4 12 20 28 37 46
5 13 21 29 38 47
6 14 22 30 39 48
7 15 23 31 40 49
7 * (7 - 1) / (7 - 2) = 8.4
floor (8.4) = 8
ceil (8.4) = 9
.4 < .5 -> 8 8 8 9 9
n * (n - 1) / (n - 2) = ?
*/
int i = 0;
int j = 0;
int k = input - 2;
int tmp = 0;
int num_of_digits = log10 (input * input) + 2;
int distance = input * input - input;
double step_size = (double) input * (input - 1) / (input - 2);
int floor_val = floor (step_size);
int ceil_val = ceil (step_size);
int mid_point = 0;
while ((distance - mid_point * floor_val) % ceil_val != 0)
{
++mid_point;
}
for (i = 1; i <= input; i++)
{
printf ("%*d", num_of_digits, i);
for (j = 1, tmp = i; j <= k; j++)
{
if (j <= mid_point)
{
tmp += floor_val;
}
else
{
tmp += ceil_val;
}
printf ("%*d", num_of_digits, tmp);
}
printf ("\n");
}
}
```

Eus