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);
Related
I'm trying to return a message if one of the argument is not a number. Otherwise continue with the function.
I'm trying this but it's not working as I'm expecting.. ..Please, any help?
function findingPairs(arr, value){
if(isNaN(arr) || isNaN(value)){
return "Please, introduce just numbers"
}
let sum = 0;
let finalOutput = [];
for(let i = 0; i < arr.length; i++){
let numA = arr[i]
console.log(numA)
} for(let j = 1; j < arr.length; j++){
let numB = arr[j]
console.log(numB)
}
}
findingPairs([1,3,7], 9)
You can use Number.isInteger to check if something is a number.
And Array.every over the array to check all the array.
Also I'm throwing an Error instead of returning a value because that's what is expected usually.
Error Docs
function findingPairs(arr, value) {
if (!arr.every(Number.isInteger) || !Number.isInteger(value)) {
throw new Error("Please, introduce just numbers");
}
let sum = 0;
let finalOutput = [];
for (let i = 0; i < arr.length; i++) {
let numA = arr[i];
console.log(numA);
}
for (let j = 1; j < arr.length; j++) {
let numB = arr[j];
console.log(numB);
}
}
const value = findingPairs([1, 3, 7], 9);
const value2 = findingPairs([1, "a", 7], 9); // Will throw
const value2 = findingPairs([1, 23, 7], "hey"); // Will throw
console.log(value);
You need to check if each element of the array is a number, you can use Array.prototype.some() to test if one element of the array respects a condition
function findingPairs(arr, value){
if(arr.some(isNaN) || isNaN(value)){
return "Please, introduce just numbers"
}
let sum = 0;
let finalOutput = [];
for(let i = 0; i < arr.length; i++){
let numA = arr[i]
console.log(numA)
}
for(let j = 1; j < arr.length; j++){
let numB = arr[j]
console.log(numB)
}
}
findingPairs([1,3,7], 9)
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);
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
}
The algorithm is taken from LeetCode: https://leetcode.com/problems/maximum-product-of-word-lengths/description/
Here is the jsperf I created (I have some local tests which gives the same result): https://jsperf.com/maximum-product-of-word-lengths
Here is the first "slow" implementation:
function maxProduct (words) {
if (!words || !words.length) return 0;
let len = words.length;
let values = [];
// console.log(values)
for (let i = 0; i < len; ++i) {
let tmp = words[i];
let num = 0, len = tmp.length;
for (let j = 0; j < len; ++j) {
num |= 1 << (tmp.charCodeAt(j) - 'a'.charCodeAt(0));
}
values[i] = {
num: num,
len: tmp.length
};
}
let maxProduct = 0;
for (let i = 0; i < len; ++i) {
for (let j = 0; j < len; ++j) {
if ((values[i].num & values[j].num) == 0) {
maxProduct = Math.max(maxProduct, values[i].len * values[j].len);
}
}
}
return maxProduct;
};
Here is the "fast" implementation:
function maxProductFast (words) {
var temp = [];
for(var i = 0; i < words.length; i++){
var tempObj = {};
tempObj.item = words[i];
var num = 0;
for(var j = 0; j < words[i].length; j++){
num |= 1 << (words[i].charCodeAt(j) - 97);
}
tempObj.num = num;
temp.push(tempObj);
}
var res = 0;
for(var i = 0; i < temp.length; i++){
for(var j = i + 1; j < temp.length; j++){
var item1 = temp[i];
var item2 = temp[j];
if((item1.num & item2.num) == 0) {
res = Math.max(res, item1.item.length * item2.item.length);
}
}
}
return res;
}
They're not the same. The second algorithm has a loop with a complexity of (n*(n+1))/2 where each progressive step is from i+1 to the length of temp. the first algorithm has a two nested for loops each with a cost of n^2. the complexity of both will reduce to O(n^2). I believe that both of these will have a similar performance with a significantly large enough set.
The reason you would do n+1 for each sub iteration is because you are trying to find the max of any pair of items. if you place your elements in a grid you will notice that any diagonal pair a_3 * a_2 = a_2 * a_3 produces the same value. you can basically halve the collection and save a few cycles.
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
}