how to find mean and variance using reduce()? - javascript

I wrote a function which returns mean and variance of the given list using only reduce().
var list = [1, 2, 3, 4];
var math = getMeanAndVar(list);
function getMeanAndVar(list) {
var res = list.reduce(function(lis, cur, ind, arr) {
var meanTot = arr.reduce(function(pre, cur) {
return pre + cur;
})
var total = getVariance(arr, tot / arr.length);
return {
mean: meanTot / arr.length,
variance: total / arr.length
}
function getVariance(list, mean) {
return list.reduce(function(pre, cur) {
pre = pre + Math.pow((cur - mean), 2);
return pre;
}, 0)
}
})
return ["Mean:",
res.mean,
"Variance:",
res.variance
].join(' ');
}
console.log(math);
Is there any other way to optimize the code?

Get rid of the outer reduce. It is useless. consider this:
function getMeanAndVar(arr) {
function getVariance(arr, mean) {
return arr.reduce(function(pre, cur) {
pre = pre + Math.pow((cur - mean), 2);
return pre;
}, 0)
}
var meanTot = arr.reduce(function(pre, cur) {
return pre + cur;
})
var total = getVariance(arr, meanTot / arr.length);
var res = {
mean: meanTot / arr.length,
variance: total / arr.length
}
return ["Mean:",
res.mean,
"Variance:",
res.variance
].join(' ');
}
var arr = [1, 2, 3, 4];
var math = getMeanAndVar(arr);
console.log(math);'
Prints:
Mean: 2.5 Variance: 1.25

Related

JavaScript recursive function is returning strange value

Here is my code, why it is returning 13 in place of 4:
const superNumber = (n) => {
let nums = n.toString().split('').map(Number);
let sum = parseInt(nums.reduce((x, y)=> x + y));
console.log('Nums: ',nums, 'Sum: ', sum);
if(sum > 9) {
superNumber(sum);
}
return sum;
}
let result = superNumber(148);
console.log('Ans: ', result);
Here is the console log:
Nums: [1, 4, 8] Sum: 13
Nums: [1, 3] Sum: 4 // Calculated sum
correctly but returning the previous value
Ans: 13
You forgot a return there:
if (sum > 9)
return superNumber(sum);
// ^^^^^^ here you forgot to return
const superNumber = (n) => {
let nums = n.toString().split('').map(Number);
let sum = parseInt(nums.reduce((x, y) => x + y));
console.log('Nums:', nums.toString(), ' Sum:', sum);
if (sum > 9) {
return superNumber(sum);
}
return sum;
}
let result = superNumber(148);
console.log('Ans: ', result);
if you don't want to mess up with the return...
const superNumber = n =>
{
let
nums = Array.from(n.toString(10))
, sum = nums.reduce((s,v) => s + +v, 0)
;
console.log( 'Nums: ', ...nums, ' , Sum: ', sum );
return (sum < 10) ? sum : superNumber(sum);
}
console.log('Ans: ', superNumber(148));

Is there a Javascript function to calculate the median of a Set [duplicate]

