Comparing numerical values of an array against eachother javascript - javascript

let arrayOfNumbers = [1, 2, 3, 4, 5]
What would be the best way to compare the numbers against each other ?
For instance, comparing 1 to 2 then 2 to 3 then 3 to four, and so on ?
function t(a) {
let t = 0
for (let i = 0; i < a.length; i++) {
if (a[t] > a[t + 1]) {
console.log('down')
} else if (a[t] < a[t + 1]) {
console.log('up')
} else if (a[t] === a[t + 1]) {
console.log('no change')
}
t++
}
}

You could start from index one and check the previous value.
function t(a) {
for (let i = 1; i < a.length; i++) {
if (a[i - 1] > a[i]) console.log('down');
else if (a[i - 1] < a[i]) console.log('up');
else console.log('no change');
}
}
t([0, 1, 3, 2, 4, 4, 2]);

If you want to pick up trend then you can do a linear regression.
function linearRegression(y, x) {
var lr = {};
var n = y.length;
var sum_x = 0;
var sum_y = 0;
var sum_xy = 0;
var sum_xx = 0;
var sum_yy = 0;
for (var i = 0; i < y.length; i++) {
sum_x += x[i];
sum_y += y[i];
sum_xy += (x[i] * y[i]);
sum_xx += (x[i] * x[i]);
sum_yy += (y[i] * y[i]);
}
lr['slope'] = (n * sum_xy - sum_x * sum_y) / (n * sum_xx - sum_x * sum_x);
lr['intercept'] = (sum_y - lr.slope * sum_x) / n;
lr['r2'] = Math.pow((n * sum_xy - sum_x * sum_y) / Math.sqrt((n * sum_xx - sum_x * sum_x) * (n * sum_yy - sum_y * sum_y)), 2);
return lr;
}
function find_next(arr) {
var y = [];
for (var i = 0; i < arr.length; i++) {
y.push(i);
}
var reg = linearRegression(y, arr)
// y = a*x + b
// x = (y-b)/a
var next = (arr.length - reg.intercept) / reg.slope
return next
}
console.log(find_next([1, 2, 3, 4, 5]))
console.log(find_next([0, 1, 3, 2, 4, 4, 2]))

Related

Struggling with while loop in this algorithm

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.

finding a triplet in an array that sums up to a given value in javascript

I am trying to solve this problem in JavaScript:
Given an array and a value in JavaScript, find if there is a triplet in array whose sum is equal to the given value. If there is such a triplet present in array, then print the triplet and return true. Else return false.
Now, I wrote some code, and for some reason, it's not working properly.
Here is the code:
A = [1, 4, 45, 6, 10, 8];
sum = 15;
x = A.length;
function find3Numbers(A, x, sum) {
for (i=0; i<(x-2); i++) {
for (j=i+1; j<(x-1); j++) {
for (k=j+1; x; k++) {
if (A[i] + A[j] + A[k] == sum) {
console.log(A[i]);
console.log(A[j]);
console.log(A[k]);
return true
}
return false
}
}
}
}
console.log(find3Numbers(A, x, sum));
Now when I run the code, I get a "false" message.
Any idea, why is that?
You immediately return false if the first triplet you try does not match, when you should only do so after all loops have finished.
A = [1, 4, 45, 6, 10, 8];
sum = 15;
x = A.length;
function find3Numbers(A, x, sum) {
for (i = 0; i < (x - 2); i++) {
for (j = i + 1; j < (x - 1); j++) {
for (k = j + 1; x; k++) {
if (A[i] + A[j] + A[k] == sum) {
console.log(A[i]);
console.log(A[j]);
console.log(A[k]);
return true
}
}
}
}
return false;
}
console.log(find3Numbers(A, x, sum));
Consider sorting the array beforehand for O(n^2) time complexity rather than O(n^3).
Note: O(nlog(n) + n^2) is asymptotically the same as O(n^2).
const find3Numbers = (nums, nums_length, target) => {
nums.sort((a, b) => a - b);
let i = 0;
while (i < nums_length - 2) {
let j = i + 1;
let k = nums_length - 1;
while (j < k) {
curr_sum = nums[i] + nums[j] + nums[k];
if (curr_sum < target) {
j++;
while (j < k && nums[j] == nums[j - 1]) {
j++;
}
} else if (curr_sum > target) {
k--;
while (j < k && nums[k] == nums[k + 1]) {
k--;
}
} else {
return [nums[i], nums[j], nums[k]];
}
}
i++;
while (i < nums_length - 2 && nums[i] == nums[i - 1]) {
i++;
}
}
return [-1, -1, -1];
}
const A = [1, 4, 45, 6, 10, 8];
const x = A.length;
const sum = 15;
console.log(find3Numbers(A, x, sum));

How many times needed to Sort a number in an Array Javascript

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]
}

my attempt at kernel-based image processing with p5.js

