Here is the link to my JavaScript Insertion Sort Algorithm
Quite simply, I just can't figure out why I can't get that pesky arr[0] to get sorted correctly. I've tried everything I know of. sigh
It's pretty close though.
Any idea's
var aoo = [5,2,4,6,1,3];
function jInsertionSort(a) {
for(var j=2; j<a.length; j++){
//console.log(j);
var key = a[j];
var i = j - 1;
while (i > 0 && a[i] > key) {
a[i+1] = a[i];
i = i-1;
}
a[i+1]=key;
}
return a;
}
var aooSorted = jInsertionSort(aoo);
console.log("jInsertionSort = ["+aooSorted+"]");
?
JavaScript Insertion Sort Algorithm
You almost got it, this works:
var aoo = [5,2,4,6,1,3];
function jInsertionSort(a) {
for(var j=1; j<a.length; j++){
var key = a[j];
var i = j;
while (i > 0 && a[i-1] > key) {
a[i] = a[i - 1];
a[i - 1] = key;
i = i-1;
}
}
return a;
}
var aooSorted = jInsertionSort(aoo);
console.log("jInsertionSort = ["+aooSorted+"]");
var aoo = [5,2,4,6,1,3];
function jInsertionSort (a) {
for (var i = 0; i < a.length; i++) {
var k = a[i];
for (var j = i; j > 0 && k < a[j - 1]; j--)
a[j] = a[j - 1];
a[j] = k;
}
return a;
}
var aooSorted = jInsertionSort(aoo);
console.log("jInsertionSort = ["+aooSorted+"]");
Related
I have tried setting Error.stackTraceLimit = Infinity in chrome and firefox, but no effect.
I'm just trying to multiply two matrixes in a recursive way.
it breakes at the point of a [32][32] matrix.
Here is the code that i run, a simple devide and conquer matrix multiplication
first i generate 2 random matrices and then multiply them
function divideConquer(a, b) {
var i = 0,
j = 0,
k = 0;
var c = [];
let row = [];
// creating the output
for (let l = 0; l < a.length; l++) {
row = [];
for (let m = 0; m < b[0].length; m++) {
row.push(parseInt(0));
}
c.push(row);
}
multiplyRecursion(a, b);
return c;
function multiplyRecursion(a, b) {
// If all rows traversed
if (i >= a.length)
return;
// If i < row1
if (j < b[0].length) {
if (k < a[0].length) {
c[i][j] += a[i][k] * b[k][j];
k++;
multiplyRecursion(a, b);
}
k = 0;
j++;
multiplyRecursion(a, b);
}
j = 0;
i++;
multiplyRecursion(a, b);
}
}
function generateRandomMatrix(n) {
let row = [],
matrix = [];
for (let i = 0; i < n; i++) {
row = [];
for (let j = 0; j < n; j++) {
row.push(Math.floor(Math.random() * 10));
}
matrix.push(row);
}
return matrix;
}
let a = generateRandomMatrix(32);
let b = generateRandomMatrix(32);
console.log(divideConquer(a, b));
What is the most JS-style way to solve the following problem?
Given an array A, find all arrays B, such that for i <= A.length: B[i] <= A[i]. Example of what I expect:
#Input
A = [1,2,0]
#Output
B = [[0,0,0],
[1,0,0],
[1,1,0],
[1,2,0],
[0,1,0],
[0,2,0]]
In Python I used:
B = [[]];
for t in [range(e+1) for e in A]:
B = [x+[y] for x in B for y in t]
Thanks in advance!
Use the following code (any loop for one item of the array a):
var a = [1, 2, 0], b = [];
for (var i = 0; i < a[0]; i++) {
for (var j = 0; j < a[1]; j++) {
for (var k = 0; k <= a[2]; k++) {
b.push([i, j, k]);
}
}
}
If you know the numebr of items in the array a only on runtime, use the following recursive function:
function fillArray(source, dest, recursionLevel, tempArr) {
if (recursionLevel >= source.length) {
dest.push(tempArr);
return;
}
for (var i = 0; i <= source[recursionLevel]; i++) {
var tempArr2 = tempArr.slice(); // Copy tempArr
tempArr2.push(i);
fillArray(source, dest, recursionLevel + 1, tempArr2);
}
}
fillArray(a, b, 0, []);
I found this solution. I'm sure it can be coded in a much nicer way. However, it works and I hope you find it useful
all_combinations(A){
var B = [];
for (var i = 0; i < A[0] + 1; i++) {
B.push([i]);
}
for (var i = 1; i < A.length; i++) {
var _tmp_array = [];
for (var j = 0; j < A[i] + 1; j++) {
for (var k = 0; k < B.length; k++) {
var _new_element = B[k].concat([j]);
_tmp_array.push(_new_element);
}
}
B = _tmp_array;
}
return B;
}
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));
So I need to implement a javascript method which will return true or false depending on if the masterString contains a subString.
I did something like following but not sure if this is the right approach :
function contains(masterString, subString) {
if(subString.length > masterString.length){
return false;
}
for(var i=subString.length-1; i<masterString.length; i++){
if(concatString(i - subString.length-1, i, masterString) === subString){
return true;
}
}
return false;
}
function concatString(index1, index2, string){
var conString = '';
console.log(index1, index2-1, string);
for(var i=index1; i<index2-1; i++){
conString += string[i];
}
console.log(conString);
return conString;
}
contains('abcd', 'bc');
It isn't working fine though.
Can we implement it? Thanks :)
For each possible index, test if subString is on that index of masterString.
var indexOf = function(masterString,subString){
for(var i = 0 ; i < masterString.length - subString.length + 1; i++){
var match = true;
for(var j = 0; j < subString.length; j++){
if(masterString[i + j] !== subString[j]){
match = false;
break;
}
}
if(match)
return i;
}
return -1;
}
var contains = function(master,sub){
return indexOf(master,sub) !== -1;
}
Note: There are faster algorithms to achieve that like Knuth–Morris–Pratt.
You have a good solution. But I think mine is easier.
By the way: I think .length is a javascript funciton too.
function length(string){
var count = 0;
while(string[count] != undefined)
count++;
return count;
}
function contains(masterString, subString) {
var masterStringLength = length(masterString);
var subStringLength = length(subString);
for(var i = 0; i <= masterStringLength - subStringLength; i++)
{
var count = 0;
for(var k = 0; k < subStringLength; k++)
{
if(masterString[i + k] == subString[k])
count++;
else
break;
}
if(count == subStringLength)
return true;
}
return false;
}
console.log(contains('abcdefgh', 'bcde'));
console.log(contains('abcdefgh', 'ab'));
console.log(contains('abcdefgh', 'fgh'));
You can use a nested loop:
function contains(masterString, subString) {
outerloop:
for(var i=0; i <= masterString.length-subString.length; ++i) {
for(var j=0; j<subString.length; ++j)
if(masterString[i + j] !== subString[j]) continue outerloop;
return true;
}
return false;
}
Of course, using native methods you could achieve better performance.
This is similar to longest common subsequence See this.
this code solves your issue.
function contains(masterString, subString) {
if (findCommonSubsequence(masterString, subString) == subString)
alert(true);
else
alert(false);
}
function findCommonSubsequence(a, b) {
var table = [],
aLen = a.length,
bLen = b.length;
squareLen = Math.max(aLen, bLen);
// Initialize a table of zeros
for (var i = 0; i <= squareLen ; i++) {
table.push([]);
for (var j = 0; j <= squareLen; j++) {
table[i][j] = 0;
}
}
// Create a table of counts
for (var i = 1; i <= aLen; i++) {
for (var j = 1; j <= bLen; j++) {
if (a[i - 1] == b[j - 1]) {
table[i][j] = table[i - 1][j - 1] + 1;
} else {
table[i][j] = Math.max(table[i - 1][j], table[i][j - 1]);
}
}
}
// Move backwards along the table
i = aLen, j = bLen, LCS = [];
while (i > 0 && j > 0) {
if (a[i - 1] == b[j - 1]) {
LCS.push(a[i - 1]);
i -= 1;
j -= 1;
} else {
if (table[i][j - 1] >= table[i - 1][j]) {
j -= 1;
} else {
i -= 1;
}
}
}
return(LCS.reverse().join(''));
}
Your question doesn't have enough odd constraints, so let's do it
without for-loops as well, with some help from ES6.
// Cf. Array.prototype.some
const any = (f, [x,...xs]) =>
x === undefined ? false : f(x) || any(f,xs);
// Return true if the first iterable is a prefix of the second.
const isprefix = ([x,...xs], [y,...ys]) =>
x === undefined ? true : x == y && isprefix(xs,ys);
// tails('abc') --> [['a','b','c'], ['b','c'], ['c']]
const tails = ([x,...xs]) =>
x === undefined ? [] : [[x,...xs],...tails(xs)];
// If needle is empty, or is a prefix of any of tails(haystack), return true.
const contains = (haystack, needle) =>
needle.length ? any(bale => isprefix(needle, bale), tails(haystack)) : true;
const tests = [
['aaafoobar', 'foo'],
['foo', 'foo'],
['fo', 'foo'],
['', 'f'],
['f', ''],
['', '']
];
tests.forEach(test => console.log(JSON.stringify(test), contains(test[0], test[1])));
You can do like this
var substr = "test",
masterstr = "test1",
checksubstr = (ms,ss) => !!~ms.indexOf(ss);
console.log(checksubstr(masterstr,substr));
I come from a Ruby background, which features an enumerable class. In Ruby, I can easily find combinations of array elements.
array.combination(2).count
I know that JavaScript doesn't feature such built in functions, so I was wondering how I could implement this in JS. I was thinking something like
I have an array as follows
var numbers = [9,7,12]
var combos = []
for (var i = 0; i < numbers.length; i++) {
combos.push([numbers[i], numbers[i+1])
}
By the way, the possible combos are
[9,7], [9,12] and [7,12]
so by calling the length function on this array, 3 would be returned.
Any ideas?
How about:
for (var i = 0; i < numbers.length; i++)
for (var j = i + 1; j < numbers.length; j++)
combos.push([numbers[i], numbers[j]]);
Are you strictly talking about 2-combinations of the array or are you interested in a k-combinations solution?
Found this in this gist
function k_combinations(set, k) {
var i, j, combs, head, tailcombs;
if (k > set.length || k <= 0) {
return [];
}
if (k == set.length) {
return [set];
}
if (k == 1) {
combs = [];
for (i = 0; i < set.length; i++) {
combs.push([set[i]]);
}
return combs;
}
// Assert {1 < k < set.length}
combs = [];
for (i = 0; i < set.length - k + 1; i++) {
head = set.slice(i, i+1);
tailcombs = k_combinations(set.slice(i + 1), k - 1);
for (j = 0; j < tailcombs.length; j++) {
combs.push(head.concat(tailcombs[j]));
}
}
return combs;
}
Here's a recursive function, which should work for any number:
function combination(arr, num) {
var r= [];
for(var i = 0 ; i < arr.length ; i++) {
if(num===1) r.push([arr[i]]);
else {
combination(arr.slice(i+1), num-1).forEach(function(val) {
r.push([].concat(arr[i], val));
});
}
}
return r;
} //combination
Working Fiddle