I've been trying to calculate median but still I've got some mathematical issues I guess as I couldn't get the correct median value and couldn't figure out why. Here's the code;
class StatsCollector {
constructor() {
this.inputNumber = 0;
this.average = 0;
this.timeout = 19000;
this.frequencies = new Map();
for (let i of Array(this.timeout).keys()) {
this.frequencies.set(i, 0);
}
}
pushValue(responseTimeMs) {
let req = responseTimeMs;
if (req > this.timeout) {
req = this.timeout;
}
this.average = (this.average * this.inputNumber + req) / (this.inputNumber + 1);
console.log(responseTimeMs / 1000)
let groupIndex = Math.floor(responseTimeMs / 1000);
this.frequencies.set(groupIndex, this.frequencies.get(groupIndex) + 1);
this.inputNumber += 1;
}
getMedian() {
let medianElement = 0;
if (this.inputNumber <= 0) {
return 0;
}
if (this.inputNumber == 1) {
return this.average
}
if (this.inputNumber == 2) {
return this.average
}
if (this.inputNumber > 2) {
medianElement = this.inputNumber / 2;
}
let minCumulativeFreq = 0;
let maxCumulativeFreq = 0;
let cumulativeFreq = 0;
let freqGroup = 0;
for (let i of Array(20).keys()) {
if (medianElement <= cumulativeFreq + this.frequencies.get(i)) {
minCumulativeFreq = cumulativeFreq;
maxCumulativeFreq = cumulativeFreq + this.frequencies.get(i);
freqGroup = i;
break;
}
cumulativeFreq += this.frequencies.get(i);
}
return (((medianElement - minCumulativeFreq) / (maxCumulativeFreq - minCumulativeFreq)) + (freqGroup)) * 1000;
}
getAverage() {
return this.average;
}
}
Here's the snapshot of the results when I enter the values of
342,654,987,1093,2234,6243,7087,20123
The correct result should be;
Median: 1663.5
Change your median method to this:
function median(values){
if(values.length ===0) throw new Error("No inputs");
values.sort(function(a,b){
return a-b;
});
var half = Math.floor(values.length / 2);
if (values.length % 2)
return values[half];
return (values[half - 1] + values[half]) / 2.0;
}
fiddle
Here's another solution:
function median(numbers) {
const sorted = Array.from(numbers).sort((a, b) => a - b);
const middle = Math.floor(sorted.length / 2);
if (sorted.length % 2 === 0) {
return (sorted[middle - 1] + sorted[middle]) / 2;
}
return sorted[middle];
}
console.log(median([4, 5, 7, 1, 33]));
The solutions above - sort then find middle - are fine, but slow on large data sets. Sorting the data first has a complexity of n x log(n).
There is a faster median algorithm, which consists in segregating the array in two according to a pivot, then looking for the median in the larger set. Here is some javascript code, but here is a more detailed explanation
// Trying some array
alert(quickselect_median([7,3,5])); // 2300,5,4,0,123,2,76,768,28]));
function quickselect_median(arr) {
const L = arr.length, halfL = L/2;
if (L % 2 == 1)
return quickselect(arr, halfL);
else
return 0.5 * (quickselect(arr, halfL - 1) + quickselect(arr, halfL));
}
function quickselect(arr, k) {
// Select the kth element in arr
// arr: List of numerics
// k: Index
// return: The kth element (in numerical order) of arr
if (arr.length == 1)
return arr[0];
else {
const pivot = arr[0];
const lows = arr.filter((e)=>(e<pivot));
const highs = arr.filter((e)=>(e>pivot));
const pivots = arr.filter((e)=>(e==pivot));
if (k < lows.length) // the pivot is too high
return quickselect(lows, k);
else if (k < lows.length + pivots.length)// We got lucky and guessed the median
return pivot;
else // the pivot is too low
return quickselect(highs, k - lows.length - pivots.length);
}
}
Astute readers will notice a few things:
I simply transliterated Russel Cohen's Python solution into JS,
so all kudos to him.
There are several small optimisations worth
doing, but there's parallelisation worth doing, and the code as is
is easier to change in either a quicker single-threaded, or quicker
multi-threaded, version.
This is the average linear time
algorithm, there is more efficient a deterministic linear time version, see Russel's
post for details, including performance data.
ADDITION 19 Sept. 2019:
One comment asks whether this is worth doing in javascript. I ran the code in JSPerf and it gives interesting results.
if the array has an odd number of elements (one figure to find), sorting is 20% slower that this "fast median" proposition.
if there is an even number of elements, the "fast" algorithm is 40% slower, because it filters through the data twice, to find elements number k and k+1 to average. It is possible to write a version of fast median that doesn't do this.
The test used rather small arrays (29 elements in the jsperf test). The effect appears to be more pronounced as arrays get larger. A more general point to make is: it shows these kinds of optimisations are worth doing in Javascript. An awful lot of computation is done in JS, including with large amounts of data (think of dashboards, spreadsheets, data visualisations), and in systems with limited resources (think of mobile and embedded computing).
var arr = {
max: function(array) {
return Math.max.apply(null, array);
},
min: function(array) {
return Math.min.apply(null, array);
},
range: function(array) {
return arr.max(array) - arr.min(array);
},
midrange: function(array) {
return arr.range(array) / 2;
},
sum: function(array) {
var num = 0;
for (var i = 0, l = array.length; i < l; i++) num += array[i];
return num;
},
mean: function(array) {
return arr.sum(array) / array.length;
},
median: function(array) {
array.sort(function(a, b) {
return a - b;
});
var mid = array.length / 2;
return mid % 1 ? array[mid - 0.5] : (array[mid - 1] + array[mid]) / 2;
},
modes: function(array) {
if (!array.length) return [];
var modeMap = {},
maxCount = 1,
modes = [array[0]];
array.forEach(function(val) {
if (!modeMap[val]) modeMap[val] = 1;
else modeMap[val]++;
if (modeMap[val] > maxCount) {
modes = [val];
maxCount = modeMap[val];
}
else if (modeMap[val] === maxCount) {
modes.push(val);
maxCount = modeMap[val];
}
});
return modes;
},
variance: function(array) {
var mean = arr.mean(array);
return arr.mean(array.map(function(num) {
return Math.pow(num - mean, 2);
}));
},
standardDeviation: function(array) {
return Math.sqrt(arr.variance(array));
},
meanAbsoluteDeviation: function(array) {
var mean = arr.mean(array);
return arr.mean(array.map(function(num) {
return Math.abs(num - mean);
}));
},
zScores: function(array) {
var mean = arr.mean(array);
var standardDeviation = arr.standardDeviation(array);
return array.map(function(num) {
return (num - mean) / standardDeviation;
});
}
};
2022 TypeScript Approach
const median = (arr: number[]): number | undefined => {
if (!arr.length) return undefined;
const s = [...arr].sort((a, b) => a - b);
const mid = Math.floor(s.length / 2);
return s.length % 2 === 0 ? ((s[mid - 1] + s[mid]) / 2) : s[mid];
};
Notes:
The type in the function signature (number[]) ensures only an array of numbers can be passed to the function. It could possibly be empty though.
if (!arr.length) return undefined; checks for the possible empty array, which would not have a median.
[...arr] creates a copy of the passed-in array to ensure we don't overwrite the original.
.sort((a, b) => a - b) sorts the array of numbers in ascending order.
Math.floor(s.length / 2) finds the index of the middle element if the array has odd length, or the element just to the right of the middle if the array has even length.
s.length % 2 === 0 determines whether the array has an even length.
(s[mid - 1] + s[mid]) / 2 averages the two middle items of the array if the array's length is even.
s[mid] is the middle item of an odd-length array.
TypeScript Answer 2020:
// Calculate Median
const calculateMedian = (array: Array<number>) => {
// Check If Data Exists
if (array.length >= 1) {
// Sort Array
array = array.sort((a: number, b: number) => {
return a - b;
});
// Array Length: Even
if (array.length % 2 === 0) {
// Average Of Two Middle Numbers
return (array[(array.length / 2) - 1] + array[array.length / 2]) / 2;
}
// Array Length: Odd
else {
// Middle Number
return array[(array.length - 1) / 2];
}
}
else {
// Error
console.error('Error: Empty Array (calculateMedian)');
}
};
const median = (arr) => {
return arr.slice().sort((a, b) => a - b)[Math.floor(arr.length / 2)];
};
Short and sweet.
Array.prototype.median = function () {
return this.slice().sort((a, b) => a - b)[Math.floor(this.length / 2)];
};
Usage
[4, 5, 7, 1, 33].median()
Works with strings as well
["a","a","b","b","c","d","e"].median()
For better performance in terms of time complexity, use MaxHeap - MinHeap to find the median of stream of array.
Simpler & more efficient
const median = dataSet => {
if (dataSet.length === 1) return dataSet[0]
const sorted = ([ ...dataSet ]).sort()
const ceil = Math.ceil(sorted.length / 2)
const floor = Math.floor(sorted.length / 2)
if (ceil === floor) return sorted[floor]
return ((sorted[ceil] + sorted[floor]) / 2)
}
Simple solution:
function calcMedian(array) {
const {
length
} = array;
if (length < 1)
return 0;
//sort array asc
array.sort((a, b) => a - b);
if (length % 2) {
//length of array is odd
return array[(length + 1) / 2 - 1];
} else {
//length of array is even
return 0.5 * [(array[length / 2 - 1] + array[length / 2])];
}
}
console.log(2, calcMedian([1, 2, 2, 5, 6]));
console.log(3.5, calcMedian([1, 2, 2, 5, 6, 7]));
console.log(9, calcMedian([13, 9, 8, 15, 7]));
console.log(3.5, calcMedian([1, 4, 6, 3]));
console.log(5, calcMedian([5, 1, 11, 2, 8]));
Simpler, more efficient, and easy to read
cloned the data to avoid alterations to the original data.
sort the list of values.
get the middle point.
get the median from the list.
return the median.
function getMedian(data) {
const values = [...data];
const v = values.sort( (a, b) => a - b);
const mid = Math.floor( v.length / 2);
const median = (v.length % 2 !== 0) ? v[mid] : (v[mid - 1] + v[mid]) / 2;
return median;
}
const medianArr = (x) => {
let sortedx = x.sort((a,b)=> a-b);
let halfIndex = Math.floor(sortedx.length/2);
return (sortedx.length%2) ? (sortedx[Math.floor(sortedx.length/2)]) : ((sortedx[halfIndex-1]+sortedx[halfIndex])/2)
}
console.log(medianArr([1,2,3,4,5]));
console.log(medianArr([1,2,3,4,5,6]));
function Median(arr){
let len = arr.length;
arr = arr.sort();
let result = 0;
let mid = Math.floor(len/2);
if(len % 2 !== 0){
result += arr[mid];
}
if(len % 2 === 0){
result += (arr[mid] + arr[mid+1])/2
}
return result;
}
console.log(`The median is ${Median([0,1,2,3,4,5,6])}`)
function median(arr) {
let n = arr.length;
let med = Math.floor(n/2);
if(n % 2 != 0){
return arr[med];
} else{
return (arr[med -1] + arr[med])/ 2.0
}
}
console.log(median[1,2,3,4,5,6]);
The arr.sort() method sorts the elements of an array in place and returns the array. By default, it sorts the elements alphabetically, so if the array contains numbers, they will not be sorted in numerical order.
On the other hand, the arr.sort((a, b) => a - b) method uses a callback function to specify how the array should be sorted. The callback function compares the two elements a and b and returns a negative number if a should be sorted before b, a positive number if b should be sorted before a, and zero if the elements are equal. In this case, the callback function subtracts b from a, which results in a sorting order that is numerical in ascending order.
So, if you want to sort an array of numbers in ascending order, you should use arr.sort((a, b) => a - b), whereas if you want to sort an array of strings alphabetically, you can use arr.sort():
function median(numbers) {
const sorted = Array.from(numbers).sort((a, b) => a - b);
const middle = Math.floor(sorted.length / 2);
if (sorted.length % 2 === 0) {
return (sorted[middle - 1] + sorted[middle]) / 2;
}
return sorted[middle];
}
function findMedian(arr) {
arr.sort((a, b) => a - b)
let i = Math.floor(arr.length / 2)
return arr[i]
}
let result = findMedian([0, 1, 2, 4, 6, 5, 3])
console.log(result)

