The Cube

You just watched the movie ’Cube’ before going to bed. Bad idea – you find yourself in a nightmare where you are also put in a huge cube which has 6 doors. But fortunately you remember an idea from the film about how each of the doors has a numeric code. If decoded correctly it tells you if there is a deadly trap behind it or not.

You read the first code 28733 13412 96476 – and remember that one had to add the digits of each group together (e.g. 2+8+7+3+3 = 23) and test if at least one of the 3 check sums is a prime number. If it is, there is a deadly trap!

Coding Kata

<!DOCTYPE html>
<html>
<head>
	<meta charset=utf-8 />
	<title></title>
	<link rel="stylesheet" type="text/css" media="screen" href="master.css" />
	<script type="text/javascript" src="jquery.min.js"></script>
	<!--[if IE]>
		<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
	<![endif]-->
	<script type="text/javascript">
		function isPrime(text){
			var e = text.split(',');
			for (var i=0; i<text.length; i++){
				var num = 0;
				for (pos = 0; pos < text[i].length; pos++) {
					num = num + parseInt(text[i].charAt (pos))
				}

				console.info("Testing %i, the sum of digits %s.", num, text[i]);

				if (num == 1 || num == 2) {
					console.info("%i, the sum of digits %s, is prime!.", num, text[i]);
					return true;
				}
				for (var divisor = 3; divisor < num; divisor++) {
					if (num % divisor == 0) {
					console.info("%i, the sum of digits %s, is prime!.", num, text[i]);
						return true;
					}
					else {
						console.info(num + ", the sum of digits " + text[i] + ", is not prime.  It is divisible by " + divisor + ".");
						break;
					}
				}
			}
			return false;
		}

		function isTrap(text){
			if(isPrime(text)){
				trap.play();
				return "It's a Trap!";
			}
		    return  "It's safe!";
		}
	</script>
</head>
<body>
	<form>
		<div class="box">
			<h1>Add and Prime</h1>
            <label>
            	<span>Please enter first number</span>
               	<input type="text" class="input_text" id="number1"/>
			</label>
			<label>
               	<span>Tada</span>
               	<input type="text" class="input_text" id="result1"/>
            <label>
				<input type="button" value="Calculate" onclick="$('#result1').val(isTrap($('#number1').val()))">
            </label>
 		</div>
		<audio id="trap" src="itsatrap.mp3">
			Your browser does not support the audio element.
		</audio>
</body>
</html>
  1. No comments yet.

  1. No trackbacks yet.