var imagething;
var kernel = [[1, 2, 1], [2, 4, 2], [1, 2, 1]];
var sum_of_elements = 0;
var mult_factor = 0.0625;
var bias = 0;
function preload() {
imagething = loadImage('data/image.png');
}
function setup() {
createCanvas(1000, 1000);
imagething.loadPixels();
image(imagething, 0, 0);
makeBlurred(imagething, 1);
image(imagething, 512, 0);
}
function imageIndex(img, x, y) {
return 4 * (x + y * img.width);
}
function makeBlurred() {
for(var i = 0; i < kernel.length; i++) {
for(var j = 0; j < kernel.length; j++) {
sum_of_elements += kernel[i][j];
}
}
for(var x = 0; x < imagething.width; x++) {
for(var y = 0; y < imagething.height; y++) {
var red = 0;
var green = 0;
var blue = 0;
for(var i = 0; i < kernel.length; i++) {
for(var j = 0; j < kernel.length; j++) {
var imageX = (x - kernel.length / 2 + i + imagething.width) % imagething.width;
var imageY = (y - kernel.length / 2 + j + imagething.height) % imagething.height;
var RGB = imageIndex(imagething, imageX, imageY);
var pix = imagething.pixels;
var R = pix[RGB];
var G = pix[RGB + 1];
var B = pix[RGB + 2];
console.log("Start: ",R,G,B);
red += (R * kernel[i][j]);
green += (G * kernel[i][j]);
blue += (B * kernel[i][j]);
}
}
var outR;
var outG;
var outB;
outR = Math.min(Math.max(Math.round(red * mult_factor), 0), 255);
outG = Math.min(Math.max(Math.round(green * mult_factor), 0), 255);
outB = Math.min(Math.max(Math.round(blue * mult_factor), 0), 255);
console.log("End: ", outR, outG, outB);
pix[RGB] = outR;
pix[RGB + 1] = outG;
pix[RGB + 2] = outB;
imagething.updatePixels();
}
}
}
So I am referencing this blog post on kernel-based image processing and I am trying to blur my image. I am using the blur matrix and I use the original image and it should turn out like this but it ends up like this so I must be doing something wrong. Help is much appreciated :)

How to convert one dimensional array into two dimensional array in javascript

Here's my code
const arrayColumn = (arr, n) => arr.map(x => x[n]);
const pcorr = (x, y) => {
let sumX = 0,
sumY = 0,
sumXY = 0,
sumX2 = 0,
sumY2 = 0;
const minLength = x.length = y.length = Math.min(x.length, y.length),
reduce = (xi, idx) => {
const yi = y[idx];
sumX += xi;
sumY += yi;
sumXY += xi * yi;
sumX2 += xi * xi;
sumY2 += yi * yi;
}
x.forEach(reduce);
return (minLength * sumXY - sumX * sumY) / Math.sqrt((minLength * sumX2 - sumX * sumX) * (minLength * sumY2 - sumY * sumY));
};
//create pearson correlation matrix
var r = [[]];
var r_temp = [];
for (var i = 1; i <= _arrData[0].length; i++) {
for (var j = 1; j <= _arrData[0].length; j++) {
r_temp.push(pcorr(arrayColumn(_arrData,i-1),arrayColumn(_arrData,j-1)));
}
}
var r_temp_length = r_temp.length;
for (var i = 1; i <= _arrData[0].length; i++) {
for (var j = 1; j <= _arrData[0].length; j++) {
r[i - 1][j - 1] = r_temp[_arrData[0].length^2 - r_temp_length];
r_temp_length = r_temp_length - 1;
}
}
_arrData is the data from .csv file that already read as matrix 43X4
r_temp result is
[1, 0.1001546791334383, -0.09722360940329312, -0.1119017933192886, 0.1001546791334383, 1, 0.19766088533723247, -0.03844791092325515, -0.09722360940329312, 0.19766088533723247, 1, -0.06161560854254137, -0.1119017933192886, -0.03844791092325515, -0.06161560854254137, 1]
r_temp length is 16
I want to input the r_temp value into r which is gonna be 4x4 Matrix
When I run this code, there's error from this part
r[i - 1][j - 1] = r_temp[_arrData[0].length^2 - r_temp_length];
Uncaught TypeError: Cannot set property '0' of undefined
var r = [];
...
for (var i = 1; i <= _arrData[0].length; i++) {
r[i - 1] = [];
....
It should be var r = []; instead of [[]].
In your code the line r[i - 1] = []; is missing.
It creates the second array for r[i - 1].
thank you all, it works!
//create pearson correlation matrix
var r = [];
for (var i = 1; i <= _arrData[0].length; i++) {
r[i - 1] = [];
}
var r_temp = [];
for (var i = 1; i <= _arrData[0].length; i++) {
for (var j = 1; j <= _arrData[0].length; j++) {
r_temp.push(pcorr(arrayColumn(_arrData,i-1),arrayColumn(_arrData,j-1)));
}
}
var r_temp_length = r_temp.length;
for (var i = 1; i <= _arrData[0].length; i++) {
for (var j = 1; j <= _arrData[0].length; j++) {
r[i - 1][j - 1] = r_temp[Math.pow(_arrData[0].length,2) - r_temp_length];
r_temp_length = r_temp_length - 1;
}
}

Categories

Resources