I am new to javascript and working with DOM, so please bear with me.
I have an array called num that I want to sort and display. The sort is a selection sort that returns the number of moves it took.
I can display the unsorted array but can't figure out how to call my sort function and then display the sorted array to the screen. My code is below:
function fn(a, b) {
if (a < b)
return true;
}
function selection(list, fun) {
var min, temp, count,
len = list.length;
for (var i = 0; i < len; i++) {
min = i;
for (var j = i + 1; j < len; j++) {
if (fun(list[j], list[min])) {
min = j;
}
}
temp = list[i];
list[i] = list[min];
listlist
list[min] = temp;
count += 3;
}
return count;
}
var num = [10, 1, 3, 5, 2, 9, 8, 6, 7, 4];
var demoP = document.getElementById("content");
{
var html = "";
html += "Original:" + num + "<br>";
selection(num, fn);
html += "Sorted:" + num + "<br>";
}
demoP.innerHTML = html;
<div id="content"></div>
arr is undefined, you should use list instead. Returning count returns the number of operations (after it's been initialized), return list instead. And as list is local to the function, you need to set num to the return value of the function call.
<span id='content'/>
<script>
function fn(a, b) {
if (a < b)
return true;
}
function selection(list, fun) {
var min, temp, count=0,
len = list.length;
for (var i = 0; i < len; i++) {
min = i;
for (var j = i + 1; j < len; j++) {
if (fun(list[j], list[min])) {
min = j;
}
}
temp = list[i];
list[i] = list[min];
list[min] = temp;
count += 3;
}
return list;
}
var num = [10, 1, 3, 5, 2, 9, 8, 6, 7, 4];
var demoP = document.getElementById("content");
var html = "";
html += "Original:" + num + "<br>";
num= selection(num, fn);
html += "Sorted:" + num + "<br>";
demoP.innerHTML = html;
</script>
Related
I've got to create var with few elements:
var arrNum = [4,7,5,3,4,5,6,7,8,10]
I need to find first number that is the same in array using for loop. So it will be "4" and "4"
I need to create var sameIndex and adjust the same number to sameIndex and print after for loop
So I did loop
for(var i = 0; i < arrNum.length; i++){
console.log("")
console.log("Loop number is " + i)
if(arrNum[i] === arrNum[i]{
break
sameIndex = going[i]
}
}
console.log(sameIndex)
It's not working.
One way would be to use Array#indexOf. It returns the first index of the given element in the array:
var arrNum = [4, 7, 5, 3, 4, 5, 6, 7, 8, 10];
var i;
var sameIndex = -1;
for (i = 0; i < arrNum.length; i++) {
if (arrNum.indexOf(arrNum[i]) !== i) {
console.log('This is the second occurrence of', arrNum[i]);
sameIndex = arrNum.indexOf(arrNum[i]);
break;
}
}
console.log('The indices are', sameIndex, 'and', i);
If you're looking to get the first duplicate, then use :
var arrNum = [4,7,5,3,4,5,6,7,8,10];
function firstDuplicate(array){
var history = [];
for(var element of array){
if(history.indexOf(element)<0)
//not in the history yet
history.push(element);
else
return element;
}
return null; //or any distinctive value
}
var fDup = firstDuplicate(arrNum);
You could take a hash table and display the value.
var array = [4, 7, 5, 3, 4, 5, 6, 7, 8, 10],
hash = Object.create(null),
i;
for (i = 0; i < array.length; i++) {
if (hash[array[i]]) {
console.log('first dupe: ' + array[i]);
break;
}
hash[array[i]] = true;
}
A working script:
var arrNum = [4,7,5,3,4,5,6,7,8,10];
var sameIndex = -1, going = new Array();
for(var j = 0; j < arrNum.length; j++) {
for(var i = 1; i < arrNum.length; i++){
console.log("Loop number is " + j + ", " + i)
if(arrNum[i] === arrNum[j]){
sameIndex = i;
break;
}
}
if(sameIndex > 0) {
console.log(j, sameIndex)
break;
}
}
var arrNum = [4,7,5,3,4,5,6,7,8,10];
for(var i = 0; i < arrNum.length; i++){
for(var j = i+1; j < arrNum.length; j++) {
if(arrNum[i] === arrNum[j]) {
console.log('value: '+arrNum[i]+' index1: '+i+' index2: '+j);
}
}
}
Iterate over the original array and if the value is not in a comparison array - push it into a common numbers array. The first item in that common numbers array is the target.
var origArray = [4,7,5,3,4,5,6,7,8,10];
var newArray = [];
var commonNums = [];
origArray.forEach(function(item,i) {
newArray.indexOf(item) == -1
? newArray.push(item)
: commonNums.push({item: item, index:i});
})
if(commonNums.length > 0) {
var firstCommonNum = commonNums[0].item;
var firstCommonNumIndex = commonNums[0].index;
console.log("common number " + firstCommonNum);
console.log("Loop number is " + firstCommonNumIndex);
}
before going to problem, i want to generate dynamically like
temp = word[i] for 2,
temp = word[i-1] + word [i] for 3,
temp = word[i-2] + word[i-1] + word [i] for 4
I explained with code and what i have tried
function produceTwoChArray(word) {
var temp = "";
var tempArr = [];
for (var i = 0; i < word.length; i++) {
temp += word[i];
if (temp.length === 2) {
tempArr.push(temp);
}
temp = word[i];
}
return tempArr;
}
produceTwoChArray("breaking")
above code will produce result as :
["br", "re", "ea", "ak", "ki", "in", "ng"]
So inside the for loop if i change to below codes to produce three letters then
if (temp.length === 3) {
tempArr.push(temp);
}
temp = word[i-1] + word[i];
Result:
["bre", "rea", "eak", "aki", "kin", "ing"]
so adding word[i-1], word[i-2] with temp length 3, 4 and so on..
For dynamically creating the temp statement, i created these Function
1)
function generateWordSequence(n) {
var n = n - 2;
var temp1 = [];
for (var j = n; j >= 0; j--) {
temp1.push("word[i - " + j + "]");
}
temp1 = temp1.join('+').toString();
return temp1;
}
2)
function generateWordSequence(n, word) {
var n = n - 2;
var temp1 = "";
for (var j = n; j >= 0; j--) {
temp1 = temp1 + word[i - j];
}
return temp1;
}
But both above try's are returning as string so it didnt work. When i invoke above fn in produceTwoChArray fn like this
function produceTwoChArray(word, n) {
var temp = "";
var tempArr = [];
var retVar = generateWordSequence(n, word);
for (var i = 0; i < word.length; i++) {
temp += word[i];
if (temp.length === n) {
tempArr.push(temp);
}
temp = retVar;
}
return tempArr;
}
When i tried those all logic inside produceTwochArray itself , i also didnt work.
Please help me out here.
You could take a double slice with mapping part strings.
function part(string, count) {
return [...string.slice(count - 1)].map((_, i) => string.slice(i, i + count));
}
console.log(part("breaking", 2));
console.log(part("breaking", 3));
console.log(part("breaking", 4));
You can use slice method in order to obtain a more easy solution.
function produceArray(str,n){
return str=str.split('').map(function(item,i,str){
return str.slice(i,i+n).join('');
}).filter(a => a.length == n);
}
console.log(produceArray("breaking",2));
console.log(produceArray("breaking",3));
console.log(produceArray("breaking",4));
console.log(produceArray("breaking",5));
console.log(produceArray("breaking",6));
I want to sort a string in javascript without using a built in method, just by using for's and comparisons like 'a' > 'b';
Something that doesn't work:
function replaceAt(str, i, char) {
return str.substr(0,i) + char + str.substr(i + 1)
}
function swap(str, i1, i2) {
return replaceAt(replaceAt(str, i1, str[i2]),i2,str[i1]);
}
function sort(str) {
var sorted = str;
for (var i = 0; i < str.length; i++) {
if (str[i] > str[i + 1]) {
str = swap(str, i, i+1)
}
}
return str;
}
Pseudo-code or books, courses recommendations on programming are welcome!
Your code is not applying any sort algorithm logic, I recommend you to read atleast 1 to solve your problem.
Below is the program, which produces the expected output from your program using selection sort.
swap and replace functions works fine.
function sort(str) {
var sorted = str;
//Selection sort
for (var i = 0; i < str.length; i++) {
for(var j = i + 1; j < str.length - 1; j++) {
if (str[i] < str[j]) {
str = swap(str, i, j)
}
}
}
return str;
}
console.log(sort("zaasfweqrouoicxzvjlmmknkniqwerpopzxcvdfaa"));
//output: aaaaccdeeffiijkklmmnnoooppqqrrsuvvwwxxzzz
function sort(arr) {
arr = arr.split("");
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr.length; j++) {
if (arr[j] > arr[i]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr.join("");
}
console.log(sort("dcna"));
function sort(arr) {
arr = arr.split("");
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr.length; j++) {
if (arr[j] > arr[i]) {
[arr[j], arr[j+1]] = [arr[j+1], arr[j]]
}
}
}
return arr.join("");
}
console.log(sort("dcna"));
Note: no need of using temp variable
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
array=[4, 10, 2, 9, 6, 3, 13, 5];
function arrayOperations()
{
var count = array.length - 1,
temp,
j,
i;
for (j = 0; j < count; j++)
{
for (i = 0; i < count; i++)
{
if (array[i] > array[i + 1])
{
temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
}
}
}
document.write("ascending order is <br>")
for(k=0;k<=array.length-1;k++){
document.write(array[k]+ "<br>");
}
document.write("descending order is <br>")
for(k=array.length-1;k>=0;k--){
document.write(array[k]+ "<br>");
}
document.write("biggest number is <br>")
for(k=array.length-1;k>=0;k--){
if((array[k])>array[k-1]){
document.write(array[k]+"<br>")
break;
}
}
document.write("smallest number is <br>")
for(k=0;k<=array.length;k++){
if((array[k])<array[k+1]){
document.write(array[k]+"<br>")
break;
}
}
}
</script>
<title></title>
</head>
<body>
array=[4, 10, 2, 9, 6, 3, 13, 5]
<br>
<input type="button" onclick="arrayOperations()" value="find">
</body>
</html>
//generic sort function to sort a word
function sortArray(str){
let strr = str.split('');
for(var index = 0 ;index <strr.length ;index ++ ){
for(var index1 = 0;index1<(strr.length-index) ;index1++){
let temp;
if( strr[index1] > strr[index1+1] ){
temp = strr[index1] ;
strr[index1] = strr[index1 +1];
strr[index1+1] =temp;
}
}
}
return(strr.join(''));
}
//data set to sort
let data = "Hey Goodmorning How are you";
let result;
let data1 =data.split(' ');
data1.forEach(value => {
value = sortArray(value.toLowerCase());
if(result){
result += " ";
result += value;
}
else {result = value;}
});
console.log(result);
I wanna my divs to be sorted but in this code it only goes through for loop once. How can i make this to end both loops and my divs sorted?
var arr = [4, 7, 1, 9, 8, 13, 6, 11];
function showarray() {
for (var i = 0; i < arr.length; i++) {
var divSort = document.createElement("div");
divSort.style.width = 30 + "px";
divSort.style.height = 30 + "px";
divSort.style.background = "yellow";
divSort.style.display = "inline-block";
divSort.style.margin = "10px";
divSort.id = arr[i];
divSort.innerHTML = arr[i];
document.body.appendChild(divSort);
}
}
showarray();
function func() {
for (var j = (arr.length - 1); j >= 0; j--) {
for (var i = 1; i <= j; i++) {
if (arr[i] < arr[i - 1]) {
doSetTimeout(i, j);
};
};
}
function doSetTimeout(i, j) {
setTimeout(function() {
$("#" + arr[i]).insertBefore("#" + arr[i - 1]);
}, j * i * 100);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="func()">Click</button>
It looks like you are only iterating one time because you aren't changing the array indexes, you are just updating the div positions, so everytime you iterate the array, it hasn't changed (just your divs). So you are always iterating the same array, doing the same changes over and over again. You need to change the array values and also change the div positions:
var arr = [4, 7, 1, 9, 8, 13, 6, 11];
var counter = 0;
function showarray() {
for (var i = 0; i < arr.length; i++) {
var divSort = document.createElement("div");
divSort.style.width = 30 + "px";
divSort.style.height = 30 + "px";
divSort.style.background = "yellow";
divSort.style.display = "inline-block";
divSort.style.margin = "10px";
divSort.id = arr[i];
divSort.innerHTML = arr[i];
document.body.appendChild(divSort);
}
}
showarray();
function func() {
for (var j = arr.length; j > 0; j--) {
for (var i = 0; i < (arr.length-1); i++) {
if (arr[i] > arr[i + 1]) {
swap(i+1, i);
}
};
}
function swap(smaller, bigger) {
var tmpBigger = arr[bigger];
var tmpSmaller = arr[smaller];
arr[bigger] = tmpSmaller
arr[smaller] = tmpBigger;
setTimeout(function() {
$("#" + tmpSmaller).insertBefore("#" + tmpBigger);
}, ++counter * 500);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="func()">Click</button>
I am not sure what Im doing wrong in my code, but it sorts the numbers correctly, but also leaves this output:
Array after sorting: ,,,,,,,7,,9,,11,,,,,,,,,,,22,,,,,,,,,,,,,,,,,,,,42,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,88,,,,,,,,,,,99
Please help me troubleshoot my code!
var swap = function(array, firstIndex, secondIndex) {
var temp = array[firstIndex];
array[firstIndex] = array[secondIndex];
array[secondIndex] = temp;
};
var indexOfMinimum = function(array, startIndex) {
var minValue = array[startIndex];
var minIndex = startIndex;
for(var i = minIndex + 1; i < array.length; i++) {
if(array[i] < minValue) {
minIndex = i;
minValue = array[i];
}
}
return minIndex;
};
var selectionSort = function(array) {
var length = array.length;
for(var i = 0; i < length; i++){
var min = indexOfMinimum(array,array[i]);
swap(array, i, min);
}
};
var array = [22, 11, 99, 88, 9, 7, 42];
selectionSort(array);
println("Array after sorting: " + array);
Program.assertEqual(array, [7, 9, 11, 22, 42, 88, 99]);
You don't want the value at index i, you just want i itself.
var min = indexOfMinimum(array, array[i]);
should be
var min = indexOfMinimum(array, i);
var selectionSort = function(array) {
var length = array.length;
for(var i = 0; i < length; i++){
var min = indexOfMinimum(array,i);
swap(array, i, min);
}
}
Try this:
var selectionSort = function(array) {
var minIdx;
for(var i = 0; i < array.length - 1; i++){
minIdx = indexOfMinimum(array, i);
swap(array, minIdx, i);
}
return array;