Equally distribute array of numbers into x subsets of numbers - javascript

I have a large array of numbers that I need to distribute into x ranges of numbers, such that each range contains an equal number of elements from the original array.
For example, when x = 4 , the following array
[1, 1, 2.5, 3, 6, 7, 10, 11.2, 14, 25, 35, 50, 75, 85.5, 100, 120, 128.9, 150, 200, 260]
would produce an array of length x + 1 with the following
[1, 6.5, 30, 110, 260]
1 is the lowest value in the array
6.5 is the midpoint of 6 and 7
30 is the midpoint of 25 and 35
110 is the midpoint of 100 and 120
260 is the highest value
Essentially, this will give me 4 ranges of numbers 1-6.5, 6.5-30, 30-110, and 110-260. Each range would contain 5 numbers of the original array.
Needs to be able to handle a dynamic number of elements that will not necessarily be divided evenly by x.
I asked this question on Mathematics but was told it was more of a programming question.

Based on your question , the following javascript code should satisfy your requirements, I've tested its correctness with a few values of x, but you might want to check if this code applies to all possible test cases for your problem.
var arr = [1, 1, 2.5, 3, 6, 7, 10, 11.2, 14, 25, 35, 50, 75, 85.5, 100, 120, 128.9, 150, 200, 260, 261, 262, 263, 264, 265];
total_elem = arr.length;
var x = 5;
var each_set_elem = total_elem / x;
var i = 1;
var temp = [];
temp.push(arr[0]);
for (i = each_set_elem; i < total_elem; i += each_set_elem) {
this_elem = (arr[i] + arr[i - 1]) / 2;
temp.push(this_elem);
}
temp.push(arr[total_elem - 1]);
console.log(temp);
This code satisfies the test case in the question as well as for x=5 it spits out the correct 6 points so that the 5 ranges each have 4 elements from the given array set.

Related

How to determine the fewest number of Y increments needed to plot a multiple of 5 on a graph?

Using JavaScript, an array of numbers is going to be charted on a graph (for my purposes it is a spline chart):
[12, 22, 25, 38, 47]
I want all the Y axis values to be multiples of 5. I have the Y axis capped at the next multiple of 5 that occurs after the highest number in the array. Since 47 is the highest number, the next multiple of 5 is 50 (call that value the "cap"), and that is the top value ("tick") on the chart's Y axis. After figuring that out, I know that the Y axis should be 0 a the bottom, and 50 at the top, but I want to override the default behavior and tell it exactly how many ticks to show in between, and what the values should be for those ticks.
This is where it gets tricky, because of the following restrictions:
Use the fewest number of ticks possible (0, the max value, and at least one tick in between)
Bottom value is always zero
All Y tick values are multiples of 5
Y ticks are evenly spaced on the axis
For the previous example, fifty is the cap, which is divisible by two, so the Y axis would only need one tick in between the bottom and top, resulting in three tick values of 0, 25, 50. The function I am trying to build would receive 50 as an argument, and output 3 as the result. Then I would know the chart needs 3 ticks, and I could generate it like so:
My question is, given that a charted value can be any multiple of 5, how can I calculate the fewest number of ticks needed on the Y axis, using only increments that are multiples of 5? It may be easiest to just show the first few scenarios to illustrate how the pattern is not (at least to me) obvious:
value = tick1, tick2, tick3, etc. >> return count of ticks
05 = 5, 4, 3, 2, 1, 0 >> return 6;// This case is an outlier and can be set manually
10 = 10, 5, 0 >> return 3;
15 = 15, 10, 5, 0 >> return 4;
20 = 20, 10, 0 >> return 3;
25 = 25, 20, 15, 10, 5, 0 >> return 6;
30 = 30, 15, 0 >> return 3;
35 = 35, 30, 25, 20, 15, 10, 5, 0 >> return 8;
40 = 40, 20, 0 >> return 3;
45 = 45, 30, 15, 0 >> return 4;
50 = 50, 25, 0 >> return 3;
55 = 55, 50, 45, 40, 35, 30, 25, 20, 15, 10, 5, 0 >> return 12;
It was at this point that I realized there is probably an equation or function that exists to address this dilemma, maybe even something to do with the Fibonacci sequence or Dan Brown. I couldn't find any related SO questions, and my use of "increments of 5" may make this use case too specific to return google results on the general principle, so any advice is appreciated.
You could take an iterative approach by using the fifth of the value an checke the abulity for the division by 2, 3, 5, 7 and so on and return this value incremented by one.
const
fn = v => {
v /= 5;
if (v === 1) return 6;
if (v % 2 === 0) return 3;
var i = 1;
while ((i += 2) < v) if (v % i === 0) return i + 1;
return v + 1;
},
format = s => s.toString().padStart(2);
var values = Array.from({ length: 12 }, (_, i) => (i + 1) * 5),
data = values.map(fn);
console.log(...values.map(format));
console.log(...data.map(format));

Probability density algorithm

