Bubblesort algorithm [duplicate] - javascript

This question already has answers here:
Bubble sort algorithm JavaScript [closed]
(7 answers)
Closed 2 years ago.
im new in this forum so, if i wrong to post this i apologize. Im learnin Javascript and for training i made this bubblesort algorithm:
var x = [1, 5, 2, 8, 3, 6, 4, 9, 7];
sort(x);
function sort(params) {
var appoggio=0;
for (i=0; i<params.length; i++) {
for (j=0; j<params.length; j++) {
appoggio=params[j];
params[j] = params[j+1];
params[j+1] = appoggio;
}
}
}
console.log(x);
I have made a basic html page where i call this script but it doesn't work and i don't understand why. I try to debugg it inser some alert(params[j]) inside the for cycle but after the first interation the scrpt blocks all the web page. What i have to do?

You are falling in an infinite loop as you push at j+1 even when you hit the end of your list (which increment the length each time). Try to stop at params.length-1.

The if condition is missing!
You need to swap values only if they are not ordered correctly.
Plus, as #MetallimaX said, you need to stop your loop at params.length - 1 to avoid writing outside of the array
Without giving you the answer, which would spoil everything:
for a given number of times (enough that values can bubble all the way) {
for each adjacent values pair (from left to right) {
if the pair is not ordered correctly {
swap both elements()
}
}
}

Related

Is my solution to the "Sum of Range" exercise in Chapter4 of Eloquent JavaScript okay? Or is there a way to make it better?

I started learning website development (just over 2 months now), learning frontend with HTML, CSS and JS. I am currently on the Eloquent JavaScript book. I did the "sum of range" exercise in chapter 4 of the book, I was able to code the range function, got a little help on the sum function, and competed the exercise. What I want now is to know how well written my solution is, and if there is a better way. This is the exercise and my code solution follows:
Write a range function that takes two arguments, start and end, and returns an array containing all the numbers from start up to (and including) end.
Next write a sum function that takes an array of numbers and returns the sum of these numbers.
As a bonus assignment, modify your range function to take an optional third argument that indicates the "step" value used when building the array. If no step is given, the elements go up by increments of one, corresponding to the old behaviour. The function call range(1, 10, 2) should return [1, 3, 5, 7, 9]. Make sure it also works with negative step values so that range(5, 2, -1) returns [5, 4, 3, 2].
My solution:
function range(start, end, skip) {
let arr = [];
let count;
for (count = start;start < end ? count<=end : count >= end ; count+= skip) {
arr.push(count);
}
return arr;
}
function sum(numbers) {
result = 0;
for (let num of numbers) {
result += num;
}
return result;
}
All I need now is a somewhat "code inspection". Thanks in advance!

understanding what the code exactly does behind the scenes

I don't know if this question is really asked but i have a running code with for loop which sorts an array of numbers. But i don't get the idea behind the code. If someone who has experience can tell me whats happening behind the scenes would be great.
Here is the code:
var a = [1, 7, 2, 8, 3, 4, 5, 0, 9];
for(i=1; i<a.length; i++)
for(k=0; k<i; k++)
if(a[i]<a[k]){
var y = a[i]
a[i]= a[k]
a[k]=y;
}
alert(a);
First, having your code indented properly and not taking advantage of optional syntax (braces and semi-colons) will go a long way towards your understanding of how the code is processed. Technically, curly braces are not required with for and if statements if there is just one statement to perform within the loop or within the branch of the if. Additionally, JavaScript technically does not require that you place a semicolon at the end of your statements. Do not take advantage of either one of these optional syntaxes as it will only make things more confusing and possibly lead to bugs in your code.
With that in mind, your code really should be written as follows. The job of this code is to sort the items in the array. It does this by looping through the array and always checking the current array item and the item that precedes it. If the items are out of order, the values are swapped.
Please see the comments for descriptions of what each line does:
// Declare and populate an array of numbers
var a = [1, 7, 2, 8, 3, 4, 5, 0, 9];
// Loop the same amount of times as there are elements in the array
// Although this code will loop the right amount of times, generally
// loop counters will start at 0 and go as long as the loop counter
// is less than the array.length because array indexes start from 0.
for(i=1; i<a.length; i++){
// Set up a nested loop that will go as long as the nested counter
// is less than the main loop counter. This nested loop counter
// will always be one less than the main loop counter
for(k=0; k<i; k++){
// Check the array item being iterated to see if it is less than
// the array element that is just prior to it
if(a[i]<a[k]){
// ********* The following 3 lines cause the array item being iterated
// and the item that precedes it to swap values
// Create a temporary variable that stores the array item that
// the main loop is currently iterating
var y = a[i];
// Make the current array item take on the value of the one that precedes it
a[i]= a[k];
// Make the array item that precedes the one being iterated have the value
// of the temporary variable.
a[k]=y;
}
}
}
alert(a);

