Calculating bands for Graphic EQ - javascript

I'm trying to make a Graphic EQ using web audio and the goal is build a function that
calculates an array of fixed center frequency's using a band count (a.k.a number) as input.
In other words it generates an array for fixed center frequencies.
example:
function calcBands(bands) {
// Since there are different graphic EQ's they usually around 6 - 31 bands
// but professionally it's normally 31 bands
// band parameter needs to be a number between 6 and 31
//insert code here:
const freqs = new Array(bands);
return freqs;
}
function buildFilters(bands) {
let centers = calcBands(bands);
let filters = [];
for (let i = 0; i < bands; i++) {
let filter = context.createBiquadFilter();
filter.type = "peaking";
filter.frequency.value = centers[i];
filter.Q.value = Math.SQRT1_2;
if (i > 0) {
filters[i - 1].connect(filter);
}
filters.push(filter);
}
return filters;
}
The thing is I tried doing some research and I found out that there are ISO standards and other things, but I just can't do the maths of it.
All I can understand from this is that:
This is calculated using octave bands either 1 or 1/3, etc in base 2
Graphic EQ's usually have 6 to 31 bands
Middle C (a.k.a A4) equals to 440Hz
Nyquist Frequency is sampleRate / 2
Can anyone please help me?
Feel free to correct me if I'm wrong
references:
https://www.cross-spectrum.com/audio/articles/center_frequencies.html
https://sound.stackexchange.com/questions/14101/what-is-the-frequency-step-formula-for-10-and-31-band-eqs
http://www.tonmeister.ca/main/textbook/intro_to_sound_recordingch13.html

Related

Find the player of the year Algorithm JavaScript/Java

Can anyone please help me out on this one, I do not really understand sample input format. Can somebody guide me with the pseudocode of this algorithm ??
There are multiple line graphs that denote the performance of star players in different sports teams.
The player of the year has the longest time as the number one player, i.e. the player whose graph values stay above the values of all players for the longest time.
Find the player of the year.
Input Format
The first line contains an integer, n, denoting the number of players.
The next line contains an integer, m, denoting the number of data points per player.
Each line i of the n subsequent lines(where 0 ≤ i < n)contains m space separated integers denoting the relative performance of player i during that data point duration.
Output Format
A single Integer
Sample Input
3
4
1 3 4 5
7 2 3 4
1 3 2 1
Sample Output
0
Explanation
Player 0 has been on the top for 3 data point durations, which is the maximum.
Approach.
function Logic() {
//INPUT [uncomment & modify if required]
let sampleInput = gets();
let result = -404;
//OUTPUT [uncomment & modify if required]
console.log(result)
}
Thank you for the help!
To explain the sample input, a visual representation may be helpful:
The performance is on the vertical axis, the moments of measurement on the horizontal axis (4 data points), and each player is identified by colour.
The challenge is then to find the colour of the bars that reach highest during the longest consecutive period of time. In this case blue bars represent the maximum performance during 3 consecutive periods (labelled 2, 3 and 4).
Algorithm
In a first phase identify for each period which is the top performance value. So in the example that is: 7, 3, 4 and 5.
Then find the longest consecutive sequence in the performances of each player that matches that top performance. In this case the performance sequence 3, 4 and 5 is achieved by player 0, and is the longest such sequence.
Implementation
A JavaScript snippet:
function getPlayerOfTheYear(series) {
// The following two values are actually part of the input,
// but since this function takes a 2D array, they are implied:
let playerCount = series.length;
let periodCount = series[0].length;
// 1. Collect all best performance values (= top of the "graph")
let tops = [];
for (let i = 0; i < periodCount; i++) {
// Get best performance for this particular period:
let bestPerformance = -Infinity;
for (let player = 0; player < playerCount; player++) {
bestPerformance = Math.max(bestPerformance, series[player][i]);
}
tops.push(bestPerformance);
}
// 2. Per player, find longest sequence of achieving the top performance
let longestDuration = 0;
for (let player = 0; player < playerCount; player++) {
let duration = 0;
for (let i = 0; i < periodCount; i++) {
if (series[player][i] === tops[i]) {
duration++;
if (duration > longestDuration) {
playerOfTheYear = player;
longestDuration = duration;
}
} else duration = 0;
}
}
return playerOfTheYear;
}
let player = getPlayerOfTheYear([
[1, 3, 4, 5],
[7, 2, 3, 4],
[1, 3, 2, 1]
]);
console.log("Player of the year: ", player);

