Jury-rig


Software Engineering, a personal journey

Javascript recursive fraction simplification

Instead of falling back on the usual suspect of for loops to solve my problem I looked through my old lecture notes and thought, "this is a job for recursion"

Oh, sorry I forgot to mention the problem: return all simplified fractions of a proper fraction. It's one of those work problems faced daily and generally answered with iteration, one thing I hear alot about recursion and 'infinite loops' and this is a good reason to pick recursion as it forces a clear test to be produced.
var fractions = {
	arrElement: [],
	arrFractions: [],
	commonDivisor: function (numerator, denominator) {
		//Iteration approach
		var arr = [];
		var res = [];
		for (var count = 0; count < denominator; count++) {
			if (numerator % count == 0 && denominator % count == 0) {
				arr.push(count);
			}
		}
		for (var i = 0; i < arr.length; i++) {
			res.push(numerator / arr[i] + "/" + denominator / arr[i]);
		}
		return res;
	},

	recursiveCall: function (value, numerator, denominator) {
		//recursive approach
		if (value < denominator) {
			if (numerator % value === 0 && denominator % value === 0) {
				fractions.arrElement.push(value);
			}
			return fractions.recursiveCall(value + 1, numerator, denominator);
		} else {
			return fractions.arrElement;
		}
	},

	recursiveResults: function(value, numerator, denominator){
		if (value < fractions.arrElement.length) {
			fractions.arrFractions.push(numerator / fractions.arrElement[value] + "/" + denominator / fractions.arrElement[value]);
			return fractions.recursiveResults(value + 1, numerator, denominator);
		} else {
			return fractions.arrFractions;
		}
	}
};
<br/ > The recursion approach has produced more complex code but it has abstracted the main tasks into two distinct methods which can be used elsewhere.
 


Comments



Have your say

Author:

Comment here (140 chars only)*:

Email address: