I am trying to write an insertion sort function that works from right to left.
Not in descending order. I just am not understanding why this code would not properly sort numbers.
function reverseInsertionSort(arr) {
for(var i = arr.length -1; i >0; i--)
var val = arr[i];
var j;
for(j = i; j > 0 && arr[j-1] < val; j--) {
arr[j-1] = arr[j]; }
va=arr[j]; }
function insertionSort(arr) {
for(var i = 1; i < arr.length; i++) {
var val = arr[i];
var j;
for(j = i; j > 0 && arr[j-1] > val; j--) {
arr[j] = arr[j-1]; }
arr[j] = val; }
}
arr[j] = val;
}
}
var length = Math.floor(Math.random()*100)+1;
var arr = new Array();
for(let i = 0; i < length; i++) {
arr.push(Math.floor(Math.random()*10000)+1);
}
var arr2= arr.slice();
reverseInsertionSort(arr2);
console.log(arr2)
It is not sorted, and the output ends in undefined.
arr is being used to test the insertionsort fun
Happy to accept constructive criticism.
This will work.
function reverseInsertionSort(arr) {
for(var i = arr.length-2; i>=0; i--) {
var value = arr[i];
var j;
for(j = i; ((j < arr.length) && (arr[j+1] > value)); j++){
arr[j] = arr[j+1];
}
arr[j] = value;
}
return arr;
}
//test
var inputArray = [3,2,4,5,1,10,23];
var resultArray = reverseInsertionSort(inputArray);
console.log(resultArray); //[23, 10, 5, 4, 3, 2, 1]
You should start the outer loop from the last element ie. len-1. The undefined member of the array is created due to your outer loop starting from arr.length .
Try this :
function insSort(arr){
for(var i=arr.length-1;i>=0;i--){
key=arr[i];
j=i+1;
while(j<arr.length&&arr[j]<=key){
arr[j-1]=arr[j];
j++;
}
arr[j-1]=key;
}
}
var length = Math.floor(Math.random()*100)+1;
var arr = new Array();
for(let i = 0; i < length; i++) {
arr.push(Math.floor(Math.random()*10000)+1);
}
console.log(arr);
insSort(arr);
console.log(arr);
Related
This is my function, on my console I got the sorted array, with a property on my array object which's key is undefined, and the property's value is the last item of the array. My question is how did that property was created, why, and what does a property called undefined mean.
const selectionSort = function (arr) {
for (let i = 0; i < arr.length; i++) {
let smallest = arr[i];
let currentIndex;
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < smallest) {
smallest = arr[j];
currentIndex = j;
}
if (j === arr.length - 1) {
arr[currentIndex] = arr[i];
arr[i] = smallest;
}
}
}
return arr;
};
The problem is that you assign value to currentIndex inside the first if condition, so in an unsorted array you use an unassigned variable as index.
const selectionSort = function (arr) {
for (let i = 0; i < arr.length; i++) {
let smallest = arr[i];
let currentIndex;
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < smallest) {
smallest = arr[j];
currentIndex = j;
}
if (j === arr.length - 1) {
console.log("currentIndex:", currentIndex);
arr[currentIndex] = arr[i];
arr[i] = smallest;
}
}
}
return arr;
};
let res1 = selectionSort([5,8]);
console.log(res1);
let res2 = selectionSort([5,3]);
console.log(res2);
What you are trying to do is called bubble-sort, and here is the code for it:
const selectionSort = function (arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[i]) {
let tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
return arr;
};
let res1 = selectionSort([5,8,1,99,45]);
console.log(res1);
let res2 = selectionSort([5,6,7,8]);
console.log(res2);
I am attempting to write a javascript file that has a insertion sort function, a function to check a sorted array and return true or false, and an insertion sort function that works from the end of the array index to the beginning.
Here is the code i have
function insertionSort(arr) {
for(var i = 1; i < arr.length; i++) {
var val = arr[i]; var j; for(j = i; j > 0 && arr[j-1] > val; j--) {
arr[j] = arr[j-1]; } arr[j] = val; }
}
function reverseInsertionSort(arr) {
for(var i = arr.length; i >1; i--)
{ var val = arr[i]; var j;
for(j = i; j > 0 && arr[j-1] > val; j--)
{ arr[j] = arr[j-1]; } arr[j] = val;
} }
var length = Math.floor(Math.random()*100)+1;
var arr = new Array();
for(let i = 0; i < length; i++) {
arr.push(Math.floor(Math.random()*10000)+1);
}
console.log(arr);
//function sortCheck(arr) {
//for( var i = 0 ; i < arr.length; i++){
// if(arr[i]>rr[i+1]){
// return false
// }
//}
//return true}
var sortedArr = insertionSort(arr);
console.log(sortedArr);
console.log("And with reverse \n");
var reverseSortedArr = reverseInsertionSort(arr);
console.log(reverseSortedArr);
//console.log(sortCheck(sortedArr));
The issue I am having right now is that sortedArr is undefined when output with console.log, it appears that the issue is that my function is "undefined" but seeing how i define it above, i dont understand how that is.
Your insertionSort function doesn't return a value, it modifies the array passed as an argument. Instead of var sortedArr = insertionSort(arr), just call insertionSort(arr) and then do console.log(arr).
You have to return arr from the function. It is not returning anything that's why you are getting undefined
function insertionSort(arr) {
for(var i = 1; i < arr.length; i++) {
var val = arr[i]; var j; for(j = i; j > 0 && arr[j-1] > val; j--) {
arr[j] = arr[j-1]; } arr[j] = val; }
return arr; }
function reverseInsertionSort(arr) {
for(var i = arr.length; i >1; i--)
{ var val = arr[i]; var j;
for(j = i; j > 0 && arr[j-1] > val; j--)
{ arr[j] = arr[j-1]; } arr[j] = val;
} return arr}
var length = Math.floor(Math.random()*100)+1;
var arr = new Array();
for(let i = 0; i < length; i++) {
arr.push(Math.floor(Math.random()*10000)+1);
}
console.log(arr);
var sortedArr = insertionSort(arr);
console.log(sortedArr);
console.log("And with reverse \n");
var reverseSortedArr = reverseInsertionSort(arr);
console.log(reverseSortedArr);
//console.log(sortCheck(sortedArr));
Make sure you return the array from the function(s). Since you currently are not, assigning the function to a variable would not yield any particular value.
function insertionSort(arr) {
for(var i = 1; i < arr.length; i++) {
var val = arr[i];
var j;
for(j = i; j > 0 && arr[j-1] > val; j--) {
arr[j] = arr[j-1];
}
arr[j] = val;
}
return arr
}
I have the following function to get all of the substrings from a string in JavaScript. I know it's not correct but I feel like I am going about it the right way. Any advice would be great.
var theString = 'somerandomword',
allSubstrings = [];
getAllSubstrings(theString);
function getAllSubstrings(str) {
var start = 1;
for ( var i = 0; i < str.length; i++ ) {
allSubstrings.push( str.substring(start,i) );
}
}
console.log(allSubstrings)
Edit: Apologies if my question is unclear. By substring I mean all combinations of letters from the string (do not have to be actual words) So if the string was 'abc' you could have [a, ab, abc, b, ba, bac etc...] Thank you for all the responses.
You need two nested loop for the sub strings.
function getAllSubstrings(str) {
var i, j, result = [];
for (i = 0; i < str.length; i++) {
for (j = i + 1; j < str.length + 1; j++) {
result.push(str.slice(i, j));
}
}
return result;
}
var theString = 'somerandomword';
console.log(getAllSubstrings(theString));
.as-console-wrapper { max-height: 100% !important; top: 0; }
A modified version of Accepted Answer. In order to give the minimum string length for permutation
function getAllSubstrings(str, size) {
var i, j, result = [];
size = (size || 0);
for (i = 0; i < str.length; i++) {
for (j = str.length; j - i >= size; j--) {
result.push(str.slice(i, j));
}
}
return result;
}
var theString = 'somerandomword';
console.log(getAllSubstrings(theString, 6));
Below is a recursive solution to the problem
let result = [];
function subsetsOfString(str, curr = '', index = 0) {
if (index == str.length) {
result.push(curr);
return result;
}
subsetsOfString(str, curr, index + 1);
subsetsOfString(str, curr + str[index], index + 1);
}
subsetsOfString("somerandomword");
console.log(result);
An answer with the use of substring function.
function getAllSubstrings(str) {
var res = [];
for (let i = 0; i < str.length; i++) {
for (let j = i + 1; j <= str.length; j++) {
res.push(str.substring(i, j));
}
}
return res;
}
var word = "randomword";
console.log(getAllSubstrings(word));
function generateALlSubstrings(N,str){
for(let i=0; i<N; i++){
for(let j=i+1; j<=N; j++){
console.log(str.substring(i, j));
}
}
}
Below is a simple approach to find all substrings
var arr = "abcde";
for(let i=0; i < arr.length; i++){
for(let j=i; j < arr.length; j++){
let bag ="";
for(let k=i; k<j; k++){
bag = bag + arr[k]
}
console.log(bag)
}
}
function getSubstrings(s){
//if string passed is null or undefined or empty string
if(!s) return [];
let substrings = [];
for(let length = 1 ; length <= s.length; length++){
for(let i = 0 ; (i + length) <= s.length ; i++){
substrings.push(s.substr(i, length));
}
}
return substrings;
}
I'm having a little trouble with my attempt at this problem. Code Below:
function pasc(n){
var result = [[1]];
for (var row = 1; row < n; row++){
for (var col = 1; col <= row; col++){
result[row][col] = result[row - 1][col] + result[row - 1][col - 1];
}
}
return result;
}
pasc(10)
for (var i = 0; i < result.length; i++){
document.write(result[i]+"<br>");
}
It seems the problem hinges on assigning values to an array using an expression like myArray[1][1] = "foo"
I'm confused about this because I can do this: var myArray = []; myArray[4] = "foo" which seems to suggest that an element can be created at an arbitrary position in a 1 dimensional array, but not with 2 dimensions.
Any help with clearing up my misconceptions appreciated.
The Pascal's Triangle can be printed using recursion
Below is the code snippet that works recursively.
We have a recursive function pascalRecursive(n, a) that works up till the number of rows are printed. Each row is a element of the 2-D array ('a' in this case)
var numRows = 10,
triangle,
start,
stop;
// N is the no. of rows/tiers
// a is the 2-D array consisting of the row content
function pascalRecursive(n, a) {
if (n < 2) return a;
var prevRow = a[a.length-1];
var curRow = [1];
for (var i = 1; i < prevRow.length; i++) {
curRow[i] = prevRow[i] + prevRow[i-1];
}
curRow.push(1);
a.push(curRow);
return pascalRecursive(n-1, a); // Call the function recursively
}
var triangle = pascalRecursive(numRows, [[1]]);
for(var i = 0; i < triangle.length; i++)
console.log(triangle[i]+"\n");
JavaScript doesn't have two-dimensional arrays. What it does have is arrays that happen to contain other arrays. So, yes, you can assign a value to any arbitrary position in an array, and the array will magically make itself big enough, filling in any gaps with 'undefined'... but you can't assign a value to any position in a sub-array that you haven't explicitly created yet. You have to assign sub-arrays to the positions of the first array before you can assign values to the positions of the sub-arrays.
Replacing
for (var row = 1; row < n; row++){
for (var col = 1; col <= row; col++){
with
for (var row = 1; row < n; row++){
result[row] = [];
for (var col = 1; col <= row; col++){
should do it. Assuming all of your indexing logic is correct, anyway. You've got some problems there, too, since your initial array only contains a single value, so result[row][col] = result[row - 1][col] + result[row - 1][col - 1]; is accessing at least one cell that has never been defined.
Thanks Logan R. Kearsley. I have now solved it:
function pasc(n){
var result = [];
result[0] = [1];
result[1] = [1,1];
for (var row = 2; row < n; row++){
result[row] = [1];
for (var col = 1; col <= row -1; col++){
result[row][col] = result[row-1][col] + result[row-1][col-1];
result[row].push(1);
}
}
return result;
}
for (var i = 0; i < pasc(10).length; i++){
document.write(pasc(10)[i]+"<br>");
console.log(pasc(10)[i]+"<br>");
}
you can create Pascal's triangle using below code:
function pascal(n) {
var arr = [];
if (n == 1) {
arr[0] = [];
arr[0][0] = 1;
} else if (n == 2) {
arr[0] = [];
arr[0][0] = 1;
arr[1] = [];
arr[1][0] = 1;
arr[1][1] = 1;
} else if (n > 2) {
arr[0] = [];
arr[1] = [];
arr[0][0] = 1;
arr[1][0] = 1;
arr[1][1] = 1;
for (i = 2; i < n; i++) {
arr[i] = [];
arr[i][0] = 1;
for (j = 1; j < i; j++) {
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
}
arr[i][j] = 1;
}
}
console.log(arr);
for (i = 0; i < arr.length; i++) {
console.log(arr[i].join(' '))
}
}
function pascal(n) {
var arr = [];
if (n == 1) {
arr[0] = [];
arr[0][0] = 1;
} else if (n == 2) {
arr[0] = [];
arr[0][0] = 1;
arr[1] = [];
arr[1][0] = 1;
arr[1][1] = 1;
} else if (n > 2) {
arr[0] = [];
arr[1] = [];
arr[0][0] = 1;
arr[1][0] = 1;
arr[1][1] = 1;
for (i = 2; i < n; i++) {
arr[i] = [];
arr[i][0] = 1;
for (j = 1; j < i; j++) {
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
}
arr[i][j] = 1;
}
}
console.log(arr);
for (i = 0; i < arr.length; i++) {
console.log(arr[i].join(' '))
}
}
pascal(5)
This function will calculate Pascal's Triangle for "n" number of rows. It will create an object that holds "n" number of arrays, which are created as needed in the second/inner for loop.
function getPascalsTriangle(n) {
var arr = {};
for(var row = 0; row < n; row++) {
arr[row] = [];
for(var col = 0; col < row+1; col++) {
if(col === 0 || col === row) {
arr[row][col] = 1;
} else {
arr[row][col] = arr[row-1][col-1] + arr[row-1][col];
}
}
}
return arr;
}
console.log(getPascalsTriangle(5));
Floyd triangle
You can try the following code for a Floyd triangle
var prevNumber=1,i,depth=10;
for(i=0;i<depth;i++){
tempStr = "";j=0;
while(j<= i){
tempStr = tempStr + " " + prevNumber;
j++;
prevNumber++;
}
console.log(tempStr);
}
You can create arbitrary 2d arrays and store it in there and return the correct Pascal.
JavaScript does not have a special syntax for creating multidimensional arrays. A common workaround is to create an array of arrays in nested loops.
source
Here is my version of the solution
function pascal(input) {
var result = [[1], [1,1]];
if (input < 0) {
return [];
}
if (input === 0) {
return result[0];
}
for(var j = result.length-1; j < input; j++) {
var newArray = [];
var firstItem = result[j][0];
var lastItem = result[j][result[j].length -1];
newArray.push(firstItem);
for (var i =1; i <= j; i++) {
console.log(result[j][i-1], result[j][i]);
newArray.push(sum(result[j][i-1], result[j][i]));
}
newArray.push(lastItem);
result.push(newArray);
}
return result[input];
}
function sum(one, two) {
return one + two;
}
Here is the code i created for pascal triangle in javascript
'use strict'
let noOfCoinFlipped = 5
let probabiltyOfnoOfHead = 2
var dataStorer = [];
for(let i=0;i<=noOfCoinFlipped;i++){
dataStorer[i]=[];
for(let j=0;j<=i;j++){
if(i==0){
dataStorer[i][j] = 1;
}
else{
let param1 = (j==0)?0:dataStorer[i-1][j-1];
let param2 = dataStorer[i-1][j]?dataStorer[i-1][j]:0;
dataStorer[i][j] = param1+param2;
}
}
}
let totalPoints = dataStorer[noOfCoinFlipped].reduce((s,n)=>{return s+n;})
let successPoints = dataStorer[noOfCoinFlipped][probabiltyOfnoOfHead];
console.log(successPoints*100/totalPoints)
Here is the link as well
http://rextester.com/TZX59990
This is my solve:
function pascalTri(n){
let arr=[];
let c=0;
for(let i=1;i<=n;i++){
arr.push(1);
let len=arr.length;
if(i>1){
if(i>2){
for(let j=1;j<=(i-2);j++){
let idx=(len-(2*i)+j+2+c);
let val=arr[idx]+arr[idx+1];
arr.push(val);
}
c++;
}
arr.push(1);
}
}
return arr;
}
let pascalArr=pascalTri(7);
console.log(pascalArr);
here is the pattern for n = 3
#
##
###
here is js code to print this.
function staircase(n) {
for(var i=0 ; i<n ; i++) {
for(var j=n-1 ; j>i ; j--)
process.stdout.write(" ");
for(var k=0 ; k<=i; k++) {
process.stdout.write("#");
}
process.stdout.write("\n");
}
}
class PascalTriangle {
constructor(n) {
this.n = n;
}
factoriel(m) {
let result = 1;
if (m === 0) {
return 1;
}
while (m > 0) {
result *= m;
m--;
}
return result;
}
fill() {
let arr = [];
for (let i = 0; i < this.n; i++) {
arr.push([]);
}
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j <= i; j++) {
arr[i].push(this.factoriel(i) / (this.factoriel(j) * this.factoriel(i - j)));
}
}
return arr;
}
}
var m = prompt("enter number:");
var arrMain = new Array();
for (var i = 0; i < m; i++) {
arrMain[i] = [];
}
for (var i = 0; i < m; i++) {
if (i == 0) {
arrMain[i] = [1];
} else if (i == 1) {
(arrMain[i]) = [1, 1];
} else {
for (var j = 0; j <= i; j++) {
if (j == 0 || j == arrMain[i - 1].length) {
arrMain[i][j] = 1;
} else {
arrMain[i][j] = arrMain[i - 1][j] + arrMain[i - 1][j - 1];
}
}
}
document.write(arrMain[i] + "<br>");
}
This is my take on this problem by gaining access to the previous row.
const generate = numRows => {
const triangle = [[1]]
for (let i = 1; i < numRows; i++) {
// Previous row
const previous = triangle[i - 1]
// Current row
const current = new Array(i + 1).fill(1)
// Populate the current row with the previous
// row's values
for (let j = 1; j < i; j++) {
current[j] = previous[j - 1] + previous[j]
}
// Add to triangle result
triangle.push(current)
}
return triangle
}
Can anyone tell me why all the object.num's print as 1? This is driving me mad. Somehow after the for loop the values of the object.num = 1 no matter what, even though they are never set to 1. Please copy the entire segment to debug.
<script type="text/javascript">
window.addEventListener("load", main, false);
const n = 4;
function main()
{
var belt = new Array(4*n);
initArr(belt);
printIt(belt);
populateArr(belt);
printIt(belt);
reorder(belt);
printIt(belt);
}
function populateArr(arr)
{
var a = {name:"a", num:0};
var b = {name:"b", num:0};
var end = arr.length;
var i = end-1;
for(var temp = n; temp > 0; temp--)
{
a.num = temp;
arr[i] = a;
i-=2;
}
i = end-2;
for(var temp = n; temp > 0; temp--)
{
b.num = temp;
arr[i] = b;
i-=2;
}
return arr;
}
function printIt(arr)
{
var tempArr = new Array(arr.length);
for(var i=0; i < arr.length; i++)
{
tempArr[i] = arr[i].name + arr[i].num;
}
console.log(tempArr);
}
function initArr(arr)
{
var nothing = {name:null, num:0};
for(var i=0; i<arr.length; i++)
{
arr[i] = nothing;
}
return arr;
}
function reorder(arr)
{
var nothing = {name:null, num:0};
var counter = 0;
var aIndex = 0;
var bIndex = null;
for(var i=0; i < arr.length; i++)
{
if(arr[i].name === "b" && bIndex === null)//first b doesn't get moved
{
bIndex = i+1;
}
else if(arr[i].name === "a")
{
arr[aIndex] = arr[i];
arr[i] = nothing;
counter++;
aIndex++;
}
else if(arr[i].name ==="b")
{
arr[bIndex] = arr[i];
arr[i] = nothing;
counter++;
bIndex++;
}
}
console.log("count: " + counter);
console.log("n: " + n);
return arr;
}
</script>
Somehow after the for loop the values of the object.num = 1 no matter what, even though they are never set to 1.
Yes "they" are - "they're" set to 1 in the last iteration of this loop:
for(var temp = n; temp > 0; temp--)
{
a.num = temp;
arr[i] = a;
i-=2;
}
The last iteration of that loop is when temp is 1.
Now, you've only actually got one object - and you're setting every element of the array to be a reference to that object. That's why all the values in the array look the same. If you want to create a different object each time, you should use:
for(var temp = n; temp > 0; temp--)
{
arr[i] = { name: "a", num: temp };
i -= 2;
}