Return random number excluding specific range - javascript

I'm trying to return a random number within a specific range while also excluding a specific range within it. I've seen similar questions posed, but I can't get it to work. Here's what I have so far:
var x = xFunction();
function xFunction() {
return parseFloat(Math.round(Math.random() * 2250) / 1000).toFixed(3);
}
if (x > 1.250 && x < 2.001 ) {
// this number is excluded so redo xFunction();
} else {
// this number is acceptable so do some code
}
Any help is appreciated. Thank you so much!
One way to handle this is to look for a random number in the range with the excluded part removed. For example if you were looking for a random number between 0 and 100 with 70-80 removed, you would find a random number between 0 and 90 (removing the 10 from the excluded range). Then if any value falls above 70 you add the excluded range back. This will preserve the appropriate ratio of randomness for each range and you should see results mostly from the lower range with a few from the upper range because that is a larger percentage of the distribution.
(I've moved the division and rounding out of the function just to make it clearer how it works.)
function xFunction(max, exclude) {
let excluded_range = exclude[1] - exclude[0]
let rand = Math.random() * (max - excluded_range)
if (rand > exclude[0]) rand += excluded_range
return rand
}
for (let x = 0; x<10; x++){
let r = xFunction(2250, [1250, 2000])
console.log ((r / 1000).toFixed(3));
}
If you pick a random 0 or 1 and use that to determine the range as recommended in the comments, you will end up with approximately half of the result in the much smaller top range. This will bias your results toward that top range rather than truly finding a random number within the whole range.

Don't understand what this code does

So I know this code is randomly removing to of my objects to create a hole so another object can go through but line by line I would like to go through and understand each part. Would be great if someone not so arrogant could help me because I'm new. I would appreciate any help. The area I don't understand is the last part which I have highlighted in bold. Thank you.
// Add a pipe on the screen
add_one_pipe: function(x, y) {
// Get the first dead pipe of our group
var pipe = this.pipes.getFirstDead();
// Set the new position of the pokeballs
pipe.reset(x, y);
// Add velocity to the pokeballs to make it move left
pipe.body.velocity.x = -200;
// Kill the pokeballs when it's no longer visible
pipe.outOfBoundsKill = true;
},
**add_row_of_pipes: function() {
var hole = Math.floor(Math.random()*5)+1;**
**for (var i = 0; i < 8; i++)
if (i != hole && i != hole +1)
this.add_one_pipe(400, i*60+10);**
add_row_of_pipes will add 6 pipes at fixed intervals heights, but with a randomly placed gap of 2 missing pipes.
var hole = Math.floor(Math.random()*5)+1;
Take a random number (between 0 and 0.999),
Multiply by 5 (possible range is now 0-4.9999...),
Round down (0-4),
Add one (1-5)
This value is where the hole is
for (var i = 0; i < 8; i++)
For the whole numbers 0 to 7 inclusive, representing height, i...
if (i != hole && i != hole +1)
If this height is not where the hole starts, nor the next value,
this.add_one_pipe(400, i*60+10);
Add a pipe at width 400, and height i*60+10.

Calculate maximum available rows and columns to fill with N amount of items

By reviewing this and this, I've come up with a function, that's probably more complex than it should be, but, man, my math sux:
function tablize(elements)
{
var root = Math.floor(Math.sqrt(elements));
var factors = [];
for (var i = 1; i <= root; i++)
{
if (elements % i === 0)
{
factors.push([i, elements / i]);
}
}
var smallest = null;
for (var f = 0; f < factors.length; f++)
{
var factor = factors[f];
var current = Math.abs(factor[0] - factor[1]);
if (!smallest || factors[smallest] > factor)
{
smallest = f;
}
}
return factors[smallest];
}
While this does work, it provides results I'm not satisfied with.
For instance - 7, it's divided in 1x7, where I'd like it to be 3x3. That's the minimum, optimal, grid size needed to fill with 7 elements.
Also - 3, it's divided in 1x3, where I'd like it to be 2x2.
I need this for a live camera feed frame distribution on a monitor, but I'm totally lost. The only way I can think of is building an extra function to feed with previously generated number and divide again, but that seems wrong.
What is the optimal solution to solve this?
For squares:
function squareNeeded(num) {
return Math.ceil(Math.sqrt(num));
}
http://jsfiddle.net/aKNVq/
(I think you mean the smallest square of a whole number that is bigger than the given amount, because if you meant a rectangle, then your example for seven would be 2*4 instead of 3*3.)

Different probability for ranges of random numbers

I'm looking for the best way of implementing random number generator, that will allow me to have control over probability from what range the generated number will be returned. To visualize what I'm trying to achieve I have a picture :
So to summarize :
Let's say that my range is 400. At the beginning I'd like to have 5% probability of getting number 0-20. But at some moment in time I'd like to have this probability increased up to 50%. Hope you get the idea.
Hmm, working on your original I had a pretty simple algorithm to generate ranges in an array in the appropriate proportion, then randomly select a range and generate a random number within that range. No doubt it can be optimised if necessary, but it works for me.
It looks like a lot of code, but 3/4 of it is comments, test data and function, the actual randomRange function is only 17 lines of code.
<script type="text/javascript">
function randomRange(dataArray) {
// Helper function
function getRandomInRange(s, f) {
return (Math.random() * (f-s+1) | 0) + s
}
// Generate new data array based on probability
var i, j = dataArray.length;
var oArray = [];
var o;
while (j--) {
o = dataArray[j];
// Make sure probability is an integer
for (i=0, iLen=o.probability|0; i<iLen; i++) {
oArray.push([o.rangeStart, o.rangeEnd]);
}
}
// Randomly select a range from new data array and
// generate a random number in that range
var oEnd = oArray.length;
var range = oArray[getRandomInRange(0, oArray.length - 1)];
return getRandomInRange(range[0], range[1]);
}
// Test data set. Probability just has to be
// representative, so 50/50 === 1/1
var dataArray = [
{
rangeStart: 0,
rangeEnd : 20,
probability: 1
},
{
rangeStart: 21,
rangeEnd : 400,
probability: 1
}
];
// Test function to show range and number is randomly
// selected for given probability
function testIt() {
var el0 = document.getElementById('div0');
var el1 = document.getElementById('div1');
function run() {
var n = randomRange(dataArray);
if (n <= 20) {
el0.innerHTML += '*';
} else {
el1.innerHTML += '*';
}
}
setInterval(run, 500);
}
</script>
<button onclick="testIt();">Generate random number</button>
<div>Numbers 0 - 20</div>
<div id="div0"></div>
<div>Numbers 21 - 400</div>
<div id="div1"></div>
It sounds to me like what you're looking for is a way to generate numbers on a normal (or Gaussian) distribution (take a look at the Wikipedia page if you don't know what that means).
The Box-Muller transformation can be used to generate pairs of normally distributed numbers.
Here is a c++ implementation of the polar form of the Box-Muller transformation that shouldn't be hard to translate to javascript.
// Return a real number from a normal (Gaussian) distribution with given
// mean and standard deviation by polar form of Box-Muller transformation
double x, y, r;
do
{
x = 2.0 * rand() - 1.0;
y = 2.0 * rand() - 1.0;
r = x * x + y * y;
}
while ( r >= 1.0 || r == 0.0 );
double s = sqrt( -2.0 * log(r) / r );
return mean + x * s * stddev;
Where mean is the mean of the normal distribution and stddev is the Standard Deviation of the distribution. This code is from a MersesenneTwister C++ class that I've been using recently that you can find on Rick Wagner's page. You can find some more useful information about the Box-Muller transformation on this page.

Categories

Resources