Implementing slide puzzle using Javascript - javascript

First off, thank you for reading this question. With this javascript code, I'm trying to implement a 4x4 slide number puzzle, which looks like this when completed. :
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 [blank]
Each number are represented by .gif number files which are on the same folder where this HTML file is.
When a user clicks "START" button below the puzzle, it shuffles pieces by repetitively swapping randomly chosen two pieces. (shuffle function)
When a user clicks a piece adjacent to the blank piece then it swaps the two. (movePiece function)
But the problem is when I click the START button and the piece adjacent to the blank piece, nothing happens.. even though except for this code's logic and algorithm is not different from the answer that my instructor's given and I can't find where is causing this problem.
Can anyone help me find out where is wrong with this code?
Any advice would be much appreciated.
<html>
<head>
<title>15 Puzzle Game</title>
<meta name="generator" content="Microsoft FrontPage 4.0" charset="UTF-8">
<script language="JavaScript">
var completed=true;
function tokenize(sep,str){
tokens = new Array();
i=0;
while(1)
{
idx=str.indexOf(sep);
if(idx == -1)
{
if(str.length>0)
{
tokens[i]=str;
}
break;
}
tokens[i++]=str.substring(0,idx);
str=str.substr(idx+1);
}
return tokens;
}
function getX(idx)
{
var rest=idx-Math.floor(idx/4)*4;
return (rest==0)?4:rest;
}
function getY(idx)
{
return Math.floor((idx-1)/4)+1;
}
function getIndex(x,y)
{
return x+(y-1)*4;
}
function newDirection(pos)
{
var dir;
if ((pos==2)||(pos==3)) dir=(Math.floor(Math.random()+0.5)==0)?-1:1;
else dir=(pos==1)?1:-1;
return (pos+dir);
}
function newIndex(idx)
{
var x,y;
x=getX(idx);
y=getY(idx);
if (Math.floor(Math.random()+0.5)==0) x=newDirection(x);
else y=newDirection(y);
return getIndex(x,y);
}
function isComplete()
{
if(completed) return 0;
for(var i = 1; i <= document.images.length; i++){
if(document.images[i-1].src != i+".gif") return 0;
}
return 1;
}
function getNum(idx){
var index = idx - 1;
var token[] = tokenize("/",document.images[index].src);
var numOfTokens = tokenize("/",document.images[index].src).length;
var num = tokenize(".", token[numOfTokens-1])[0];
return Number(num);
}
function shuffle()
{
var puzzles=new Array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
iter=Math.floor(Math.random()*200+0.5)+100;
for (i=0;i<iter;i++)
{
var ranNum = Math.floor(Math.random()*16)+1;
var newNum = newIndex(ranNum);
var temp = puzzles[ranNum-1];
puzzles[ranNum-1] = puzzles[newNum-1];
puzzles[newNum-1] = temp;
}
}
for(i=1;i<document.images.length+1;i++){
document.images[i-1].src = ""+puzzles[i-1]+".gif";
}
completed = false;
}
function movePiece(idx)
{
x = getX(idx);
y = getY(idx);
var flag = 0;
var tempIdx;
for(i=-1; i<=1 ; i=i+2){
if ((x==2)||(x==3)) dir=i;
else dir=(x==1)?1:-1;
var tmpx= (x+dir);
tempIdx = getIndex(tmpx,y);
if(getNum(tempIdx) == 16){ flag = 1; midx=tempIdx; }
}
for(i=-1; i<=1 ; i=i+2){
if ((y==2)||(y==3)) dir=i;
else dir=(y==1)?1:-1;
var tmpy= (y+dir);
tempIdx = getIndex(x,y);
if(getNum(tempIdx) == 16){ flag = 1; midx=tempIdx; }
}
if (flag == 1){
document.images[midx-1].src = document.images[idx-1].src;
document.images[idx-1].src = "16.gif";
}
if(isComplete()) alert('Congratulation!');
completed = true;
}
</script>
</head>
<body bgcolor="silver" text="black" link="#0000EE" vlink="#551A8B" alink="red">
<h2 align="center">
15 Puzzle</h2>
<div align="center">
<table border>
<tr>
<td width="50%" align="center">
<script language="JavaScript">
with(window.document)
{
open();
writeln('<table border=1 cellpadding=0 cellspacing=1>');
for(var i=1;i<17;i++)
{
if(i==1 || i==5 || i==9 || i==13 )
{
writeln('<tr>');
}
writeln(' <td width=49 height=49>');
writeln(' <a href=JavaScript:movePiece('+i+');>');
writeln(' <img src=',i,'.gif border=0 width=49 height=49 name=i',i,'></a>');
writeln(' </td>');
if(i==4 || i==8 || i==12 || i==16 )
{
writeln('</tr>');
}
}
writeln('</table>');
close();
}
</script>
</td>
</tr>
</table>
</div>
<p align="center">
<br>
</p>
<form method="get">
<p align="center">
<input type="button" value="START" onClick="shuffle()"></p>
</form>
</body>
</html>
javascript
and this is working code
<html>
<head>
<title>15 Puzzle Game</title>
<meta charset="UTF-8">
<script language="JavaScript">
var completed=true;
function tokenize(sep,str)
{
tokens = new Array();
i=0;
while(1)
{
idx=str.indexOf(sep);
if(idx == -1)
{
if(str.length>0)
{
tokens[i]=str;
}
break;
}
tokens[i++]=str.substring(0,idx);
str=str.substr(idx+1);
}
return tokens;
}
function getX(idx)
{
var rest=idx-Math.floor(idx/4)*4;
return (rest==0)?4:rest;
}
function getY(idx)
{
return Math.floor((idx-1)/4)+1;
}
function getIndex(x,y)
{
return x+(y-1)*4;
}
function newDirection(pos)
{
var dir;
if ((pos==2)||(pos==3)) dir=(Math.floor(Math.random()+0.5)==0)?-1:1;
else dir=(pos==1)?1:-1;
return (pos+dir);
}
function newIndex(idx)
{
var x,y;
x=getX(idx);
y=getY(idx);
if (Math.floor(Math.random()+0.5)==0) x=newDirection(x);
else y=newDirection(y);
return getIndex(x,y);
}
function isComplete() {
if(completed)
return false;
var prev = getPiece(1);
for(var i = 2; i < 17; i++) {
var current = getPiece(i);
if(current != prev+1)
return false;
prev = current;
}
return true;
}
function shuffle()
{
var puzzles=new Array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
iter=Math.floor(Math.random()*200+0.5)+100;
var blank = 15;
for (i=0; i<iter; i++)
{
var move = newIndex(blank+1)-1;
var t = puzzles[blank];
puzzles[blank] = puzzles[move];
puzzles[move] = t;
blank = move;
}
for(i = 0; i < 16; i++)
document.images[i].src = ""+puzzles[i]+".gif";
completed = false;
}
function movePiece(idx)
{
var current = getPiece(idx);
if(current == 16)
return;
var x = getX(idx);
var y = getY(idx);
var flag=false, midx=idx;
var dx = [0, 0, -1, 1], dy = [-1, 1, 0, 0];
for(var i = 0; i < 4; i++) {
if(1 <= x+dx[i] && x+dx[i] <= 4 && 1 <= y+dy[i] && y+dy[i] <= 4) {
if(getPiece(getIndex(x+dx[i], y+dy[i])) == 16) {
flag = true;
midx = getIndex(x+dx[i], y+dy[i]);
break;
}
}
}
if(flag) {
var t = document.images[idx-1].src;
document.images[idx-1].src = document.images[midx-1].src;
document.images[midx-1].src = t;
}
if(isComplete()) {
alert("Congratulation!");
completed = true;
}
}
function getPiece(idx) {
idx--;
var len = tokenize("/", document.images[idx].src).length;
return Number(tokenize(".", tokenize("/", document.images[idx].src)[len-1])[0]);
}
</script>
</head>
<body bgcolor="silver" text="black" link="#0000EE" vlink="#551A8B" alink="red">
<h2 align="center">
15 Puzzle</h2>
<div align="center">
<table border>
<tr>
<td width="50%" align="center">
<script language="JavaScript">
with(window.document)
{
open();
writeln('<table border=1 cellpadding=0 cellspacing=1>');
for(var i=1;i<17;i++)
{
if(i==1 || i==5 || i==9 || i==13 )
{
writeln('<tr>');
}
writeln(' <td width=49 height=49>');
writeln(' <a href=JavaScript:movePiece('+i+');>');
writeln(' <img src=',i,'.gif border=0 width=49 height=49 name=i',i,'></a>');
writeln(' </td>');
if(i==4 || i==8 || i==12 || i==16 )
{
writeln('</tr>');
}
}
writeln('</table>');
close();
}
</script>
</td>
</tr>
</table>
</div>
<p align="center">
<br>
</p>
<form method="get">
<p align="center">
<input type="button" value="START" onClick="shuffle()"></p>
</form>
</body>
</html>

