// JavaScript for puzzle 106: Flying cards.

// Multiply two polynomials, held as arrays.
function mul(a, b) {
	var c = new Array(a.length + b.length - 1);
	for (var n = 0; n < c.length; n++) c[n] = 0;
	for (var i = 0; i < a.length; i++)
		for (var j = 0; j < b.length; j++)
			c[i+j] += (a[i] * b[j]);
	return c;
}

// Convert polynomial to string.
function str(a) {
	var res = '';
	for (var i = 0; i < a.length; i++) {
		if (i === 0) {if (a[i] !== 0) res += a[i];}
		else {
			if (a[i] !== 0) {
				res += (a[i] > 0) ? ' + ' : ' - ';
				if (Math.abs(a[i]) != 1) res += Math.abs(a[i]);
				res += 'x';
				if (i > 1) res += ('<sup>' + i + '</sup>');
			}
		}
	}
	return res;
}

// Write remarks and f(x).
function writeF() {
	document.write('<hr><h2 class="h3">Remarks</h2><p>The full expansion of the generating function is given below.&nbsp; So, for example, the <a href="http://mathworld.wolfram.com/Mode.html">mode</a> is total value&nbsp;=&nbsp;182, which can occur in&nbsp;62256518307724 different ways.</p>');

	// Declare generating function factors.
	var p1 = new Array(1, 1), p2 = new Array(1, 0, 1), p3 = new Array(1, 0, 0, 1), p4 = new Array(1, 0, 0, 0, 1), p5 = new Array(1, 0, 0, 0, 0, 1), p6 = new Array(1, 0, 0, 0, 0, 0, 1), p7 = new Array(1, 0, 0, 0, 0, 0, 0, 1), p8 = new Array(1, 0, 0, 0, 0, 0, 0, 0, 1), p9 = new Array(1, 0, 0, 0, 0, 0, 0, 0, 0, 1), p10 = new Array(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1), p11 = new Array(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1), p12 = new Array(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1), p13 = new Array(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);

	// Multiply generating function factors.
	var t1 = mul(p1, p2), t2 = mul(p3, p4), t3 = mul(p5, p6), t4 = mul(p7, p8), t5 = mul(p9, p10), t6 = mul(p11, p12);
	t1 = mul(t1, t2); t3 = mul(t3, t4); t5 = mul(t5, t6); t5 = mul(t5, p13);
	t1 = mul(t1, t3); t1 = mul(t1, t5);
	t1 = mul(t1, t1); t1 = mul(t1, t1);

	// Write expanded generating function.
	document.write('<p>f(x) = ', str(t1), '.</p>');
}