about summary refs log tree commit diff
path: root/others/other/spiral.pas
blob: 819b9b2baa3fdc20aa12f192b00c3284f02cce0b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
uses strutils, sysutils;

const
  direction: array[0..3, 0..1] of int8 = ((0, 1), (1, 0), (0, -1), (-1, 0));

var
  f: text;
  n, i: int32;
  m, x, y: int16;
  d: int8 = 0;
  a: array of array of int32;

function mt(x, y: int16): boolean;
  begin
    if (x < 0) or (y < 0) then
      exit(false);
    if (x >= m) or (y >= n) then
      exit(false);
    if a[x][y] > 0 then
      exit(false);
    mt := true
  end;

begin
  assign(f, 'SPIRAL.INP');
  reset(f);
  readln(f, n);
  for m := trunc(sqrt(n)) downto 1 do
    if n mod m = 0 then
      begin
        n := n div m;
        break
      end;
  close(f);

  setlength(a, m);
  for x := m - 1 downto 0 do
    begin
      setlength(a[x], n);
      for y := n - 1 downto 0 do
        a[x][y] := 0
    end;

  for i := 1 to m * n do
    begin
      a[x][y] := i;
      if not mt(x + direction[d][0], y + direction[d][1]) then
        d := succ(d) mod 4;
      inc(x, direction[d][0]);
      inc(y, direction[d][1])
    end;

  assign(f, 'SPIRAL.OUT');
  rewrite(f);
  d := length(inttostr(m * n));
  for x := 0 to m - 1 do
    begin
      for y := 0 to n - 2 do
        write(f, padleft(inttostr(a[x][y]), d), ' ');
      writeln(f, padleft(inttostr(a[x][n - 1]), d))
    end;
  close(f)
end.