The code you provided isn't a good read, so I've created my own version in React. I hope it'll help you to figure things out or at least inspire you to learn React.
https://codesandbox.io/s/wq8n9k5jr7

Related

JavaScript not further executed once a button is disabled

I am using next and prev buttons so one question will be shown at a time, however, once next or prev buttons are disabled, the other button doesn't work anymore either. Here's my code:
var showing = [1, 0, 0, 0];
var questions = ['q0', 'q1', 'q2', 'q3'];
function next() {
var qElems = [];
for (var i = 0; i < questions.length; i++) {
qElems.push(document.getElementById(questions[i]));
}
for (var i = 0; i <= showing.length; i++) {
if (showing[i] == 1) {
showing[i] = 0;
if (i == showing.length - 1) {
document.getElementById("next").disabled = true;
} else {
console.log(i);
qElems[i + 1].style.display = 'block';
qElems[i].style.display = 'none';
showing[i + 1] = 1;
}
break;
}
}
}
function prev() {
var qElems = [];
for (var i = 0; i < questions.length; i++) {
qElems.push(document.getElementById(questions[i]));
}
for (var i = 0; i <= showing.length; i++) {
if (showing[i] == 1) {
showing[i] = 0;
if (i == showing.length - 4) {
document.getElementById("prev").disabled = true;
} else {
qElems[i - 1].style.display = 'block';
qElems[i].style.display = 'none';
showing[i - 1] = 1;
}
break;
}
}
}
I think you want this simplified script
I had to guess the HTML, but there is only one function.
window.addEventListener("load", function() {
let showing = 0;
const questions = document.querySelectorAll(".q");
questions[showing].style.display = "block";
const next = document.getElementById("next");
const prev = document.getElementById("prev");
document.getElementById("nav").addEventListener("click", function(e) {
var but = e.target, dir;
if (but.id === "prev") dir = -1;
else if (but.id === "next") dir = 1;
else return; // not a button
questions[showing].style.display = "none"; // hide current
showing += dir; // up or down
next.disabled = showing === questions.length-1;
if (showing <= 0) showing = 0;
prev.disabled = showing === 0
questions[showing].style.display = "block";
})
})
.q { display:none }
<div class="q" id="q0">Question 0</div>
<hr/>
<div class="q" id="q1">Question 1</div>
<hr/>
<div class="q" id="q2">Question 2</div>
<hr/>
<div class="q" id="q3">Question 3</div>
<hr/>
<div id="nav">
<button type="button" id="prev" disabled>Prev</button>
<button type="button" id="next">Next</button>
</div>
Since this is a quiet interesting java script task, Im doing my own solution.
Hope this matches the requirement.
I have created 4 divs of which first one is only displayed at first. Remaining divs are placed hidden. On clicking next, the divs are displayed according to index. Once the last and first indexes are interpreted, the respective next and previous buttons are enabled and disabled.
var showing = [1, 0, 0, 0];
var questions = ['q0', 'q1', 'q2', 'q3'];
var qElems = [];
function initialize() {
for (var i = 0; i < questions.length; i++) {
qElems.push(document.getElementById(questions[i]));
}
}
function updatevisibilitystatus(showindex, hideindex) {
qElems[showindex].style.display = 'block';
qElems[hideindex].style.display = 'none';
showing[showindex] = 1;
}
function next() {
for (var i = 0; i <= showing.length; i++) {
if (showing[i] == 1) {
showing[i] = 0;
if (i == showing.length - 2) {
document.getElementById("next").disabled = true;
}
updatevisibilitystatus(i + 1, i);
document.getElementById("prev").disabled = false;
break;
}
}
}
function prev() {
for (var i = 0; i <= showing.length; i++) {
if (showing[i] == 1) {
showing[i] = 0;
if (i == 1) {
document.getElementById("prev").disabled = true;
}
updatevisibilitystatus(i - 1, i);
document.getElementById("next").disabled = false;
break;
}
}
}
<body onload="initialize()">
<div id="q0" style="display: block;">Q0</div>
<div id="q1" style="display: none;">Q1</div>
<div id="q2" style="display: none;">Q2</div>
<div id="q3" style="display: none;">Q3</div>
<button id="prev" disabled onclick="prev()">Prev</button>
<button id="next" onclick="next()">Next</button>
</body>