javascript least amount of elements from an integer array that can be used to get to a total value

please can somebody help?
If i have a total or a sum for instance 91
How can I create an array of the least amount of elements needed to get to the total value?
[50, 20, 10 , 5, 3, 2, 1] totaling this array will provide 91.
I know how to perform the opposite function using reduce or like so:
<script>
var numbers = [65, 44, 12, 4];
function getSum(total, num) {
return total + num;
}
function myFunction(item) {
document.getElementById("demo").innerHTML = numbers.reduce(getSum);
}
</script>
Greedy algorithm
Here is a solution using greedy algorithm. Note that this solution will work correctly in case when all the smaller numbers are divisors of all the bigger numbers such as in case [50, 10, 5, 1]. (see dynamic algorithm below this one for solution that can handle any input)
50 mod 10 = 0
50 mod 5 = 0
50 mod 1 = 0
10 mod 5 = 0
10 mod 1 = 0
5 mod 1 = 0
const sum = xs => xs.reduce((acc, v) => acc + v, 0);
function pickSubset(options, total, currentPick) {
if (sum(currentPick) === total) { return currentPick; }
if (options.length === 0) { return null; }
const firstVal = options[0];
let res = null;
if (sum(currentPick) + firstVal > total) {
res = pickSubset(options.slice(1), total, currentPick);
} else {
let opt1 = pickSubset(options, total, currentPick.concat(options[0]));
let opt2 = pickSubset(options.slice(1), total, currentPick.concat(options[0]));
if (opt1 && opt2) {
opt1.length < opt2.length ? res = opt1 : res = opt2
} else if (opt1) {
res = opt1;
} else {
res = opt2;
}
}
return res;
}
const total = 73;
const options = [50, 25, 10, 5, 2, 1];
console.log(pickSubset(options, total, []));
To handle unsorted input you can wrap it in another function and sort it prior to passing it to the main function.
const sum = xs => xs.reduce((acc, v) => acc + v, 0);
function pickSubset(options, total, currentPick) {
const sortedOptions = options.sort((a, b) => b - a);
function _pickSubset(options, total, currentPick) {
if (sum(currentPick) === total) { return currentPick; }
if (options.length === 0) { return null; }
const firstVal = options[0];
let res = null;
if (sum(currentPick) + firstVal > total) {
res = pickSubset(options.slice(1), total, currentPick);
} else {
let opt1 = pickSubset(options, total, currentPick.concat(options[0]));
let opt2 = pickSubset(options.slice(1), total, currentPick.concat(options[0]));
if (opt1 && opt2) {
opt1.length < opt2.length ? res = opt1 : res = opt2
} else if (opt1) {
res = opt1;
} else {
res = opt2;
}
}
return res;
}
return _pickSubset(sortedOptions, total, currentPick);
}
const total = 73;
const options = [50, 25, 10, 5, 2, 1].reverse();
console.log(pickSubset(options, total, []));
Dynamic programming (bottom-up natural ordering approach)
This solution works correctly for any type of input.
function pickSubset(options, total) {
function _pickSubset(options, change, minNums, numsUsed) {
for (let i = 0; i < change + 1; i++) {
let count = i;
let newNum = 1;
let arr = options.filter(v => v <= i);
for (let j of arr) {
if (minNums[i - j] + 1 < count) {
count = minNums[i - j] + 1;
newNum = j;
}
}
minNums[i] = count;
numsUsed[i] = newNum;
}
return minNums[change];
}
function printNums(numsUsed, change) {
const res = [];
let num = change;
while (num > 0) {
let thisNum = numsUsed[num];
res.push(thisNum);
num = num - thisNum;
}
return res;
}
const numsUsed = [];
const numsCount = [];
_pickSubset(options, total, numsCount, numsUsed);
return printNums(numsUsed, total);
}
const options = [50, 10, 5, 2, 1];
console.log(pickSubset(options, 73));
Dynamic programming (top-down memoization approach)
// helper function that generates all the possible solutions
// meaning, all the possible ways in which we can pay the provided amount
// and caches those solutions;
// returns the number of possible solutions but that is not neccessary
// in this case
const _pickSubset = (toPay, options, currentPick, cache) => {
if (toPay < 0) { return 0; }
if (toPay === 0) {
cache.add(currentPick);
return 1;
}
if (options.length === 0) { return 0; }
return _pickSubset(toPay - options[0], options, currentPick.concat(options[0]), cache)
+ _pickSubset(toPay, options.slice(1), currentPick, cache);
};
// memoize only with respect to the first two arguments - toPay, bills
// the other two are not necessary in this case
const memoizeFirstTwoArgs = fn => {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args.slice(0, 2));
if (cache.has(key)) { return cache.get(key); }
const res = fn(...args);
cache.set(key, res);
return res;
};
};
// uses memoized version of makeChange and provides cache to that function;
// after cache has been populated, by executing memoized version of makeChange,
// find the option with smallest length and return it
const pickSubset = (toPay, options) => {
const cache = new Set();
const memoizedPickSubset = memoizeFirstTwoArgs(_pickSubset);
memoizedPickSubset(toPay, options, [], cache);
let minLength = Infinity;
let resValues;
for (const value of cache) {
if (value.length < minLength) {
minLength = value.length;
resValues = value;
}
}
return resValues;
}
const options = [50, 25, 10, 5, 2, 1];
const toPay = 73;
console.log(pickSubset(toPay, options));

