I want to generate light colors in RGB format.
A human being should be able to distinguish these colors easily.
I want a solution using JavaScript.
What I did:
var getRandom = function(min, max) {
return (Math.random() * (max - min) + min);
};
var randomColorGenerator = function(index) {
var p = getRandom(0,10)/10;
var q = getRandom(0,10)/10;
var r = getRandom(0,10)/10;
var max=235;
var min= 150;
var rgb = [Math.floor(min + p*(max-min)), Math.floor(min + q*(max-min)), Math.floor(min + r*(max-min))];
return rgb;
}
As you can see that can generate colors but we are not certain to get different colors...
A solution can be:
Two colors u,v are similar when their distance d(u,v) = sqrt [ (u(r)-v(r))^2 + ... + (u(b)-v(b))^2 ] / [sqrt(3)*255] < epsilon (where epsilon is small, assume that epsilon = 0.01);
Then we can create an array and use randomColorGenerator with that rule.
But I'm here to discuss it, about an efficient algorithm.
Basically, I will use it on the chart (Chart JavaScript) to generate a readable doughnut.
I think that we can group chart elements by three elements to do it.
When I have created charts, I would simply define a list of colors that I already knew looked good and distinguishable from each other, and used them in a specified order (looping back to the first if needed). I think this is the most reliable way to make sure your chart is both readable and aesthetically pleasing.
If your question was purely theoretical, I wouldn't have said anything, but since you said:
Basically, I will use it on chart (Chart Js) to generate a readable doughnut. I think that we can group chart elements by three elements to do it.
I just wanted to offer my two cents on it; and I would have just left a comment but my Stack Overflow reputation isn't high enough.
Related
For my Node.js application I need to choose the best performing structure to represent a grid.
My requirements/limitations are:
The grid to store is two-dimensional by nature (x, y) and not very large (100-300 cells)
Some cells in the grid contain nothing, i.e. the grid will be empty for up to 25%
I will have to address the grid very often. I'll need to do some heavy
algorithms to the grid, like flood-fill, A* pathfinding and some more
This will be a repetitive simulation process of changing the grid and applying the algorithms again
I aim at hundreds of simulations in a limited time, so every millisecond matters
I do not care about readability of the code
Amount of memory used is also a minor concern
Switch to another programming language is not possible
I've been choosing between three options:
var grid = [height][width];
grid[y][x] = {};
var grid = [height * width];
grid[y * height + x] = {};
var y = ~~(index % height);
var x = index - height * y;
var grid = [];
var key = x + ',' + y;
grid[key] = {};
The first one is the most comfortable as I will manipulate the coordinates a lot, meaning x and y will be handy all the time. Possible disadvantage - I've read it could be much slower when holding objects in comparison to 1D array.
The second is fine and probably very fast. But I will need to convert index to x and y and vice versa which is extra calculations involving modulo for index to coords conversion. Still I see this approach in many good sources.
The third way is new to me but I've seen it in some robust code examples and I've read that retrieving an object from hash table can be faster in comparison to 2D array as well.
I do not trust synthetic benchmarks too much so I do not wish to set up a code competition with almost empty logic so far. But I'm afraid it will be a very long way back if I pick a wrong way now and then will have to revert.
I've seen similar questions asking about different pairs of these methods, but none of them reflects my requirements close enough.
Thank you for your considerations with code samples.
I don't think the whole spreadsheet is relevant here (Hope I am not wrong) but essentially I am working with some financial figures and need to work out a "Cumulative Cost".
The spreadsheet is correct, but I don't understand the maths of the formula, so I hope somebody can break it down into BODMAS or pseudo code or something (or even Java which it will ultimately be.)
{=(PRODUCT($D$4:D7/100+1)-1)*100}
{=(PRODUCT($D$4:D8/100+1)-1)*100}
{=(PRODUCT($D$4:D9/100+1)-1)*100}
etc..
I think I only needed to supply one formula, but just giving a few more for context.
So the formulas above are found in column E:
Screenshot of Table
Thanks!
The part of the formula, /100+1, converts from a percentage change. The part, -1)*100, converts to a percentage change. PRODUCT() multiplies the numbers togther.
double d[12], e[12]; // input and output arrays, respectively
double p = 1.0; // to accumulate the product
for (i = 0; i < 12; i++)
{
p = p * ((d[i] / 100) + 1); // convert from percentage and multiply
e[i] = (p - 1) * 100; // convert to percentage
}
Additional ( and ) and spaces added for clarity.
I need a random number for many projects. For example, consider a video game in which the character finds a bag of gold that is partially empty. To set the percentage of gold in the bag, I would often use Math.floor(Math.random() * 100 + 0.5). Upon reading about geometric distribution, I sought to make a geometric distribution random percentage generator. After reading dozens of articles, I cobbled together this function:
function geoDistPercent() {
var rand = Math.random();
var prob = ???;
var rate = -Math.log(1 - prob);
var expr = -Math.log(rand)/rate;
return Math.floor(min + expr);
}
I have tried various numbers for prob = ???, but I am unable to find a way to add a maximum limit. I have tried many attempts at finding equations, to no avail. Pleas help!
UPDATE: I have just learned that geometric distribution has no maximum. I need a way to add one, so that results like "112%" are not generated. This could be done by adding a while loop and some control flow. It is the prob = ??? issue that I need help with.
Okay, after reviewing lots of articles and some other posts on SE, I cobbled together this solution:
function geoDist(min, max, prob) {
var q = 0;
var p = Math.pow(prob, 1 / (max - min));
while (true) {
q = Math.ceil(Math.log(1-Math.random()) / Math.log(p)) + (min - 1);
if (q <= max) {
return q;
}
}
}
It takes three parameters: min and max, as well as prob: the probability of getting max in one try. For generating percentages, geoDist(0,100,0.002) works exceptionally well. Thanks #NathanMerrill and #Bergi for providing helpful information
I am developing simple game program to show q-learning with linear function approximation.
screen shot
In this game, there are uncountable state. I have to consider many factors like player's position, speed, and enemy's position (there are 12 ~ 15 enemy objects). I ended up changing my algorithm from using table to use linear function approximation.
I decided around 20 ~ 22 features.(constant, player position, player speed, all of enemies position). and there is
After implementing that algorithm, I got stuck in some problem.
Weight value is overflowed in a few second after running my program. I found that I didn't normalize features and weight.
It was easy to normalize feature value because each feature has their bound .
However, It wasn't enough to normalize only feature value.
It still end up overflow.
My problem is how do I normalize my weights.
Below is my code to implement to normalize features.
//f is feature
f[0] = 1;
f[1] = this.getNormMinMax(this.player.x,0,cc.winSize.width);
f[2] = this.getNormMinMax(this.player.vel,-80,80);
for(var i=0; i<pooList.length;++i)
{
f[3 + 2*i] = this.getNormMinMax(pooList[i].x,0,cc.winSize.width);
f[3 + 2*i+1] = this.getNormMinMax(pooList[i].y,0,cc.winSize.height*3);
}
And this below code is updating weight without any normalization.
for(var i=0; i<this.featureSize; ++i)
{
var w = this.weightArray[this.doAction][i];
this.weightArray[this.doAction][i] =
w + this.learningRate*(this.reward + this.discountFactor*maxAction - this.updateQSA) * f[i];
}
It seems you're using Linear Regression without regularization, and there are collinear features. Try adding L1 or L2 regularization (use Ridge, Lasso or Elastic Net models).
I have a formula with several components, let's say w = x * y / z^2 + c. Now I have an input-field for each variable. My goal is, to calculate the missing one as soon, as all the others were entered. Difficulty is, that you can choose which fields you fill and which you want to leave free.
The easy (naive) way would of course be to resolve it for each variable by hand, detect the missing var, and have seperate js functions for each case. But I even have linked formulas (like x in the above formula is x = a + b, too) as well and the options are almost infinitive. Is there any option in JS to solve a formula by a specified variable? I could then replace each variable string with the assigned value and then eval the string.
First I thought Nerdamer would be the thing, but it turned out that it can only evaluate expressions and can't handle equations.
Is this possible? Any better idea?
Thanks in advance!
P.S.: My actual set of formula is:
dR = c * I^2 / A
R = L * dR
P = I * U
DV = R * I
DW = DV * I
It's for calculating losses in a cable due to ohm's resistance. Each Variable has a corresponding input field.
The following solution can be built for finding "R" using nerdamer. The logic can be extended to solve for the remaining variables. Do keep in mind that the current limitation is that nerdamer can currently only solve up to cubic functions algebraically. Higher order functions will be solved numerically.
//You can then take care of the non linear containing I. I is quadratic
var dR = nerdamer('R=L*dR').solveFor('dR');
var I = nerdamer('dR=c*I^2/A').sub('dR', dR).solveFor('I');
//You can first start by reducing the first few equations since they are linear and you can solve them as a linear system
var solutions = nerdamer.solveEquations(['P = I * U', 'DV = R * I', 'DW = DV * I'], ['I', 'DW', 'P']);
//the solutions come back as an array arrays in the form of [variable, value]
//you can see what they look like. In your case all your solutions will be in terns of DV & U since these are the only actual knowns
//You can see what the solutions look like
solutions.map(function(x) {
console.log('-'+x[0]+' = '+x[1]);
});
console.log('------------------ R ----------------');
var R = nerdamer.setEquation(I[0], solutions[0][1]).solveFor('R');
//I will have 3 solutions since it's cubic. You can console.log them below
R.map(function(x) {
console.log('R = '+x.toString());
});
<script src="https://cdn.jsdelivr.net/npm/nerdamer#latest/nerdamer.core.js"></script>
<script src="https://cdn.jsdelivr.net/npm/nerdamer#latest/Algebra.js"></script>
<script src="https://cdn.jsdelivr.net/npm/nerdamer#latest/Calculus.js"></script>
<script src="https://cdn.jsdelivr.net/npm/nerdamer#latest/Extra.js"></script>
<script src="https://cdn.jsdelivr.net/npm/nerdamer#latest/Solve.js"></script>