I'm not sure that the name for what I need is probability density but anyway.
I'd like to find a function or algorithm for generating random numbers in the specified range with specified chance and linear change.
For example, specified range and chances are:
Range from -10 to 15.
Chaces are: [[-10, 5], [-5, 0], [3, 5], [10, 30], [15, 0]]
The result after generating a number could be any numbers from that range except -5 and 15. So could be -10, -9, -8, -7 ... 13, 14.
And chance to get -10 is 5 units.
-5 is 0 units.
3 is 5 units.
So -9 will appear with 4 units chance and -8 with 3 units chance etc.
And in this case, the most common numbers should appear about 10 because 10 has 30 units chance.
You could turn the probabilities into numbers from 0 to 1 that sum up to 1:
const chances = [[-10, 5], [-5, 0], [3, 5], [10, 30], [15, 0]];
const total = chances.reduce((total, [_, v]) => total + v, 0);
chances.forEach(it => it[1] /= total);
Now you can generate a random number, and find the first value where the sum of probabilities before is bigger than that number:
let random = Math.random();
const result = chances.find(([_, p]) => (random -= p) < 0)[0];

Heart Rate Monitor

Okay, so I followed a previous post on creating a hear rate monitor and tweaked it a bit to fit my web design. Instead of setting Var Data how would I randomize the numbers between 1 and 300 over and over again until it reaches 200 random numbers total and draws them? Thanks for your time. This is my code but I took out most of the Var Data as it's 200 numbers long!
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#dbbd7a";
ctx.fill();
var fps = 60;
var n = 1;
var data = [
110, 149, 89, 150, 117, 150, 143, 82, 12, 92, 144, 73, 82, 200,
177, 149, 199, 116, 88, 105, 123, 12, 82, 72, 66, 15, 177, 182,
199, 116, 159, 150, 100, 10, ];
drawWave();
function drawWave() {
setTimeout(function() {
requestAnimationFrame(drawWave);
ctx.lineWidth = "1";
ctx.strokeStyle = 'green';
n += 1;
if (n >= data.length) {
n = 1;
}
ctx.beginPath();
ctx.moveTo(n - 1, data[n - 1 ]);
ctx.lineTo(n, data[n]);
ctx.stroke();
ctx.clearRect(n+1, 0, 10, canvas.height);
}, 1000 / fps);
}
</script>
The essence would be something like this: an array of size 200, since you want 200 values, and using a loop randomly populate the values.
Math.random will generate a number between 0 (inclusive) and 1 (non-inclusive), multiplying by 300 will give you anything between 0 and 299.99... Math.floor() removes the decimal places (range becomes 0 and 299); so we add 1 in the end to get the 1 to 300 range you wanted.
Hope this helps
var data = [];
for(var i = 0; i < 200; ++i) {
data[i] = Math.floor(Math.random() * 300) + 1;
}
with an elegant one-liner:
var data = Array.apply(null, Array(200)).map(function(){
return Math.floor(Math.random() * 299) + 1;
});
the above will work with the sparse / falsy val els in the array.
One easy way to do this is the following:
// creating a new Array with a length of 20 (obviously
// adjust the '20' to '200' for your own use-case):
var arr = new Array(20);
// using Array.prototype.fill() to assign a value (an
// empty String) to each array element, in order that
// Array.prototype.forEach() can iterate over each array
// element:
arr.fill('').forEach(function(needle, i, haystack){
// the arguments are automagically available to the
// the anonymous function;
// needle: the current array-element of the Array,
// i: the index of the current array-element,
// haystack: the Array itself.
// here we set the array value using bracket notation:
haystack[i] = Math.floor(Math.random() * (300 - 1) + 1);
});
// outputting the array to the console:
console.log( arr );
var arr = new Array(20);
arr.fill('').forEach(function(needle, i, haystack) {
haystack[i] = Math.floor(Math.random() * (300 - 1) + 1);
});
// Setting the array as the text of the <body> element,
// given the lack of a Snippet console:
document.body.textContent = arr.join(', ') + '.';
JS Fiddle demo.
The portion of the posted solution that generates the random numbers within a range:
Math.floor(Math.random() * (300 - 1) + 1)
was effectively borrowed from an answer elsewhere on the site (https://stackoverflow.com/a/1527820/82548, written by Ionut G. Stan), and is explained in that answer.
However, briefly, it generates a random number between 0 and 1; multiplies that by 299 (300 - 1), so that the integer portion becomes a number between 0 and 299; and then 1 is added to ensure the integer is now between 1 and 300.
Afterwards we apply Math.float() to round that random number to the integer portion of the number. The answer I've linked to, above, explains it far more completely.
References:
JavaScript:
Array.
Array.prototype.fill().
Array.prototype.forEach().
Math.floor().
Math.random().
String.prototype.join().
Stack Overflow:
Generating random whole numbers in JavaScript in a specific range?

Calculate Power and Logarithmic Regression

I need to calculate Logarithmic, Power Regression points(Trend line) for my array [X, Y] values below here using java script. Example:
X: [1, 2, 3, 4, 5, 6]
Y: [10, 40, 35, 50, 55, 65]
I referred more sites. But they are only given formula and its description. There is no example how to calculate X,Y values using that equation. Any one please help me on how to calculate Logarithmic, Power Regression.
Thanks,
Bharathi

Setting vAxis format in Google Line Chart [duplicate]

This question already has answers here:
Google Charts vertical axis in whole numbers
(4 answers)
Closed 9 years ago.
How to set the vAxis value format in google Line Chart in order to not get multiple lines with same value? Let's say I have lines with values: 1.5 1.0 0.5 and 0, after I set the format to '#', I got 0, 0, 1, 1...
Possible duplicate of this question
Copy-pasted answer:
If you just want numbers to display as whole numbers, then it's
easy:
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['x', 'Cats', 'Blanket 1', 'Blanket 2'],
['A', 1, 1, 0.5],
['B', 2, 0.5, 1],
['C', 4, 1, 0.5],
['D', 8, 0.5, 1],
['E', 7, 1, 0.5],
['F', 7, 0.5, 1],
['G', 8, 1, 0.5],
['H', 4, 0.5, 1],
['I', 2, 1, 0.5],
['J', 3.5, 0.5, 1],
['K', 3, 1, 0.5],
['L', 3.5, 0.5, 1],
['M', 1, 1, 0.5],
['N', 1, 0.5, 1]
]);
// Create and draw the visualization.
new google.visualization.LineChart(document.getElementById('visualization')).
draw(data, {curveType: "function",
width: 500, height: 400,
vAxis: {maxValue: 10, format: '0'}}
);
}
If you go to [google playground][1] you will note that the axis labels
are 0, 2.5, 5, 7.5, 10. By adding the format: '0' to the vAxis, it
will display only whole numbers, so my labels become 0, 3, 5, 8, 10.
But obviously this is not ideal since 8 displays as being halfway
between 5 and 10, which it isn't, because the number is actually 7.5
and just being rounded.
Your ability to change the axis scale/labels is restricted. And to do
what you're asking would take a special bit of javascript to create an
appropriate scale and number of gridlines to prevent breaking things
down in to funky numbers.
Basically, you want to make sure that your maximum and minimum values,
and number of gridlines, allow for easy division such that you will
only get whole numbers. To do that, you need to create some funky new
logic. Here is some sample code that will allow you to get an
appropriate min/max axis value:
// Take the Max/Min of all data values in all graphs
var totalMax = 345;
var totalMin = -123;
// Figure out the largest number (positive or negative)
var biggestNumber = Math.max(Math.abs(totalMax),Math.abs(totalMin));
// Round to an exponent of 10 appropriate for the biggest number
var roundingExp = Math.floor(Math.log(biggestNumber) / Math.LN10);
var roundingDec = Math.pow(10,roundingExp);
// Round your max and min to the nearest exponent of 10
var newMax = Math.ceil(totalMax/roundingDec)*roundingDec;
var newMin = Math.floor(totalMin/roundingDec)*roundingDec;
// Determine the range of your values
var range = newMax - newMin;
// Define the number of gridlines (default 5)
var gridlines = 5;
// Determine an appropriate gap between gridlines
var interval = range / (gridlines - 1);
// Round that interval up to the exponent of 10
var newInterval = Math.ceil(interval/roundingDec)*roundingDec;
// Re-round your max and min to the new interval
var finalMax = Math.ceil(totalMax/newInterval)*newInterval;
var finalMin = Math.floor(totalMin/newInterval)*newInterval;
There are a couple issues here (unfortunately). The first is that I am
using the number of gridlines to determine the min/max values -- you
want to figure out how many gridlines you should have to use nice
whole numbers. The easiest way to do this, I think, would be as
follows (pseudo-code only):
// Take the Max/Min of all data values in all graphs
var totalMax = 3;
var totalMin = -1;
// Figure out the largest number (positive or negative)
var biggestNumber = Math.max(Math.abs(totalMax),Math.abs(totalMin));
// Round to an exponent of 10 appropriate for the biggest number
var roundingExp = Math.floor(Math.log(biggestNumber) / Math.LN10);
var roundingDec = Math.pow(10,roundingExp);
// Round your max and min to the nearest exponent of 10
var newMax = Math.ceil(totalMax/roundingDec)*roundingDec;
var newMin = Math.floor(totalMin/roundingDec)*roundingDec;
// Determine the range of your values
var range = newMax - newMin;
// Calculate the best factor for number of gridlines (2-5 gridlines)
// If the range of numbers divided by 2 or 5 is a whole number, use it
for (var i = 2; i <= 5; ++i) {
if ( Math.round(range/i) = range/i) {
var gridlines = i
}
}
Then you set the gridlines option (vAxis.gridlines) to the above
variable, and your max to newMax, and your min to newMin. That should
give you whole number axis labels.
Note: if your numbers are really small then the above function may not
work. The function is also not tested so please check it against some
examples on your own time and let me know if it doesn't work properly.
[1]:
http://code.google.com/apis/ajax/playground/?type=visualization#line_chart

Categories