How do I get Fibonacci numbers in an array?

Given input = [1,2,4] return [1,2], or if no fibonacci numbers return [], [1,1,2] should return [1,2];
I know you can check whether a number is in the fibonacci sequence with this code:
function isSquare(n) {
return n > 0 && Math.sqrt(n) % 1 === 0;
};
//Equation modified from http://www.geeksforgeeks.org/check-number-fibonacci-number/
function isFibonacci(numberToCheck)
{
// numberToCheck is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both
// is a perferct square
return isPerfectSquare(5*numberToCheck*numberToCheck + 4) ||
isPerfectSquare(5*numberToCheck*numberToCheck - 4);
}
But I don’t know how to implement it. Thanks.
Array.from(new Set(arr)) Removes duplicates from the original array
let newArr = []; Defining the new array
for ( let i = 0; i < arrD.length; i++ ) Loop every number of arrD, arrD[i] accesses a number in the array
if(fib(arrD[i])) { newArr.push(arrD[i]); } if the number is in the fibonacci sequence, fib(arrD[i]) will return true, and the number will be .pushed into the newArr
Using a for loop
let arr = [1,2,3,8,3,8];
let sqrt = (num) => { return num > 0 && Math.sqrt(num) % 1 === 0; };
let fib = (num) => { return sqrt(5 * Math.pow(num,2) + 4) || sqrt(5 * Math.pow(num,2) - 4); };
function fibArr(arr) {
arrD = Array.from(new Set(arr));
let newArr = [];
for ( let i = 0; i < arrD.length; i++ ) {
if(fib(arrD[i])) { newArr.push(arrD[i]); }
}
return newArr;
}
console.log(fibArr(arr));
OR using .filter
let arr = [1,2,3,8,3,8];
let sqrt = (num) => { return num > 0 && Math.sqrt(num) % 1 === 0; };
let fib = (num) => { return sqrt(5 * Math.pow(num,2) + 4) || sqrt(5 * Math.pow(num,2) - 4); };
function fibArr(arr) {
arrD = Array.from(new Set(arr));
let newArr = arrD.filter(function(arrD){
return fib(arrD);
})
return newArr;
}
console.log(fibArr(arr));

