I am writing a program to calculate euclidean distance and then display the lines based, with the below code:
function discreteFrechet(X, Y) {
var M = X.length;
var N = Y.length;
var S = [
[],
[]
];
var backpointers = [
[],
[]
];
var backpaths = [];
var idx;
var path = [];
var paths;
var back = [
[],
[]
];
for (i = 0; i < M; i++) {
for (j = 0; j < N; j++) {
S[i][j] = 0;
backpointers[i][j] = 0;
}
} /* populates S array */
/*sanity check*/
S[0, 0] = euclidian(X, Y, 0, 0);
opt1 = [-1, 0];
opt2 = [0, -1];
opt3 = [-1, -1];
backpaths.push(opt1);
backpaths.push(opt2);
backpaths.push(opt3);
/*backpaths populated*/
for (i = 0; i < M; i++) {
for (j = 0; j < N; j++) {
options = [];
if (i != 0 || j != 0) {
if (i > 0) {
options[0] = S[i - 1, j];
}
if (j > 0) {
options[1] = S[i - 1, j];
}
if (i > 0 && j > 0) {
options[2] = S[i - 1, j];
}
idx = Math.min(options);
backpointers[i][j] = idx;
S[i][j] = Math.max(options[idx], euclidian(X, Y, i, j));
}
}
}
console.log(S);
paths = [
[M - 1, N - 1]
];
path = [
[],
[]
];
path.push(paths);
//Create "path"
i = M - 1;
j = N - 1;
count = 0;
while ((path[path.length - 1][0] != 0) || (path[0][path[1].length - 1] != 0)) {
back[0][1] = backpaths[backpointers[i], [j]];
i += back[0];
j += back[1];
path.push([i, j]);
if (count > 1000) {
console.log("too many loops");
break;
}
count += 1;
}
path.push([0, 0]);
path.reverse();
//returns bottleneck and the path
}
As I am testing, I am running into a problem with an infinite while loop (hence the break statement) any help or suggestions would be greatly appreciated! The goal is to append indicies into the path element, such that I can then take those path indicies and the bottleneck and use them to plot with d3.
Related
I am trying to debug one online coding platform problem. The problem I am facing is to return element occurring most often in array. I am interested in correcting my current code than trying other methods.
function findMostOccured(M, A) { //value of elements in A should not be greater than M
var N = A.length;
var count = new Array(M + 1);
var i;
for (i = 0; i <= M; i++)
count[i] = 0;
var maxOccurence = 1;
var index = -1;
for (i = 0; i < N; i++) {
if (count[A[i]] > 0) {
var tmp = count[A[i]];
if (tmp > maxOccurence) {
maxOccurence = tmp;
index = i;
}
count[A[i]] = tmp + 1;
} else {
count[A[i]] = 1;
}
}
return A[index];
}
Given M = 3 and A = [1, 2, 3, 3, 1, 3, 1]. It should return 3 or 1.
var arr = [1, 2, 3, 3, 1, 3, 1];
var M = 3;
function findMostOccured(M, arr) {
var obj = {};
var result = [];
for (let i = 0; i < arr.length; i++) {
if (obj[arr[i]]) {
obj[arr[i]] = obj[arr[i]] + 1;
} else {
obj[arr[i]] = 1;
}
}
for (var key in obj) {
if (obj[key] === M) {
result.push(parseInt(key));
}
}
return result;
}
console.log(findMostOccured(3, arr));
So... If I input:
4 1 5 3
INSTEAD OF 1,3,4,5
I GET [ 4, 1, 5, 3 ]
Following is the code for merge sort but for the last comparison the program doesn't fetch updated (1,4) (3,5) value rather (4,1) (5,3) thus giving the wrong result.
var a = [4, 1, 5, 3];
q(a);
function q(a) {
var start = 0;
var n = a.length;
var length = parseInt(n / 2);
if (n < 2) {
return n;
}
var l = [], r = [];
for (i = 0; i < length; i++) {
l[i] = a[i]; //left array
}
for (i = 0, j = length; j < n; i++ , j++) {
r[i] = a[j]; //right array
}
q(l); //merge sort left array
q(r); //merge sort right array
comp(l, r);
}
function comp(l, r) {
var k = [], m = 0, i = 0, j = 0;
while (i < ((l.length)) && j < ((r.length))) {
if (l[i] < r[j]) {
k[m] = l[i];
i++;
m++
}
else {
k[m] = r[j];
j++;
m++
}
}
while (i != (l.length)) {
k[m] = l[i];
m++;
i++;
}
while (j != (r.length)) {
k[m] = r[j];
m++;
j++;
}
console.log(k); //for final output it is [ 4, 1, 5, 3 ] instead of [1,3,4,5]
}
You have a couple small problems. The main one is that you are returning the wrong thing from your edge condition:
if (n < 2) {
return n; // n is just a length; doesn't make sense to return it.
}
n is the length, you really want to return the small array here:
if (n < 2) {
return a; // return the array instead
}
Also, you need to pass the result of the recursive call to your comp function. Right now you're just returning the original lists with:
comp(l, r)
Something like this would work better:
let l_sort = q(l); //merge sort left array
let r_sort = q(r); //merge sort right array
return comp(l_sort, r_sort); // merge the arrays when recursion unwinds.
And you need to return things for recursion to work.
Put all together:
function q(a) {
var start = 0;
var n = a.length;
var length = parseInt(n / 2);
if (n < 2) {
return a;
}
var l = [],
r = [];
for (i = 0; i < length; i++) {
l[i] = a[i]; //left array
}
for (i = 0, j = length; j < n; i++, j++) {
r[i] = a[j]; //right array
}
let l_sort = q(l); //merge sort left array
let r_sort = q(r); //merge sort right array
return comp(l_sort, r_sort);
}
function comp(l, r) {
var k = [],
m = 0,
i = 0,
j = 0;
while (i < ((l.length)) && j < ((r.length))) {
if (l[i] < r[j]) {
k[m] = l[i];
i++;
m++
} else {
k[m] = r[j];
j++;
m++
}
}
while (i != (l.length)) {
k[m] = l[i];
m++;
i++;
}
while (j != (r.length)) {
k[m] = r[j];
m++;
j++;
}
return k
}
console.log(q([4, 1, 5, 3]).join(','));
console.log(q([5, 4, 3, 2, 1]).join(','));
console.log(q([2, 3]).join(','));
console.log(q([3, 2]).join(','));
console.log(q([1]).join(','));
I want to count how many times needed for an array to be sorted
var array = [4,2,3,1]
var yourCounter = 0;
for (var i = 0; i < array.length; i++) {
for (var j = 1; j < array.length-j; j++)
if (array[j - 1] > array[j]) {
yourCounter++;
} }
it will return 4 , it should be 5
but if I input array [1,2,3] will correctly return 0 , and if I input array [3,2,1] it will correctly return 3
You could take the given code and swap the values while counting.
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
// Swap adjacent elements if they are in decreasing order
if (a[j] > a[j + 1]) {
swap(a[j], a[j + 1]);
}
}
}
var array = [4, 2, 3, 1],
counter = 0,
i, j, n = array.length;
for (i = 0; i < n; i++) {
for (j = 0; j < n - 1; j++) {
if (array[j] > array[j + 1]) {
[array[j + 1], array[j]] = [array[j], array[j + 1]];
++counter;
}
}
}
console.log(counter);
console.log(array);
I found the solution
var a = [4,2,3,1]
function sortArray(a){
let swapCount = 0;
let swapOccurred = true;
let index = 0;
while (swapOccurred == true && index < a.length){
swapOccurred == false;
if (a[index] > a[index+1]){
let holder = a[index]
a[index] = a[index+1];
a[index+1] = holder;
swapOccurred == true;
swapCount ++;
index = -1;
}
index ++
}
function countSwaps(a) {
let swapCount = 0;
[a, swapCount] = sortArray(a)
console.log(swapCount)
}
return [a, swapCount]
}
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
}
I have a strange problem with my alghoritm, which work if array size less than 114468 and doesn't work if more than 114468. Browse with google chrome. Can't understand why =\ Here is the code:
Generate array:
var arr = [];
var res = [];
for (var i = 114467; i > 0; i--) {
arr.push([i - 1, i]);
}
Find first elem in array to sort:
for (var i = 0, j = arr.length; i < j && res.length == 0; i++) {
var found = false;
for (var m = 0; m < j; m++) {
if (i == m || arr[i][0] == arr[m][1] || arr[i][1] == arr[m][0]) {
found = true;
break;
}
if (!found) {
res.push(arr[m]);
arr.splice(m, 1);
}
}
}
Sorting:
do {
for (var i = 0, j = arr.length; i < j; i++) {
var resLength = res.length - 1;
if (arr[i][1] == res[resLength][0] || arr[i][0] == res[resLength][1]) {
res.push(arr[i]);
arr.splice(i, 1);
break;
}
}
} while (arr.length > 0);
On the step sorting it stops to work.
All code:
var t = function () {
var arr = [];
var res = [];
for (var i = 114467; i > 0; i--) {
arr.push([i - 1, i]);
}
var startsec = new Date().getSeconds();
var startmilsec = new Date().getMilliseconds();
document.write(startsec + '.' + startmilsec + '<br>');
for (var i = 0, j = arr.length; i < j && res.length == 0; i++) {
var found = false;
for (var m = 0; m < j; m++) {
if (i == m || arr[i][0] == arr[m][1] || arr[i][1] == arr[m][0]) {
found = true;
break;
}
if (!found) {
res.push(arr[m]);
arr.splice(m, 1);
}
}
}
do {
for (var i = 0, j = arr.length; i < j; i++) {
var resLength = res.length - 1;
if (arr[i][1] == res[resLength][0] || arr[i][0] == res[resLength][1]) {
res.push(arr[i]);
arr.splice(i, 1);
break;
}
}
} while (arr.length > 0);
var stopsec = new Date().getSeconds();
var stopmilsec = new Date().getMilliseconds();
document.write(stopsec + '.' + stopmilsec + '<br>');
var executionTime = (stopsec - startsec).toString() + "s" + (stopmilsec - startmilsec).toString() + "'ms";
document.write(executionTime + '<br>');
} ();
Do i get my memory limit?
Alright, I isolated the problem. It seems that splice(0,1) slows down astronomically when the array size increases from 114467 to 114468.
Using this custom benchmark:
var t;
function startBench(){t=new Date().getTime();}
function stopBench(){console.log(new Date().getTime()-t);}
var arr=[];
for (var i = 114467; i > 0; i--) {
arr.push([i - 1, i]);
}
var arr2=[];
for (var i = 114468; i > 0; i--) {
arr2.push([i - 1, i]);
}
startBench();
for(i=0;i<1000;i++){
arr.splice(0,1);
}
stopBench();
startBench();
for(i=0;i<1000;i++){
arr2.splice(0,1);
}
stopBench();
I get 3 ms for 114467 and 2740ms for 114468 on Chrome (1000 iterations), but 170 each on Firefox. Maybe you ought to be using a different way to remove elements? Using a variant of bubble sort may work better.
I've submitted a bug report on this. Looking at the reply, it seems to be a valid bug. Hopefully it'll be fixed.