functional loop given a number instead of an array [duplicate]

This question already has answers here:
Tersest way to create an array of integers from 1..20 in JavaScript
(16 answers)
Closed 6 years ago.
The community reviewed whether to reopen this question 2 months ago and left it closed:
Original close reason(s) were not resolved
Say I have a number 18, instead of an array, in hand.
What is the best way to create a functional loop in JS given a number X instead of array of X elements?
I can do this:
[1,2,3].forEach(function(){
));
but if I have the number 3
I can do
for(var i = 0; i < 3; i++){
}
but I want that loop to be functional instead
If you have a number and you want to create a loop then you can use the number in limiter condition in the for loop.
for(var i = 0; i < number; i++)
Edit 1: you can use foreach on arrays only, in that case since you have a number already you can create a array of that length and then use the foreach on it.
var foo = new Array(number).fill(0);
foo.foreach()
Also another option is
var N = 18;
Array.apply(null, {length: N}).map(Number.call, Number)
result [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
Many more options available in this thread Create a JavaScript array containing 1...N
I don't understand why you want to do this. An equivalent to:
[1,2,3].forEach(function(){ ... ));
Is
var limit = n;
while (--limit) {( // Note: 0 is falsy
function(){ ... }
)(limit);}
Or if you really want to use an array structure, the following will do:
new Array(limit).fill(0).forEach(function(){...});
You might be interested in Myth of the Day: Functional Programmers Don't Use Loops.
Per this question, you can "functionally" iterate over a linear sequence relatively easily using:
Array.apply(null, Array(number)).map(function () {}).forEach(...)
Not sure what advantage this gives you versus a regular for-loop with an index, though it is a neat trick.

Generate a random array in Javascript/jquery for Sudoku puzzle

I want to fill the 9 x 9 grid from the array by taking care of following condition
A particular number should not be repeated across the same column.
A particular number should not be repeated across the same row.
When i execute the below mentioned code it fills all the 9 X 9 grid with random values without the above mentioned condition.How can I add those two condition before inserting values into my 9 X 9 Grid.
var sudoku_array = ['1','2','3','4','6','5','7','8','9'];
$('.smallbox input').each(function(index) {
$(this).val(sudoku_array[Math.floor(Math.random()*sudoku_array.length)]);
});
My JSFIDDLE LINK
Generating and solving Sudokus is actually not as simple as other (wrong) answers might suggest, but it is not rocket science either. Instead of copying and pasting from Wikipedia I'd like to point you to this question.
However, since it is bad practice to just point to external links, I want to justify it by providing you at least with the intuition why naive approaches fail.
If you start generating a Sudoku board by filling some fields with random numbers (thereby taking into account your constraints), you obtain a partially filled board. Completing it is then equivalent to solving a Sudoku which is nothing else than completing a partially filled board by adhering to the Sudoku rules. If you ever tried it, you will know that this is not possible if you decide on the next number by chosing a valid number only with respect to the 3x3 box, the column and the row. For all but the simplest Sudokus there is some trial and error, so you need a form of backtracking.
I hope this helps.
To ensure that no number is repeated on a row, you might need a shuffling function. For columns, you'll just have to do it the hard way (checking previous solutions to see if a number exists on that column). I hope i am not confusing rows for columns, i tend to do it a lot.
It's similar to the eight queens problem in evolutionary computing. Backtracking, a pure random walk or an evolved solution would solve the problem.
This code will take a while, but it'll do the job.
You can the iterate through the returned two dimensional array, and fill the sudoku box. Holla if you need any help with that
Array.prototype.shuffle = function() {
var arr = this.valueOf();
var ret = [];
while (ret.length < arr.length) {
var x = arr[Math.floor(Number(Math.random() * arr.length))];
if (!(ret.indexOf(x) >= 0)) ret.push(x);
}
return ret;
}
function getSudoku() {
var sudoku = [];
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
sudoku.push(arr);
for (var i = 1; i < 9; i++) {
while (sudoku.length <= i) {
var newarr = arr.shuffle();
var b = false;
for (var j = 0; j < arr.length; j++) {
for (var k = 0; k < i; k++) {
if (sudoku[k].indexOf(newarr[j]) == j) b = true;
}
}
if (!b) {
sudoku.push(newarr);
document.body.innerHTML += `${newarr}<br/>`;
}
}
}
return sudoku;
}
getSudoku()
You need to keep track of what you have inserted before, for the following line:
$(this).val(sudoku_array[Math.floor(Math.random()*sudoku_array.length)]);
For example you can have a jagged array (arrays of arrays, its like a 2-D array) instead of 'sudoku_array' you have created to keep track of available numbers. In fact, you can create two jagged arrays, one for column and one for rows. Since you don't keep track of what you have inserted before, numbers are generated randomly.
After you create an array that keeps available numbers, you do the following:
After you generate number, remove it from the jagged array's respective row and column to mark it unavailable for those row and columns.
Before creating any number, check if it is available in the jagged array(check for both column and row). If not available, make it try another number.
Note: You can reduce the limits of random number you generate to available numbers. If you do that the random number x you generate would mean xth available number for that cell. That way you would not get a number that is not available and thus it works significantly faster.
Edit: As Lex82 pointed out in the comments and in his answer, you will also need a backtracking to avoid dead ends or you need to go deeper in mathematics. I'm just going to keep my answer in case it gives you an idea.

Getting wrong output when trying to loop through the first 50 even Fibonacci numbers in JavaScript [duplicate]

This question already has answers here:
Javascript looping through Fibonacci numbers and testing for even numbers
(2 answers)
Closed 8 years ago.
I am new to JavaScript and am having trouble getting my code to work. Any help/guidance is greatly appreciated.
I am getting the wrong output (currently “9.715575428267785e+30“) when trying to “displays the sum of first 50 even Fibonacci numbers”
I needed to:
1. create a loop that generates Fibonacci numbers.
2. test each one for whether it's even or odd.
3. Add up up the even ones, counting them as you go.
------------HERE IS MY CODE THUS FAR --------
<div id="sumFib" class="hwbutton">Get the Sum!</div>
The sum of the first 50 even Fibonacci numbers is:
<span class="" id="sumFibResult"></span>
<script>
var getFibSum = document.getElementById("sumFib");
getFibSum.onclick = function () {
fiftyEvenFibonacciSum();
}
function fiftyEvenFibonacciSum() {
var loopFib;
//Initialize fibonacci array
var fibonacci = new Array();
//Add fibonacci array items
fibonacci[0] = 0;
fibonacci[1] = 1;
var sum = 0;
//Since it takes 150 fib numbers to obtain 50 even, loop through that many.
for (loopFib = 2; loopFib <= 150; loopFib++) {
// Next fibonacci number = previous + one before previous
fibonacci[loopFib] = fibonacci[loopFib - 2] + fibonacci[loopFib - 1];
//test for even numbers with if then statement
var integer = parseInt(fibonacci[loopFib]);
if (integer % 2 == 0) {
//Add up the even fib numbers if even and output into dispay variable
var display = sum += fibonacci[loopFib];
//output results to html page
document.getElementById("sumFibResult").innerHTML = display;
}
}
}
</script>
http://jsfiddle.net/isherwood/38gPs
I disagree with the people saying this is a duplicate because I think the real question you are asking is "how do I debug my failing program?" I am sure that must be a duplicate too but, well, hem...
Anyhow I think what would help you a lot here is console.log(). I don't know what browser you are using but all major ones have a JS console. (I recommend Firefox with Firebug.) Add lines like:
console.log('integer for ' + loopFib + '=' + integer);
Or
console.log('display=' + display);
To the relevant points in your script. Then open your browser's JavaScript console to view the results. I already see some major boners in your code but I'm not going to correct them for you - this is your homework assignment after all and I'd rather teach a man to fish. Comment on this reply if you have any more questions.

Categories