User Tools

Site Tools


λ Reversing an array - recursive

======= Algorithm ======= <syntax js> function reverseArray(a) { var reversed; if (a.length === 0) { reversed = []; } else { reversed = reverseArray(a.slice(1)); reversed.push(a[0]); } return reversed; }</syntax> ======= Support ======= <syntax js> function run(input) { result = reverseArray(input); }</syntax> ======= Tests ======= <syntax js> // Test by splitting to an array and then joining back to a string. function testTest() { assert(reverseArray("test".split("")).join("") === "tset"); } function testHello() { assert(reverseArray("hello".split("")).join("") === "olleh"); } function testLong() { assert(reverseArray("By editing this page you agree to license".split("")).join("") === "esnecil ot eerga uoy egap siht gnitide yB"); } function testNothing() { assert(reverseArray("".split("")).join("") === ""); } function testA() { assert(reverseArray("A".split("")).join("") === "A"); }</syntax> ======= Options ======= <syntax js> { "title":"Reversing an array - recursive", "height":"200px" }</syntax> ======= Visualisation ======= <syntax html> <html> <head> <style type="text/css"> input {width:100px;} body {font-family:monospace} #start {color:blue; text-decoration:underline} </style> <script type="text/javascript"> function update(n, x) { var element = document.getElementById("result"); var a = x.lookupInScope("a"); var i = x.lookupInScope("i"); var temp = x.lookupInScope("temp"); var result = x.lookupInScope("result"); element.innerHTML = ""; var stringArray = ""; for (var i=x.stack.length-1; i>=0; i--) { var a = x.stack[i].lookupInScope("a"); var r = x.stack[i].lookupInScope("reversed"); if (r && r.length === a.length) { var spacer = ""; for (var s=0;s<=i;s++) spacer += "&nbsp;"; stringArray = spacer + r.join("") + "<br>" + stringArray; } else if (r) { var spacer = ""; for (var s=0;s<=i;s++) spacer += "&nbsp;"; stringArray = spacer + r.join("") + "&nbsp;&nbsp;&nbsp;+ "+a[0]+"<br>" + stringArray; } else if (a && a.length > 0) { var spacer = ""; for (var s=0;s<i;s++) spacer += "&nbsp;"; stringArray = spacer + "R(" + a.slice(1).join("") + ") + "+a[0]+"<br>" + stringArray; } } element.innerHTML += stringArray+"<br>"; } function args() { var input = document.getElementById('input').value.split(""); return input; } function reverse() { reset(); } </script> </head> <body> <input id="input" value="Algorithms"> <button id="reverse" onclick="reverse()">Reverse</button> <div id="result"></div> </body> </html></syntax>

algorithm/reverse_an_array_-_recursive.txt · Last modified: 2015/02/03 01:04 by will