// JavaScript for puzzle 104: An arbitrary sum.

// Generate random integer in the range lo..hi.
function rnd(lo, hi) {
	return lo + Math.floor(Math.random() * (hi - lo + 1));
}

// Numeric sort comparison.
function compareNum(a,b) {
	return a - b;
}

// Generate sequences and write table.
function genSeq() {

	// Generate random sequence a(i) for random n in range 2..20.
	var n = rnd(2,20), a = new Array(2*n+1);
	for (var i = 0; i < a.length; i++) a[i] = -i;
	i = 0;
	while (i < n) {
		var s = rnd(1,2*n);
		if (a[s] < 0) {a[s] = s; i++;}
	}
	a.sort(compareNum);

	// Write preamble.
	document.write('<p>The table below is generated at random, in two stages.&nbsp; Firstly, a value of n in the range 2..20 is chosen at random.&nbsp; Then, n numbers in the range 1..2n are chosen at random.&nbsp; These numbers are sorted to form the sequence a<sub>i</sub>; the remaining numbers are sorted to form the sequence b<sub>i</sub>.&nbsp; For each i, the value <span class="u"><span class="dn">|</span>a<sub>i</sub> &minus; b<sub>i</sub><span class="dn">|</span></span> is calculated, and the sum is given.</p>');
	document.write('<p>Use the button to regenerate the random table as many times as you like.&nbsp; Use the table to formulate a conjecture about each pair, (a<sub>i</sub>,&nbsp;b<sub>i</sub>.)&nbsp; Prove your conjecture, and hence find the value of the sum.</p>');
	document.write('<form><button type="button" onclick="history.go(0);">Regenerate table</button></form>');

	// Write table showing a(i), b(i), |a(i) - b(i)|, and sum.
	document.write('<table summary="a, b for n = ', n, '" border="2" cellspacing="0" cellpadding="3"><caption>n = ', n, '</caption><thead align="right"><tr><th scope="col" width="25%">a<sub>i</sub></th><th scope="col" width="25%">b<sub>i</sub></th><th scope="col" width="50%"><span class="dn">|</span>a<sub>i</sub> &minus; b<sub>i</sub><span class="dn">|</span></th></tr><tbody align="right">');
	for (i = 0; i < n; i++)
		document.write("<tr><td", (a[i+n+1] <= n) ? ' class="dc">' : '>', a[i+n+1], "</td><td", (-a[i] <= n) ? ' class="dc">' : '>', -a[i], "</td><td>", Math.abs(a[i+n+1] + a[i]), "</td></tr>");
	document.write('<tr><td colspan="2">Sum:</td><td>', n*n, "</td></tr></tbody></table>");
}
