Say I have a JS array like so...
var newArray = [20,182,757,85,433,209,57,828,635];
And I want to use this data to create a bar graph, where the height of the highest bar would == 100.
So, the 828 value bar needs to be set to 100, and the rest of the bars need to be calculated relative to that, and also to the closest integer. I am not sure how to go about this?
Is there a way to create a new array from the one above using a loop? Then I can use the new array?
First, calculate the max value:
var max = Math.max.apply(Math, newArray.map(Math.abs));
// will do `Math.max(300, 20, 182, ...)`
// if `newArray` is `[-300, 20, 182]`
Then, divide each element by that value, do it times 100, and round it down so that the highest value becomes 100:
var normalized = newArray.map(function(v) {
return Math.round(v / max * 100);
});
.map is essentially a loop, but the loop is done internally so you can write cleaner code. Do note it's ES5, so you need a shim for older browsers.
I like pimvdb's solution that uses no visible loops, but since you asked about loops, here's the loop-oriented way of doing it:
var newArray = [20,182,757,85,433,209,57,828,635];
var max = newArray[0];
var scaledArray = [];
// find max value
for (var i = 1; i < newArray.length; i++) {
if (newArray[i] > max) {
max = newArray[i];
}
}
// create new scaled array (integer values from 0 to 100)
for (i = 0; i < newArray.length; i++) {
scaledArray.push(Math.round(newArray[i] * 100 / max));
}
Working example: http://jsfiddle.net/jfriend00/ExWn8/
var max = newArray[0];
//determine max value
for (var i in newArray)
if (newArray[i] > max) max = newArray[i];
//count coficients for every bar
var coefficients = [];
for (var i in newArray)
coefficients[i] = Math.round(newArray[i] / max * 100);
Related
I have a coding challenge in which I need to create some sort of an average calculator. As it's a beginner's course, the challenge is quite straightforward ( just input a bunch of variables and add them ). However I tried to use a for loop to make my life easier.
It keeps giving me the "NaN" answer when I console log it.
I don't really know what's wrong here. It seems relatively logical from my noob perspective. I tried putting the average var inside the for loop, but it would just average the 1st and 2nd, then move onto 2nd and 3rd, and then finally give me NaN again.
var johnTeam, mikeTeam;
var johnAverage,mikeAverage;
johnTeam = [89,120,103];
mikeTeam = [116,94,123];
function averageCalc(){
var i;
for (i in johnTeam){
var j=i++;
}
var average=(johnTeam[i]+johnTeam[j])/3;
console.log(average)
}
Expected result should be '104'.
Current result 'NaN'.
You'd never use for in to loop an array, you usually don't use i after the loop. Also, i in your case is always only the last counter value. To get the sum of an array, you'd usually use reduce and to get the average you'll divide earlier result by length
const johnTeam = [89,120,103];
const mikeTeam = [116,94,123];
const average = arr => arr.reduce( ( p, c ) => p + c, 0 ) / arr.length;
const johnAvg = average(johnTeam);
const mikeAvg = average(mikeTeam);
console.log(johnAvg);
console.log(mikeAvg);
Also consider using this :
var sumjohnTeam = 0;
johnTeam.forEach(p => (sumjohnTeam += p));
var avgjohnTeam= sumjohnTeam /johnTeam.length;
The arithmetic mean is computed by taking the sum of all the measurements and dividing by the total number of measurements. If you want to be a good statistician, null/undefined measurement counts toward N, the number of measurements, but not towards the sum of all measurements. That gives us this:
function mean( values ) {
if (!values || !value.length) return undefined;
let sum = 0;
for ( let i = 0 ; i < values.length ; ++i ) {
const value = values[i];
if (value == undefined || value == null) continue;
sum += value ;
}
return sum / values.length ;
}
With that, it's easy:
const johnTeam = [89,120,103];
const johnAverage = mean( johnTeam ) ;
const mikeTeam = [116,94,123];
const mikeAverage = mean( mikeTeak ) ;
You just need to calculate the sum in the loop then outside you divide by the number of elements in you array.
Here's an updated version of your try :
var johnTeam = [89, 120, 103],
mikeTeam = [116, 94, 123],
johnAverage = 0,
mikeAverage = 0;
// added a parameter so you can send the team array you'll want to calculate its average.
function averageCalc(teamArray) {
// stores the sum.
var sum = 0;
// loop and calculate the sum.
// notice the teamArray[i] not only i.
for (var i in teamArray) sum += teamArray[i];
// calculate average based on the array length and logs it out.
console.log(sum / teamArray.length);
}
// tests
averageCalc(johnTeam); // 104
averageCalc(mikeTeam); // 111
I am working on the Codility Peak problem:
Divide an array into the maximum number of same-sized blocks, each of which should contain an index P such that A[P - 1] < A[P] > A[P + 1].
My own solution is provided below, but it only scores 45%. So my question is:
How can I still improve my solution?
The code snippet seems to be long, since I added some extra comments to make myself clearer:
function solution(A) {
var storage = [], counter = 0;
// 1. So first I used a loop to find all the peaks
// and stored them all into an array called storage
for(var i = 1; i < A.length - 1; i++) {
if (A[i] > A[i-1] && A[i] > A[i+1]) {
storage.push(i);
}
}
// 2. Go and write the function canBeSeparatedInto
// 3. Use the for loop to check the counter
for(var j = 1; j < A.length; j++) {
if (canBeSeparatedInto(j, A, storage)) {
counter = j;
}
}
return counter;
}
/* this function tells if it is possible to divide the given array into given parts
* we will be passing our function with parameters:
* #param parts[number]: number of parts that we intend to divide the array into
* #param array[array]: the original array
* #param peaks[array]: an storage array that store all the index of the peaks
* #return [boolean]: true if the given array can be divided into given parts
*/
function canBeSeparatedInto(parts, array, peaks) {
var i = 1, result = false;
var blockSize = array.length / parts;
peaks.forEach(function(elem) {
// test to see if there is an element in the array belongs to the ith part
if ((elem+1)/blockSize <= i && (elem+1)/blockSize> i-1) {
i++;
}
});
// set the result to true if there are indeed peaks for every parts
if (i > parts) {
result = true;
}
return result;
}
The main problem with my code is that it does not pass the performance test. Could you give me some hint on that?
I would suggest this algorithm:
Sort the peeks by the distance they have with their predecessor. To do that, it might be more intuitive to identify "valleys", i.e. maximised ranges without peeks, and sort those by their size in descending order
Identify the divisors of the array length, as the solution must be one of those. For example, it is a waste of time to test for solutions when the array length is prime: in that case the answer can only be 1 (or zero if it has no peeks).
Try each of the divisors in ascending order (representing the size of array chunks), and see if for each valley such a split would bring one of the chunks completely inside that valley, i.e. it would not contain a peek: in that case reject that size as a solution, and try the next size.
Implementation with interactive input of the array:
"use strict";
// Helper function to collect the integer divisors of a given n
function divisors(n) {
var factors = [],
factors2 = [],
sq = Math.sqrt(n);
for (var i = 1; i <= sq; i++) {
if (n % i === 0) {
factors.push(n / i);
// Save time by storing complementary factor as well
factors2.push(i);
}
}
// Eliminate possible duplicate when n is a square
if (factors[factors.length-1] === factors2[factors2.length-1]) factors.pop();
// Return them sorted in descending order, so smallest is at end
return factors.concat(factors2.reverse());
}
function solution(A) {
var valleys = [],
start = 0,
size, sizes, i;
// Collect the maximum ranges that have no peeks
for (i = 1; i < A.length - 1; i++) {
if (A[i] > A[i-1] && A[i] > A[i+1]) {
valleys.push({
start,
end: i,
size: i - start,
});
start = i + 1;
}
}
// Add final valley
valleys.push({
start,
end: A.length,
size: A.length - start
});
if (valleys.length === 1) return 0; // no peeks = no solution
// Sort the valleys by descending size
// to improve the rest of the algorithm's performance
valleys.sort( (a, b) => b.size - a.size );
// Collect factors of n, as all chunks must have same, integer size
sizes = divisors(A.length)
// For each valley, require that a solution must not
// generate a chunk that falls completely inside it
do {
size = sizes.pop(); // attempted solution (starting with small size)
for (i = 0;
i < valleys.length &&
// chunk must not fit entirely inside this valley
Math.ceil(valleys[i].start / size) * size + size > valleys[i].end; i++) {
}
} while (i < valleys.length); // keep going until all valleys pass the test
// Return the number of chunks
return A.length / size;
}
// Helper function: chops up a given array into an
// array of sub arrays, which all have given size,
// except maybe last one, which could be smaller.
function chunk(arr, size) {
var chunks = [];
for (var i = 0; i < arr.length; i += size) {
chunks.push(arr.slice(i, i + size));
}
return chunks;
}
// I/O management
inp.oninput = function () {
// Get input as an array of positive integers (ignore non-digits)
if (!this.value) return;
var arr = this.value.match(/\d+/g).map(v => +v);
var parts = solution(arr);
// Output the array, chopped up into its parts:
outCount.textContent = parts;
outChunks.textContent = chunk(arr, arr.length / parts).join('\n');
}
Array (positive integers, any separator): <input id="inp" style="width:100%">
Chunks: <span id="outCount"></span>
<pre id="outChunks"></pre>
When checking whether array can be splitted into K parts, you will in worst case (array of [1,2,1,2,1,...]) do N/2 checks (since you are looking at every peak).
This can be done in K steps, by using clever datastructures:
Represent peaks as an binary array (0 - no peak, 1 - peak). Calculate prefix sums over that. If you want to check if block contains a peak, just compare prefix sums at the start and end of the block.
And also you have small other problem there. You should not check number of block which does not divide the size of the array.
This might be a duplicate, though I didn't find any questions specific to my problem here.
Say I have an array like this
var hundred = [1,2,3,4,5...100]
This array has 100 elements. From 1 to 100.
Based on an integer, how can I split this array into another array with the same amount of elements, except they've been evenly distributed like this?
var integer = 2;
var hundred = [50,50,50,50,50,50...100,100,100,100,100,100]
In this example, the array has 50 elements with the value 50, and 50 elements with the value 100, because the integer was 2.
I'm bad at math, so this might be incorrect, but I hope you understand what I mean. The array must have the same ammount of indexes after the calculation.
Edit (Due to me being very bad at formulating questions, I'm going to use the code I need this for here):
So I have a frequencybin array (from the AudioContext analyser):
var fbc_array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(fbc_array);
This array has a set number of elements ( They are the frequencies of audio played ).
Now I have a spectrum analyser, which has a set number of "bars" so if I have only 3 bars, then how can I split the fbc_array so that each bar has the evenly distributed frequency in it? For example, with 3 bars, bar one would have the bass, bar two would have the mids, bar three would have the treble.
I'm using a for loop for iterating over each bar:
for (i = 0; i < bars; i++) {
bar_x = i * canspace;
bar_width = 2;
bar_height = -3 - (fbc_array[i] / 2);
ctx.fillRect(bar_x, canvas.height, bar_width, bar_height);
}
Here's what I gathered from this craziness! Sorry you're having trouble conveying your problem. That's always a headache! Good luck.
//set integer to whatever you want
var integer = 3;
var randomNumber;
var output = new Array()
function getRandomIntInclusive(min, max) {
randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
}
for(i = 0; i<integer;i++){
getRandomIntInclusive(1,100);
for(j = 1; j< (100/integer); j++){
output.push(randomNumber);
}
}
//note, you will not always get 100 array items
//you can check with console.log(output.length);
console.log(output);
(Written before your update, so guessing here).
You're looking for a way to approximate a graph so that it's divided into bands and each point within a band is replaced with that band's maximum:
Number.prototype.times = function(fn) {
var a = [];
for(var i = 0; i < this; i++)
a.push(fn(i));
return a;
}
function approximate(src, n) {
var res = [],
size = Math.ceil(src.length / n),
i = 0;
while(i < src.length) {
var chunk = src.slice(i, i += size)
var p = Math.max.apply(null, chunk);
// this gives you an average instead of maximum
// p = chunk.reduce((x, y) => x + y) / chunk.length;
res = res.concat(size.times(i => p));
}
return res;
}
src = 20..times(i => 10 + Math.floor(Math.random() * 80));
res = approximate(src, 4);
document.write('<pre>'+JSON.stringify(src));
document.write('<pre>'+JSON.stringify(res));
How can you, in using a random number generator, stop a number from appearing if it has already appeared once?
Here is the current code:
var random = Math.ceil(Math.random() * 24);
But the numbers appear more than once.
You can use an array of possible values ( I think in your case it will be 24 ) :
var values = [];
for (var i = 1; i <= 24; ++i){
values.push(i);
}
When you want to pick a random number you just do:
var random = values.splice(Math.random()*values.length,1)[0];
If you know how many numbers you want then it's easy, first create an array:
var arr = [];
for (var i = 0; i <= 24; i++) arr.push(i);
Then you can shuffle it with this little function:
function shuffle(arr) {
return arr.map(function(val, i) {
return [Math.random(), i];
}).sort().map(function(val) {
return val[1];
});
}
And use it like so:
console.log(shuffle(arr)); //=> [2,10,15..] random array from 0 to 24
You can always use an hashtable and before using the new number, check if it is in there or not. That would work for bigger numbers. Now for 24, you can always shuffle an array.
You could put the numbers you generate in an array and then check against that. If the value is found, try again:
var RandomNumber = (function()
{
// Store used numbers here.
var _used = [];
return {
get: function()
{
var random = Math.ceil(Math.random() * 24);
for(var i = 0; i < _used.length; i++)
{
if(_used[i] === random)
{
// Do something here to prevent stack overflow occuring.
// For example, you could just reset the _used list when you
// hit a length of 24, or return something representing that.
return this.get();
}
}
_used.push(random);
return random;
}
}
})();
You can test being able to get all unique values like so:
for(var i = 0; i < 24; i++)
{
console.log( RandomNumber.get() );
}
The only issue currently is that you will get a stack overflow error if you try and get a random number more times than the amount of possible numbers you can get (in this case 24).
I have:
function getRandomInt(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min;
}
But the problem is I want randomise the population of something with elements in an array (so they do not appear in the same order every time in the thing I am populating) so I need to ensure the number returned is unique compared to the other numbers so far.
So instead of:
for(var i = 0; i < myArray.length; i++) {
}
I have:
var i;
var count = 0;
while(count < myArray.length){
count++;
i = getRandomInt(0, myArray.length); // TODO ensure value is unique
// do stuff with myArray[i];
}
It looks like rather than independent uniform random numbers you rather want a random permutation of the set {1, 2, 3, ..., N}. I think there's a shuffle method for arrays that will do that for you.
As requested, here's the code example:
function shuffle(array) {
var top = array.length;
while (top--) {
var current = Math.floor(Math.random() * top);
var tmp = array[current];
array[current] = array[top - 1];
array[top - 1] = tmp;
}
return array;
}
Sometimes the best way to randomize something (say a card deck) is to not shuffle it before pulling it out, but to shuffle it as you pull it out.
Say you have:
var i,
endNum = 51,
array = new Array(52);
for(i = 0; i <= endNum; i++) {
array[i] = i;
}
Then you can write a function like this:
function drawNumber() {
// set index to draw from
var swap,
drawIndex = Math.floor(Math.random() * (endNum+ 1));
// swap the values at the drawn index and at the "end" of the deck
swap = array[drawIndex];
array[drawIndex] = array[endNum];
array[endNum] = swap;
endNum--;
}
Since I decrement the end counter the drawn items will be "discarded" at the end of the stack and the randomize function will only treat the items from 0 to end as viable.
This is a common pattern I've used, I may have adopted it into js incorrectly since the last time I used it was for writing a simple card game in c#. In fact I just looked at it and I had int ____ instead of var ____ lol
If i understand well, you want an array of integers but sorted randomly.
A way to do it is described here
First create a rand function :
function randOrd(){
return (Math.round(Math.random())-0.5); }
Then, randomize your array. The following example shows how:
anyArray = new Array('1','2','3','4','5');
anyArray.sort( randOrd );
document.write('Random : ' + anyArray + '<br />';);
Hope that will help,
Regards,
Max
You can pass in a function to the Array.Sort method. If this function returns a value that is randomly above or below zero then your array will be randomly sorted.
myarray.sort(function() {return 0.5 - Math.random()})
should do the trick for you without you having to worry about whether or not every random number is unique.
No loops and very simple.