Hey guys! not sure what is going on, but can’t get this code to pass. Please excuse some of the random decisions going on in this code, I made weird needless adaptations to try and fufill to criteria.
It seems to function as necessary. Only thing I have not done is stop from highlighting the final one. Didn’t feel it necessary until the other couple of steps pass.
Your code so far
function generateElement() {
return Math.floor(Math.random() * 100) + 1;
}
function generateArray() {
const arr = [];
let i;
for (i = 0; i < 5; i++) {
arr.push(generateElement());
}
return arr;
}
function generateContainer() {
const newDiv = document.createElement("div");
newDiv.classList.add("delete");
return newDiv;
}
const container = generateContainer();
const array = generateArray();
function fillArrContainer(element, arr) {
arr.forEach((result, index) => {
const span = document.createElement("span");
span.innerHTML = result;
span.setAttribute("id", `${index + 1}`);
span.style.marginRight = "10px";
element.appendChild(span);
});
}
function isOrdered(int, int2) {
if (int <= int2) {
return true;
} else return false;
}
function swapElements(arr, index) {
if (arr[index] > arr[index + 1]) {
[arr[index], arr[index + 1]] = [arr[index + 1], arr[index]];
return true;
}
return false;
}
function highlightCurrentEls(element, index) {
let descendants = element.querySelectorAll("span");
if (descendants[index]) {
descendants[index].style.border = "2px dashed red";
}
if (descendants[index + 1]) {
descendants[index + 1].style.border = "2px dashed red";
}
}
function final(arr) {
const beginning = startingArr.querySelector("div");
highlightCurrentEls(beginning, 0);
swapElements(arr, i);
let i = 1;
let j = 0;
while (true) {
let result = 0;
let sorted = false;
if (i >= arr.length - 1) {
result = 0;
i = 0;
j + 1;
}
const container = generateContainer();
arrayContainer.appendChild(container);
fillArrContainer(container, arr);
highlightCurrentEls(container, i);
swapElements(arr, i);
sorted = true;
for (let j = 0; j < arr.length - 1; j++) {
if (arr[j] > arr[j + 1]) {
sorted = false;
break;
}
}
if (sorted) {
const container = generateContainer();
arrayContainer.appendChild(container);
fillArrContainer(container, arr);
highlightCurrentEls(container, i);
break;
}
i++;
}
//return arr;
}
const genBtn = document.getElementById("generate-btn");
const startingArr = document.getElementById("starting-array");
const sortBtn = document.getElementById("sort-btn");
const arrayContainer = document.getElementById("array-container");
let testArr = [];
genBtn.addEventListener("click", () => {
if (sortBtn.classList.contains("hidden")) {
sortBtn.classList.toggle("hidden");
}
const divs = arrayContainer.querySelectorAll(".delete");
divs.forEach(div => {
div.remove();
});
const container = generateContainer();
startingArr.appendChild(container);
testArr = generateArray();
fillArrContainer(container, testArr);
});
sortBtn.addEventListener("click", () => {
sortBtn.classList.toggle("hidden");
console.log(arrayContainer.innerHTML);
const beginning = startingArr.querySelector("div");
highlightCurrentEls(beginning, 0);
swapElements(testArr, i);
let i = 1;
let j = 0;
while (true) {
let sorted = false;
let result = 0;
if (i >= testArr.length - 1) {
result = 0;
i = 0;
j + 1;
}
const container = generateContainer();
arrayContainer.appendChild(container);
fillArrContainer(container, testArr);
highlightCurrentEls(container, i);
swapElements(testArr, i);
sorted = true;
for (let j = 0; j < testArr.length - 1; j++) {
if (testArr[j] > testArr[j + 1]) {
sorted = false;
break;
}
}
if (sorted) {
const container = generateContainer();
arrayContainer.appendChild(container);
fillArrContainer(container, testArr);
highlightCurrentEls(container, i);
break;
}
i++;
}
//return arr;
});
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 Edg/136.0.0.0
Challenge Information:
Build a Sorting Visualizer - Build a Sorting Visualizer
I’ve edited your post to improve the readability of the code. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.
New updated code to try and copy the sample algorithm exactly. Still not passing. Also saw people warn against using a global array, so saw a few people on here use array.from so did that. still no good.
const genBtn = document.getElementById("generate-btn");
const startingArr = document.getElementById("starting-array");
const sortBtn = document.getElementById("sort-btn");
const arrayContainer = document.getElementById("array-container");
function generateElement() {
return Math.floor(Math.random() * 100) + 1;
}
function generateArray() {
const arr = [];
let i;
for (i = 0; i < 5; i++) {
arr.push(generateElement());
}
return arr;
}
function generateContainer() {
const newDiv = document.createElement("div");
newDiv.classList.add("delete");
return newDiv;
}
const container = generateContainer();
const array = generateArray();
function fillArrContainer(element, arr) {
arr.forEach((result, index) => {
const span = document.createElement("span");
span.innerHTML = result;
span.setAttribute("id", `${index + 1}`);
span.style.marginRight = "10px";
element.appendChild(span);
});
}
function isOrdered(int, int2) {
if (int <= int2) {
return true;
} else return false;
}
function swapElements(arr, index) {
if (arr[index] > arr[index + 1]) {
[arr[index], arr[index + 1]] = [arr[index + 1], arr[index]];
return true;
}
return false;
}
function highlightCurrentEls(element, index) {
let descendants = element.querySelectorAll("span");
if (descendants[index]) {
descendants[index].style.border = "2px dashed red";
}
if (descendants[index + 1]) {
descendants[index + 1].style.border = "2px dashed red";
}
}
function final(arr) {
const beginning = startingArr.querySelector("div");
highlightCurrentEls(beginning, 0);
swapElements(arr, 0);
let i = 1;
let j = 0;
while (true) {
let result = 0;
let sorted = false;
if (i >= arr.length - 1) {
result = 0;
i = 0;
j + 1;
}
const container = generateContainer();
arrayContainer.appendChild(container);
fillArrContainer(container, arr);
highlightCurrentEls(container, i);
swapElements(arr, i);
sorted = true;
for (let j = 0; j < arr.length - 1; j++) {
if (arr[j] > arr[j + 1]) {
sorted = false;
break;
}
}
if (sorted && i === 3) {
const container = generateContainer();
arrayContainer.appendChild(container);
fillArrContainer(container, arr);
break;
}
i++;
}
//return arr;
}
//let testArr = [];
genBtn.addEventListener("click", () => {
if (sortBtn.classList.contains("hidden")) {
sortBtn.classList.toggle("hidden");
}
const divs = arrayContainer.querySelectorAll(".delete");
divs.forEach(div => {
div.remove();
});
const container = generateContainer();
startingArr.appendChild(container);
const testArr = generateArray();
fillArrContainer(container, testArr);
});
sortBtn.addEventListener("click", () => {
const testArr = Array.from(startingArr.querySelector("div").children).map(span => Number(span.textContent));
final(testArr)
sortBtn.classList.toggle("hidden");
console.log(arrayContainer.innerHTML);
//return arr;
});
Ill reply properly later with screenshots e.t.c when i get a moment, but from memory it behaves exactly the same as the example in terms of function.
That doesnt mean that I’m not doing something incorrect though.
I think im failing the last few tests involving sortbtn. Console.log shows five spans per div though, so theoretically it should at LEAST past that test.
Maybe theres something important i missed. Not sure what though.
Run the example program, and screenshot what it looks like. Then pass the same array to your function (hardcode it instead of randomly generating one) and see if it does the exact same number of steps.
Take note of this instruction:
The algorithm stops after one cycle completes with no swaps.
Ok, so to be fair I was sometimes doing a couple less steps than the example. So I changed the code around a bit so that it is always the EXACT number of steps as the example. Still won’t work.
In the screenshot I accidentally hardcoded one wrong number, but you get the idea. It works the same. I did it multiple times with different examples as well.
When I try your code, I still see the Sort button after the final sort has completed. And have you tried clicking the Generate button after the final sort has completed?
UPDATE: This array 99 33 58 90 90 generates a serious console error:
Potential infinite loop detected on line 74. Tests may fail if this is not changed.
Hey not sure why it is doing that. It was working fine yesterday. Its possible in my tiredness I made stupid changes to try and meet the criteria. Try this instead.
.. so basically i redid the whole thing to see if I had missed something. Spent all day doing it, still not passing.
And yeah its exactly the same functionally as the orginal. At least in terms of output.
So what it does is it runs a loop using the functions defined earlier by the instructions, if one element is greater than the other, the elements are shifted.
J keeps count of how many times an element is greater than the last one, and is reset once the elements are swapped (done in order to make sure it has to go through whole process once like youve stated) or when the elements are not in order.
Thus for the function to complete, all the elements have to be in order and the whole thing has to have run once with them all in order. "I"tracks the array, and is the loop variable.
On first run though, starting array is highlighted, so at the very least that should pass i would have thought.
I have appended the elements using appendChild, and have done so in the function and order the instructions said. Console.log confirms five span elements within a div.
Output matches output. At least as i left it tonight.
I dont really know what else to say. Except, changing the logic of my system doesnt seem matter, because the test criteria doesnt seem to register even when i highlight the first div.
Feel free to try the code that i last put. It seems to function as intended.
Your function needs to go from 13 to 93 checking each pair and make no swaps before it ends, that’s a full cycle. Here you make a swap, get to the end, and then finish. It needs one more sweep of all the numbers with no swaps to confirm the sort.
In the example sorter, you can see the last sweep of the array compares all of the values and makes no swaps.
Thank you, but i checked and hard coded a number of arrays and they came out the same as orginal, so im confused by this.
J being set to 0 after a trade happens means that it should have to go through the whole thing before it finalises.
In any case, the fix for what you are suggesting is very simple and i am happy to implement it, but it wont pass the tests because even the highlight the first array test doesnt seem to be passing.
Thanks for your suggestion though, ill have a look tomorrow. I imagine all i have to do is make sure the check happens after the swap.
Im not denying your findings but just in case, did you download before i edited it? Because i left a typo for a few mins before i realised
if (swapElements(newArr, i)){
j = 0;
}
Should be that
After you click #sort-btn, each div within #array-container should contain five span, each with a number as its text, and arranged to represent the steps required by Bubble Sort algorithm to sort the starting array.
Are you able to confirm and prove that your output is like this?
I think so. Heres my output. Unless theres something I misunderstood, but they want five spans within a div element right?
Edit: Oh hang about. I presumed they wanted me to create a div for each element, but now I feel like maybe I don’t need to for starting array because of the div already there. Ill change it and see if it works.