aboutsummaryrefslogtreecommitdiff
path: root/challenge-163/duncan-c-white/pascal/ch-2.pas
blob: f2e2716c4c94725042bdd6543af804b417b633bb (plain)
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
(* 
 * TASK #2 - Summations
 * 
 * GUEST LANGUAGE: THIS IS THE C VERSION OF ch-2.pl, suitable for
 * the Free Pascal compiler.
 *) 

uses sysutils;

const maxints = 256;

type intarray = array [0..maxints-1] of integer;

var debug : boolean;



(* process_args( nel, v );
 *	Process command line arguments,
 *	specifically process the -d flag,
 *	set nel to the number of remaining arguments,
 *	check that all those remaining arguments are +ve numbers,
 *	copy remaining args to a new integer array v.
 *)
procedure process_args( var nel : integer; var v : intarray );

(* note: paramStr(i)); for i in 1 to paramCount() *)

var
	nparams : integer;
	arg : integer;
	i : integer;
	p : string;

begin
	nparams := paramCount();

	arg := 1;
	if (nparams>0) and SameText( paramStr(arg), '-d' ) then
	begin
		debug := true;
		arg := 2;
	end;

	nel := 1+nparams-arg;
	if nel < 2 then
	begin
		writeln( stderr,
			'Usage: summations [-d] list of +ve numbers' );
		halt;
	end;

	if nel > maxints then
	begin
		writeln( stderr,
			'summations too many numbers (max ',
			maxints, ')' );
		halt;
	end;

	if debug then
	begin
		writeln( 'debug: arg', arg, ', nparams=', nparams, ', nel=',
			nel );
	end;

	// elements are in argv[arg..nparams], copy them to v[]

	// check that all remaining arguments are +ve integers,
	// and then copy them to v[]
	for i := arg to nparams do
	begin
		p := paramStr(i);
		if (p[1] < '0') or (p[1] > '9') then
		begin
			writeln( stderr,
				'summations arg ', i,
				' (', p, ') is not a +ve number' );
			halt;
		end;
		v[i-arg] := StrToInt( p );
	end;
end;


procedure main;

var
	nel  : integer;
	v    : intarray;
	r, i : integer;
	pos  : integer;

begin
	debug := false;

	process_args( nel, v );

	r := 1;

	if debug then
	begin
		write( 'row ', r, ':' );
		for i := 0 to nel-1 do
		begin
			write( ' ', v[i] );
		end;
		writeln;
	end;
	while nel > 1 do
	begin
		// shift v array down
		for i := 0 to nel-1 do
		begin
			v[i] := v[i+1];
		end;
		v[nel-1] := -1;
		nel := nel - 1;

		for pos := 1 to nel-1 do
		begin
			v[pos] += v[pos-1];
		end;
		r := r+1;

		if debug then
		begin
			write( 'row ', r, ':' );
			for i := 0 to nel-1 do
			begin
				write( ' ', v[i] );
			end;
			writeln;
		end;
	end;

	writeln( v[0] );

end;


begin
  main;
end.