Javascript group array by intersection

Given an array of paired integers, HOW can I group by intersections. Does anyone have a simple function that could convert my input, into the desired output?
Input
var in = ["0:3", "1:3", "4:5", "5:6", "6:8"]
Desired output
[
[0, 1, 3],
[4, 5, 6, 8]
]
UPDATE:
#apsiller asked my question in the comments more clearly then I originally posted:
"Considering each number as a node in a graph, and each pairing x:y as an edge between nodes x and y, find the sets of numbers that can be traveled to using the edges defined. That is, in graph theory terms, find the distinct connected components within such a graph.
For instance, there is no way to travel from 4 to 0 so they are in different groups, but there is a way to travel from 1 to 0 (by way of 3) so they are in the same group."
To reiterate the desired output is a grouping of transversable nodes, based on a potentially random input set.
Thanks everyone. Given everyones input I was able to find a similar question on here that led me my answer. Finding All Connected Components of an Undirected Graph
The first step was to change my input to groups of pairs.
var input = [
[0, 3],
[1, 3],
[4, 5],
[5, 6],
[6, 8]
]
The next step was to use whats called Breadth-first search
function breadthFirstSearch(node, nodes, visited) {
var queue = [];
var group = [];
var pair = null;
queue.push(node);
while (queue.length > 0) {
node = queue.shift();
if (!visited[node]) {
visited[node] = true;
group.push(node);
for (var i = 0, len = nodes.length; i < len; i++) {
pair = nodes[i];
if (pair[0] === node && !visited[pair[1]]) {
queue.push(pair[1]);
} else if (pair[1] === node && !visited[pair[0]]) {
queue.push(pair[0]);
}
}
}
}
return group;
};
function groupReachableVertices(input) {
var groups = [];
var visited = {};
for (var i = 0, len = input.length; i < len; i += 1) {
var current_pair = input[i];
var u = current_pair[0];
var v = current_pair[1];
var src = null;
if (!visited[u]) {
src = u;
} else if (!visited[v]) {
src = v;
}
if (src) {
groups.push(breadthFirstSearch(src, input, visited));
}
}
return groups;
};
Putting it all together...
var output = groupReachableVertices(input);
[
[0, 1, 3],
[4, 5, 6, 8]
]
You could do something like this.
function group(data) {
var r = [[]],c = 0,a = [0]
var d = data.map(e => e.split(':').sort((a, b) => a - b)).sort((a, b) => a[0] - b[0])
d.forEach(function(e, i) {
if (e[0] > a[a.length - 1]) {
r.push(e)
a.push(e[1])
c++
} else {
r[c] = r[c].concat(e)
a[a.length - 1] = e[1]
}
})
return r.map(e => [...new Set(e)].sort((a, b) => a - b))
}
var test1 = ["0:3", "1:3", "4:5", "5:6", "6:8"]
var test2 = ["0:3", "1:3", "4:5", "9:11", "10:12", '3:6', "7:8"]
var test3 = ["20:15", "4:0", "1:3", "5:1", "9:11", "10:12", '3:6', "8:7"]
console.log(JSON.stringify(group(test1)))
console.log(JSON.stringify(group(test2)))
console.log(JSON.stringify(group(test3)))
You could use a hash table and collect all nodes in it. It works for any values.
var data = ["0:3", "1:3", "4:5", "a:8", "5:a"],
result = data
.map(function (a) { return a.split(':'); })
.reduce(function (hash) {
return function (r, a) {
if (hash[a[0]] && hash[a[1]]) {
hash[a[0]].push.apply(hash[a[0]], r.splice(r.indexOf(hash[a[1]]), 1)[0]);
hash[a[1]] = hash[a[0]];
return r;
}
if (hash[a[0]]) {
hash[a[1]] = hash[a[0]];
hash[a[1]].push(a[1]);
return r;
}
if (hash[a[1]]) {
hash[a[0]] = hash[a[1]];
hash[a[0]].push(a[0]);
return r;
}
hash[a[0]] = a.slice();
hash[a[1]] = hash[a[0]];
return r.concat([hash[a[0]]]);
};
}(Object.create(null)), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I guess, by using Object.values() and Set object you can simply do as follows in ES6.
function getConnectedVertices(a){
return [...new Set(Object.values(a.reduce((h,v) => (h[v[0]] ? h[v[1]] ? (h[v[0]] = h[v[0]].concat(h[v[1]]),
h[v[1]] = h[v[0]])
: (h[v[0]].push(v[1]),
h[v[1]] = h[v[0]])
: h[v[1]] ? (h[v[1]].push(v[0]),
h[v[0]] = h[v[1]])
: h[v[0]] = h[v[1]] = v,
h),{})))];
}
var input = ["0:3", "1:3", "4:5", "5:6", "6:8"].map(s => s.split(":")),
result = getConnectedVertices(input);
console.log(result);

Categories