JavaScript If Else errors

So I have this little problem with my if else structure. When I put in a correct star for example "Vega", the costellation shows me that it is false ("Error") while it needs to show me "Lyra".
My code is below:
var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var costellations = ["Ursu Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];
function Arrays() {
for (n = 0; n < 7; ++n) {
if (test.inputStars.value == stars[n]) {
test.inputCostellations.value = costellations[n];
}else{
test.inputCostellations.value = "Error";
}
}
}
<!DOCTYPE html>
<html>
<head>
<title> Array structures</title>
</head>
<body>
<form name = "test">
<input type = "text" name = "inputStars">
<input type = "button" onclick ="Arrays()" value = "Find costellation">
<input type = "text" name = "inputCostellations">
</form>
</body>
</html>
The problem is, when the for loop is running, the test.inputConstellations.value will be overridden, even if previously the program found a match. The solution is the break:
if(test.inputStars.value==stars[n]){
test.inputConstellations.value=constellations[n]
break
}else{
test.inputCostellations.value = "Error"
}
var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var costellations = ["Ursu Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];
function Arrays() {
for (n = 0; n < 7; ++n) {
if (test.inputStars.value == stars[n]) {
test.inputCostellations.value = costellations[n];
break
}else{
test.inputCostellations.value = "Error";
}
}
}
<!DOCTYPE html>
<html>
<head>
<title> Array structures</title>
</head>
<body>
<form name = "test">
<input type = "text" name = "inputStars">
<input type = "button" onclick ="Arrays()" value = "Find costellation">
<input type = "text" name = "inputCostellations">
</form>
</body>
</html>
You can set a default value for variable and overwrite when true:
var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var costellations = ["Ursu Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];
function Arrays() {
test.inputCostellations.value = "Error";
for (n = 0; n < 7; ++n) {
if (test.inputStars.value == stars[n]) {
test.inputCostellations.value = costellations[n];
}
}
}
And use a break:
var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var costellations = ["Ursu Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];
function Arrays() {
test.inputCostellations.value = "Error";
for (n = 0; n < 7; ++n) {
if (test.inputStars.value == stars[n]) {
test.inputCostellations.value = costellations[n];
break;
}
}
}

code that displays words, JS Jquery

Code Link: http://jsbin.com/lozifokuzi/1/edit?html,js,output should display 16 words but it displays only 15 words (The words written in Hebrew).
The code is written in languages ​​JavaScript and jQuery.
$(document).ready(function () {
// creat array of objects, DetermineIDs
var words = new Array(16);
for (var i = 0; i < words.length; i++) {
words[i] = new Object();
words[i].id = i + 1;
}
//insert into objects words
words[0].word = "קוף";
words[1].word = "קוף";
words[2].word = "אריה";
words[3].word = "אריה";
words[4].word = "נמר";
words[5].word = "נמר";
words[6].word = "טלפון";
words[7].word = "טלפון";
words[8].word = "מחשב";
words[9].word = "מחשב";
words[10].word = "מקלדת";
words[11].word = "מקלדת";
words[12].word = "אוגר";
words[13].word = "אוגר";
words[14].word = "עכבר";
words[15].word = "עכבר";
//Determine locations
var ret=Random(loc);
var random = 0;
for (var i = 0; i < words.length; i++) {
words[i].loca=ret[0];
loc=ret[1];
ret = Random(loc);
}
//write the words
for (var i = 0; i < 16; i++) {
$("#c" + (words[i].loca)).html(words[i].word);
}
});
function RandomC(ezer, random) {
for (var i = 0; i <= 16; i++) {
if (ezer[i] == random) {
return true;
}
}
return false;
}
function Random(lq) {
var ezer = new Array(16);
for (var i = 0; i < 16; i++) {
ezer[i] = lq[i];
}
var random = 0;
while ((random < 1 || random > 17) || RandomC(ezer, random)) {
random = parseInt(Math.random() * 100);
}
for (var i = 0; i < lq.length; i++) {
if (lq[i] == null) {
ezer[i] = random;
break;
}
}
var arr = new Array(2);
arr[0] = random;
arr[1] = ezer;
return arr;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<title></title>
</head>
<body>
<article>
<div id="l1">
<p id="c1"></p>
<p id ="c2"></p>
<p id="c3"></p>
<p id="c4"></p>
</div>
<div id="l2">
<p id="c5"></p>
<p id="c6"></p>
<p id="c7"></p>
<p id="c8"></p>
</div>
<div id="l3">
<p id="c9"></p>
<p id="c10"></p>
<p id="c11"></p>
<p id="c12"></p>
</div>
<div id="l4">
<p id="c13"></p>
<p id="c14"></p>
<p id="c15"></p>
<p id="c16"></p>
</div>
</article>
</body>
</html>
Can anyone help?
You have 17 in funciton Random() while loop:
while ((random < 1 || random > 17) || RandomC(ezer, random))
{
random = parseInt(Math.random() * 100);
}
make it 16:
while ((random < 1 || random > 16) || RandomC(ezer, random))
{
random = parseInt(Math.random() * 100);
}
You problem is that you have 16 element from 1 to 16, and your random function gives 16 random numbers from 1 to 17, in case returned range has number 17 it lacks something from 1 to 16, which means your p element of that nubmer doesn't get filled with content.

slideUp() all the elements but not the selected ones

All I want to do is:
there are 7 numbers and 7 divs, they are linked to each other (nr 0 it's in a relationship with div 0)
when one of the numbers is clicked, it should collapse all the other divs which are not selected
it can be selected more at one time
To sum up, basically, the page has some labels with numbers and 7 divs which are all displayed by default (the divs), but when one or more of them are chosen by clicking on the numbers, the page should display only the chosen divs.
This is what I've been trying to do:
for(var i = 0; i <= 6; i++) {
if(i != (floors[i])) {
$("#lvl" + floors[i]).slideUp();
}
}
More code:
http://jsfiddle.net/LSjg4/
Try
var floors = [];
var $lvls = $('.lvl'), $nrs = $(".nr");
$nrs.click(function () {
var $nr = $(this), index = $nrs.index($nr), $lvl = $lvls.eq(index);
$lvl.add($nr).toggleClass('active');
if($nr.hasClass('active')){
$lvls.not('.active').slideUp();
$lvl.slideDown();
$nr.css("background-color", "#1b7664");
$nr.css("border-color", "#236959");
floors.push(($nr).text());
} else {
$nr.css("background-color", "#02c099");
$nr.css("border-color", "#13a480");
if($nrs.filter('.active').length == 0){
$lvls.slideDown();
} else {
$lvls.not('.active').slideUp();
}
var text = $nr.text();
floors.splice($.inArray(text, floors), 1);
}
console.log('floors', JSON.stringify(floors))
});
Demo: Fiddle
I corrected a few things in your code. Here is the below working code and link to it in jsfiddle.
There was a data type mismatch(comparing string and int). When matching whether it exists in floors array, the code was checking floors[i] only whereas the i can be any position in floors.
var floors = [];
$(".nr").click(function () {
var state = $(this).data('state');
state = !state;
if (state) {
$(this).css("background-color", "#1b7664");
$(this).css("border-color", "#236959");
floors.push(parseInt($(this).text()));
console.log(floors);
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
} else {
$(this).css("background-color", "#02c099");
$(this).css("border-color", "#13a480");
for (var i = 0; i < floors.length; i++) {
if (floors[i] == parseInt($(this).text()))
floors.splice(i, 1);
}
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
}
$(this).data('state', state);
});
Demo Here: http://jsfiddle.net/bFe9T/
I believe this is what you're looking for:
$(".nr").click(function () {
$(this).toggleClass('selected');
$('.nr').each(function(){
var $target = $('#lvl'+$(this).text());
if($(this).is('.selected'))
$target.slideDown();
else
$target.slideUp();
});
});
Note that instead of changing the CSS properties I set up a class for the selected elements
Demo fiddle
Try this
$(".nr").click(function () {
//alert($(this).attr("data-select"));
if($(this).attr("data-select") === "1") {
$(this).attr("data-select","0");
} else {
$(this).attr("data-select","1");
}
$(".nr").each(function(){
if($(this).attr("data-select") === "1") {
var id = $(this).text();
$("div#lvl"+id).slideDown();
} else {
var id1 = $(this).text();
$("div#lvl"+id1).slideUp();
}
});
});
FIDDLE
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>slideUp demo</title>
<style>
.norm { background:#cccccc; margin:3px; width:80px;height:40px; float:left;color:#000000 }
.faded { background:#ffffff; margin:3px; width:80px;height:40px; float:left;color:#ffffff }
.btn{width:80px;}
</style>
<script src="http://code.jquery.com/jquery-1.8.1.js"></script>
</head>
<body>
<button class="btn" onClick="show(1)">1</button>
<button class="btn" onClick="show(2)">2</button>
<button class="btn" onClick="show(3)">3</button>
<button class="btn" onClick="show(4)">4</button>
<button class="btn" onClick="reset()">Reset</button>
<div class="norm" id="slide1">1</div>
<div class="norm" id="slide2">2</div>
<div class="norm" id="slide3">3</div>
<div class="norm" id="slide4">4</div>
<div></div>
<script>
var save = new Array();
function show(indx){
if($.inArray(indx, save)==-1){
save.push(indx);
for(var i=0;i<5;i++){
if($.inArray(i, save)==-1){
$('#slide'+i).attr('class','faded');
}
else{
$('#slide'+i).attr('class','norm');
}
}
}
}
function reset(){
save = new Array();
for(var i=0;i<5;i++){
$('#slide'+i).attr('class','norm');
}
}
</script>
</body>
</html>

Sorting table using javascript sort()

I am trying to sort a table. I've seen several jQuery and JavaScript solutions which do this through various means, however, haven't seen any that use JavaScript's native sort() method. Maybe I am wrong, but it seems to me that using sort() would be faster.
Below is my attempt, however, I am definitely missing something. Is what I am trying to do feasible, or should I abandon it? Ideally, I would like to stay away from innerHTML and jQuery. Thanks
var index = 0; //Index to sort on.
var a = document.getElementById('myTable').rows;
//sort() doesn't work on collection
var b = [];
for (var i = a.length >>> 0; i--;) {
b[i] = a[i];
}
var x_td, y_td;
b.sort(function(x, y) {
//Having to use getElementsByTagName is probably wrong
x_td = x.getElementsByTagName('td')[index].data;
y_td = y.getElementsByTagName('td')[index].data;
return x_td == y_td ? 0 : (x_td < y_td ? -1 : 1);
});
A td element doesn't have a .data property.
If you wanted the text content of the element, and if there's only a single text node, then use .firstChild before .data.
Then when that is done, you need to append the elements to the DOM. Sorting a JavaScript Array of elements doesn't have any impact on the DOM.
Also, instead of getElementsByTagName("td"), you can just use .cells.
b.sort(function(rowx, rowy) {
x_td = rowx.cells[index].firstChild.data;
y_td = rowy.cells[index].firstChild.data;
return x_td == y_td ? 0 : (x_td < y_td ? -1 : 1);
});
var parent = b[0].parentNode;
b.forEach(function(row) {
parent.appendChild(row);
});
If the content that you're comparing is numeric, you should convert the strings to numbers.
If they are text strings, then you should use .localeCompare().
return x_td.localeCompare(y_td);
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>All Sorting Techniques</title>
<script type="text/javascript">
var a = [21,5,7,318,3,4,9,1,34,67,33,109,23,156,283];
function bubbleSort(a)
{
var change;
do {
change = false;
for (var i=0; i < a.length-1; i++) {
if (a[i] > a[i+1]) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
change = true;
}
}
} while (change);
document.getElementById("bublsrt").innerHTML = "Bubble Sort Result is: "+a;
}
var b = [1,3,4,5,7,9,21,23,33,34,67,109,156,283,318];
function binarySearch(b, elem){
var left = 0;
var right = b.length - 1;
while (left <= right){
var mid = parseInt((left + right)/2);
if (b[mid] == elem)
return mid;
else if (b[mid] < elem)
left = mid + 1;
else
right = mid - 1;
}
return b.length;
}
function searchbinary(){
var x = document.getElementById("binarysearchtb").value;
var element= binarySearch(b,x);
if(element==b.length)
{
alert("no. not found");
}
else
{
alert("Element is at the index number: "+ element);
}
}
function quicksort(a)
{
if (a.length == 0)
return [];
var left = new Array();
var right = new Array();
var pivot = a[0];
for (var i = 1; i < a.length; i++) {
if (a[i] < pivot) {
left.push(a[i]);
} else {
right.push(a[i]);
}
}
return quicksort(left).concat(pivot, quicksort(right));
}
function quicksortresult()
{
quicksort(a);
document.getElementById("qcksrt").innerHTML = "Quick Sort Result is: "+quicksort(a);
}
function numeric(evt){
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault)
theEvent.preventDefault();
}
}
function insertionsorting(a)
{
var len = a.length;
var temp;
var i;
var j;
for (i=0; i < len; i++) {
temp = a[i];
for (j=i-1; j > -1 && a[j] > temp; j--) {
a[j+1] = a[j];
}
a[j+1] = temp;
}
document.getElementById("insrtsrt").innerHTML = "Insertion Sort Result is: "+a;
}
function hiddendiv()
{
document.getElementById("binarytbdiv").style.display = "none";
document.getElementById("Insertnotbdiv").style.display = "none";
}
function binarydivshow()
{
document.getElementById("binarytbdiv").style.display = "block";
}
function insertnodivshow()
{
document.getElementById("Insertnotbdiv").style.display = "block";
}
function insertno(a)
{
var extrano = document.getElementById("Insertnotb").value;
var b= a.push(extrano);
var change;
do {
change = false;
for (var i=0; i < a.length-1; i++) {
if (a[i] > a[i+1]) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
change = true;
}
}
} while (change);
document.getElementById("insrtnosearch").innerHTML = "Sorted List is: "+a;
alert("Index of "+extrano +" is " +a.indexOf(extrano));
}
</script>
</head>
<body onload="hiddendiv()">
<h1 align="center">All Type Of Sorting</h1>
<p align="center">Your Array is : 21,5,7,318,3,4,9,1,34,67,33,109,23,156,283</p>
<div id="main_div" align="center">
<div id="bubblesort">
<input type="button" id="bubblesortbutton" onclick="bubbleSort(a)" value="Bubble Sort">
<p id="bublsrt"></p>
</div><br>
<div id="quicksort">
<input type="button" id="quicksortbutton" onclick="quicksortresult()" value="Quick Sort">
<p id="qcksrt"></p>
</div><br>
<div id="insertionsort">
<input type="button" id="insertionsortbutton" onclick="insertionsorting(a)" value="Insertion Sort">
<p id="insrtsrt"></p>
</div><br>
<div id="binarysearch">
<input type="button" id="binarysearchbutton" onclick="binarydivshow();" value="Binary Search">
<div id="binarytbdiv">
<input type="text" id="binarysearchtb" placeholder="Enter a Number" onkeypress="numeric(event)"><br>
<input type="button" id="binarysearchtbbutton" value="Submit" onclick="searchbinary()">
<p id="binarysrch">Sorted List is : 1,3,4,5,7,9,21,23,33,34,67,109,156,283,318</p>
</div>
</div><br>
<div id="Insertno">
<input type="button" id="insertno" onclick="insertnodivshow()" value="Insert A Number">
<div id="Insertnotbdiv">
<input type="text" id="Insertnotb" placeholder="Enter a Number" onkeypress="numeric(event);"><br>
<input type="button" id="Insertnotbbutton" value="Submit" onclick="insertno(a)">
<p id="insrtnosearch"></p>
</div>
</div>
</div>
</body>
</html>

Categories

Resources