I am struck in a tricky situation where I need to calculate the number of combinations to form 100 based on different factors.
Those are
Number of combinations
Multiplication factor
distance
Sample input 1: (2-10-20)
It means
list the valid 2 way combination to form 100.
the distance between the combination should be less than or equal to 20.
And all of the resultant combination must be divisible by the given multiplication factor 10
Output will be
[40,60]
[50,50]
[60,40]
here [30,70],[20,60] are invalid because the distance is above 20.
Sample Input 2: [2-5-20]
[40,60]
[45,55]
[50,50]
[55,45]
[60,40]
I would really appreciate if you guided me to the right direction.
Cheers.
I hope it's not a homework problem!
def combinations(n: Int, step: Int, distance: Int, sum: Int = 100): List[List[Int]] =
if (n == 1)
List(List(sum))
else
for {
first <- (step until sum by step).toList
rest <- combinations(n - 1, step, distance, sum - first)
if rest forall (x => (first - x).abs <= distance)
} yield first :: rest
If you need to divide 100 over 2 with a maximum distance of N, the lowest value in the combination is
100 / 2 - N / 2
If you need to divide 100 over 3 values with a maximum distance of N, this becomes more tricky. The average of the 3 values will be 100/3, but if one of them is much lower than this average, than the other can only be slightly bigger than this average, meaning that the minimum value is not the average minus the maximum distance divided by two, but probably
100 / 3 - 2N / 3
In general with M values, this becomes
100 / M - (M-1)N / M
Which can be simplified to
(100 - (M-1)N) / M
Similarly we can calculate the highest possible value:
(100 + (M-1)N) / M
This gives you a range for first value of your combination.
To determine the range for the second value, you have to consider the following constraints:
the distance with the first value (should not be higher than your maximum distance)
can we still achieve the sum (100)
The first constraint is not a problem. The second is.
Suppose that we divide 100 over 3 with a maximum distance of 30 using multiples of 10
As calculated before, the minimum value is:
(100 - (3-1)30) / 3 --> 13 --> rounded to the next multiple of 10 --> 20
The maximum value is
(100 + (3-1)30) / 3 --> 53 --> rounded to the previous multiple of 10 --> 50
So for the first value we should iterate over 20, 30, 40 and 50.
Suppose we choose 20. This leaves 80 for the other 2 values.
Again we can distribute 80 over 2 values with a maximum distance of 30, this gives:
Minimum: (80 - (2-1)30) / 2 --> 25 --> rounded --> 30
Maximum: (80 + (2-1)30) / 2 --> 55 --> rounded --> 50
The second constraint is that we don't want a distance larger than 30 compared with our first value. This gives a minimum of -10 and a maximum of 50.
Now take the intersection between both domains --> 30 to 50 and for the second value iterate over 30, 40, 50.
Then repeat this for the next value.
EDIT:
I added the algorithm in pseudo-code to make it clearer:
calculateRange (vector, remainingsum, nofremainingvalues, multiple, maxdistance)
{
if (remaingsum==0)
{
// at this moment the nofremainingvalues should be zero as well
// found a solution
print vector
return;
}
minvalueaccordingdistribution = (remainingsum-(nofremainingvalues-1)*maxdistance)/nofremaingvalues;
maxvalueaccordingdistribution = (remainingsum+(nofremainingvalues-1)*maxdistance)/nofremaingvalues;
minvalueaccordingdistance = max(values in vector) - maxdistance;
maxvalueaccordingdistance = min(values in vector) + maxdistance;
minvalue = min (minvalueaccordingdistribution, minvalueaccordingdistance);
maxvalue = max (minvalueaccordingdistribution, minvalueaccordingdistance);
for (value=minvalue;value<=maxvalue;value+=multiple)
{
calculaterange (vector + value, remainingsum - value, nofremainingvalues-1, multiple, maxdistance);
}
}
main()
{
calculaterange (emptyvector, 100, 2, 20);
}
Why can't you use a brute force approach with few optimization? For example, say
N - Number of combinations
M - Multiples
D - Max possible Distance
So possible values in combinations can be M, 2M, 3M and so on. You need to generate this set and then start with first element from set and try to find out next two from choosing values from same set (provided that they should be less than D from first/second value).
So with i/p of 3-10-30 would
Create a set of 10, 20, 30, 40, 50, 60, 70, 80, 90 as a possible values
Start with 10, choice for second value has to be 20, 30, 40, 50 (D < 30)
Now choose second value from set of 20, 30, 40, 50 and try to get next value and so on
If you use a recursion then solution would become even simpler.
You have to find N values from a
list of possible values within MIN &
MAX index.
So try first value at
MIN index (to MAX index). Say we
have chosen value at X index.
For every first value, try to find
out N-1 values from the list where MIN =
X + 1 and MAX.
Worst performance will happen when M = 1 and N is sufficiently large.
Is the distance between all the additive factors, or between each of them? For example, with 3-10-20, is [20-40-60] a valid answer? I'll assume the latter, but the solution below can be modified pretty trivially to work for the former.
Anyway, the way to go is to start with the most extreme answer (of one sort) that you can manage, and then walk the answers along until you get to the other most extreme.
Let's try to place numbers as low as possible except for the last one, which will be as high as possible (given that the others are low). Let the common divisor be d and divide 100 by it, so we have S = 100/d. This quantizes our problem nicely. Now we have our constraint that spacing is at most s, except we will convert that to a number of quantized steps, n = s/d. Now assume we have M samples, i1...iM and write the constraints:
i1 + i2 + i3 + ... + iM = S
0 <= i1 <= n
0 <= i2 <= n
. . .
0 <= iM <= n
i1 <= i2
i2 <= i3
. . .
i(M-1) <= iM
We can solve the first equation to get iM given the others.
Now, if we make everything as similar as possible:
i1 = i2 = ... = iM = I
M*I = S
I = S/M
Very good--we've got our starting point! (If I is a fraction, make the first few I and the remainder I+1.) Now we just try to walk each variable down in turn:
for (i1 = I-1 by -1 until criteria fails)
sum needs to add to S-i1
i2 >= i1
i2 <= i1 +n
solve the same problem for M-1 numbers adding to S-i1
(while obeying the above constraint on i2)
Well, look here--we've got a recursive algorithm! We just walk through and read off the answers.
Of course, we could walk i1 up instead of down. If you need to print off the answers, may as well do that. If you just need to count them, note that counting up is symmetric, so just double the answer you get from counting down. (You'll also have a correction factor if not all values started the same--if some were I and some were I+1, you need to take that into account, which I won't do here.)
Edit: If the range is what every value has to fit within, instead of all the
0 <= i1 <= n
conditions, you have
max(i1,i2,...,iM) - min(i1,i2,...,iM) <= n
But this gives the same recursive condition, except that we pass along the max and min of those items we've already selected to throw into the mix, instead of adding a constraint on i2 (or whichever other variable's turn it is).
Input:
(2-10-20)
Divide the number by param 1
(50,50)
2 Check whether the difference rule allows this combination. If it hurts the rule, then STOP, if it allows, then add this and it's combinations to the result list
For example: abs(50-50)<20, so it is ok
3 Increase the the first value by param 2, decrease the second value by param 2
Go 2. point
Related
I guess this is more of a math question, but how come when you divide a double by 1 it returns the decimal points too?
For example, 123.23 % 1 is equal to 0.23.
Shouldn't it return only 0?
MSDN reference says that module does this ex - (x / y) * y where x is the dividend and why is the divider and if you calculate it like that it should return 0.
So tell me how come does it return the decimal points too?
You are not simply dividing by 1, you are taking the modulus. The modulus returns the remainder from the division of the first argument with the second.
This means it subtracts the highest complete divider from the input and returns the remainder. In your case that would be
123.23 - 123 = 0.23
since 123 can be divided by 1 without "anything left". What's left is then the 0.23 you experience.
The modulus operator is handy in many situations. Two very common ones are:
Checking for Even/Odd numbers
If you have an integer number and take the modulo 2 the result is 1 for odd and 0 for even numbers.
Checking for the nth iteration
If you have a loop and say you want to print a result every 10th iteration you could have a continous counter and use code like
if (Counter % 10 == 0) then {
Console.WriteLine("Tick Tock");
}
See MSDN for further examples: https://msdn.microsoft.com/de-de/library/0w4e0fzs.aspx?f=255&MSPPError=-2147217396
Could anyone give me a hint on how to generate "smooth" random numbers?
Here's what I mean by smooth:
The random numbers shall be used in a game, e.g. for wind direction and strength (does anyone remember goood old "Worms"?). Of course setting random numbers for those values every second or so would look awfully choppy.
I would rather have some kind of smooth oscillation in a given value range. Sort of like a sine wave but much more random.
Does anyone get what I'm after? ;-)
Any ideas on how to achieve this kind of behavior would be appreciated.
If you want the delta (change) to be small, just generate a small random number for the delta.
For example, instead of:
windspeed = random (100) # 0 thru 99 inclusive
use something like:
windspeed = windspeed - 4 + random (9) # -4 + 0..8 gives -4..4
if windspeed > 99: windspeed = 99
elif windspeed < 0: windspeed = 0
That way, your wind speed is still kept within the required bounds and it only ever changes gradually.
This will work for absolute values like speed, and also for direction if the thing you're changing gradually is the angle from a fixed direction.
It can pretty well be used for any measurement.
Alternatively, if you want to ensure that the windspeed changes with a possibly large delta, but slowly, you can generate your target windspeed as you currently do but move gradually toward it:
windspeed = 50
target = windspeed
while true:
# Only set new target if previous target reached.
if target == windspeed:
target = random (100)
# Move gradually toward target.
if target > windspeed:
windspeed = windspeed + max (random (4) + 1, target - windspeed)
else:
windspeed = windspeed - max (random (4) + 1, target - windspeed)
sleep (1)
Perlin (or better simplex) noise would be the first method that comes to mind when generating smoothed noise. It returns a number between 1 and -1, which will add or subtract from the current value. You can multiple that to make it seem less subtle or better yet... make the lowest wind value -1 and highest wind value 1.
Then simply have a seeder as a counter (1,2,3... etc) as the perlin/simplex input keep the values 'smooth'.
I created a new version of a smooth random number. The idea is that our random number is going to be within limits = [average - oscillation, average + oscillation], and will change everytime [-varianciance, +variance].
But, if it reaches the limits, our variance is going to be reduce.
E.g. numbers from [0, 100], with variance of 10. If the current value = 8, then the variance will be [0, 18]
python code:
def calculate_smooth_random(current_value, average, oscillation, variance):
max_value = average + oscillation
min_value = average - oscillation
max_limit = min(max_value, current_value + variance)
min_limit = max(min_value, current_value - variance)
total_variance = max_limit - min_limit
current_value = min_limit + random.random() * total_variance
print("current_value: {}".format(current_value))
return current_value
Image for distribution with values:
average: 20
oscillation: 10
variance: 5
I have a need to create a graph, where the scale of the Y-axis changes depending on the data input into the system. Conceivably this scale could be anywhere from 0-10, 0-100, or even have bottom limit of thousands and an upper limit of millions.
To properly determinethe scale of this axis, I need to work out the ratio of Points to Pixels (based on graph height/range).
Now a graphs' axis never start at the lowest value and go to the highest, usual practice is to go to the next nearest 2, 5 or 10 (above for upper limit, and below for lower) depending on the range of values.
So what I'd like to know is how to take the max value from the data set, and round it up to the nearest 10.
for clarification, the input values will always be integers.
what i have now is this
if ((rangeMax < 10) && (rangeMax > 5))
rangeMax = 10;
else if (rangeMax < 5)
rangeMax = 5;
Which is only useful for values less than 10, and doesn't allow the flexibility required to be truly dynamic. Ultimately this graph will be auto-generated during a page load event, with no user input.
I've read around a bit, and people talk about things like the modulus operator (%), but I can't find any reliable information about it's use, and talk of Math.Ceiling and Math.Round, but these go to the next nearest whole number, which isn't quite there, and don't seem to help much at all when dealing with integers anyway.
Any suggestions, pointers or help greatly appreciated.
i did find a similar question asked here How can i get the next highest multiple of 5 or 10 but i don't know java, so i can't understand any of what was said.
Cheers
if(rangeMax % 10 !=0)
rangeMax = (rangeMax - rangeMax % 10) + 10;
You could also use Math.Round() with MidpointRounding.AwayFromZero using a decimal number (otherwise integer division will truncate fractions):
decimal number = 55M;
decimal nextHighest = Math.Round(number/ 10, MidpointRounding.AwayFromZero) * 10;
If you want to go up to the next 10, you can use Math.Ceiling as follows:
rangeMax = (int)(Math.Ceiling((decimal)rangeMax / 10) * 10);
If you need to generalize to go to the next n (for example 5 here) you can do:
int n = 5;
rangeMax = (int)(Math.Ceiling((decimal)rangeMax / n) * n);
Something which might help is to divide the number by 10. This should round it to the nearest integer. Then multiply it by 10 again to get the number rounded to the nearest 10
I use THIS:
public static double RoundTo10(double number)
{
if (number > 0)
{
return Math.Ceiling(number / 10) * 10;
}
else
{
return Math.Floor(number / 10) * 10;
}
}
you can try this....
decimal val = 95;
//decimal val =Convert.ToDecimal( textBox1.Text);
decimal tmp = 0;
tmp = (val % 10);
//MessageBox.Show(tmp.ToString()+ "Final val:"+(val-tmp).ToString());
decimal finval = val - tmp;
I'm currently implementing a software that measures certain values over time. The user may choose to measure the value 100 times over a duration of 28 days. (Just to give an example)
Linear distribution is not a problem, but I am currently trying to get a logarithmical distribution of the points over the time span.
The straight-forward implementation would be to iterate over the points and thus I'll need an exponential function. (I've gotten this far!)
My current algorithm (C#) is as follows:
long tRelativeLocation = 0;
double tValue;
double tBase = PhaseTimeSpan.Ticks;
int tLastPointMinute = 0;
TimeSpan tSpan;
for (int i = 0; i < NumberOfPoints; i++)
{
tValue = Math.Log(i + 1, NumberOfPoints);
tValue = Math.Pow(tBase, tValue);
tRelativeLocation = (long)tValue;
tSpan = new TimeSpan(tRelativeLocation);
tCurrentPoint = new DefaultMeasuringPointTemplate(tRelativeLocation);
tPoints.Add(tCurrentPoint);
}
this gives me a rather "good" result for 28 days and 100 points.
The first 11 points are all at 0 seconds,
12th point at 1 sec,
20th at 50 sec,
50th at 390 min,
95th at 28605 mins
99 th at 37697 mins (which makes 43 hours to the last point)
My question is:
Does anybody out there have a good idea how to get the first 20-30 points further apart from each other, maybe getting the last 20-30 a bit closer together?
I understand that I will eventually have to add some algorithm that sets the first points apart by at least one minute or so, because I won't be able to get that kind of behaviour into a strictly mathematical algorithm.
Something like this:
if (((int)tSpan.TotalMinutes) <= tLastPointMinute)
{
tSpan = new TimeSpan((tLastPointMinute +1) * 600000000L);
tRelativeLocation = tSpan.Ticks;
tLastPointMinute = (int)tSpan.TotalMinutes;
}
However, I'd like to get a slightly better distribution overall.
Any cool ideas from you math cracks out there would be greatly appreciated!
From a practical point of view, the log function squeezes your time point near the origin already. A power function squeezes them even more. How about simple multiplication?
tValue = Math.Log(i + 1, NumberOfPoints);
tValue = tBase * tValue;
Another way to flatten the curve is start farther from the origin.
for (int i = 0; i < NumberOfPoints; i++)
{
tValue = Math.Log(i + 10, NumberOfPoints + 9);
The range of tvalue is still 0 to 1.
How about this to have a minimum space of 1 second at the beginning?
double nextTick = 0;
for (int i = 0; i < NumberOfPoints; i++)
{
tValue = Math.Log(i + 1, NumberOfPoints);
tValue = Math.Pow(tBase, tValue);
if (tValue < nextTick) tValue = nextTick;
nextTick++;
The distribution curve you choose depends on what you're measuring.
A straight line, a sine wave, a polynomial or exponential curve may individually be the best distribution curve for a given set of measurements.
Once you've decided on the distribution curve, you calculate the missing data points by calculating the y value for any given time value (x value), using the mathematical formula of the curve.
As an example, for a straight line, all you need is one data point and the slope of the line. Let's say at time 0 the measured value is 10, and the measurement goes up by 2 every minute. The formula would by y = 2 * x + 10. if we wanted to calculate the measurement when x = 5 (minutes), the formula gives us a measurement of 20.
For a logarithmic curve, you'd use a logarithm formula. For simplicity, let's say that the actual measurements give us a formula of y = 2 ** x + 12; You plug in the time values (x values) you want to calculate, and calculate the measurements (y values).
Realize that you are introducing calculation errors by calculating data points instead of measuring. You should mark the calculated data points in some manner to help the person reading your graph differentiate them from actual measurements.
I am not exactly sure what you are trying to do, your code does not seem to match your example (it could be that I am screwing up the arithmetic). If you want your samples to have a minimum separation of 1 sec, and each point at a location of x times the last point (except for the first) then you want to find x such that x^(n - 1) = span. This is just x = exp(log(span) / (n - 1)). Then your points would be at x^i for(i = 0; i < n; i++)
My question is i have a certain money amount, lets say 552.
I wish to split that in its coins/bills => So the result would for example be 1x 500 1x 50 1x 2
I have made 2 arrays for this:
double[] CoinValue = {500, 200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01};
uint[] CoinAmount = new uint[CoinValue.Length];
My problem is how exactly do i "tell" the array the value for 500 should be 1 in the countAmount array.=> 1. So if i have 1000 the array CoinAmount array would know it would need to hold 2 as value(2x500 = 1000).
So my end result would be something like this, giving the amount of coin/bills:
1 x 500
1 x 50
1 x 2
.......
Thanks in advance.
Don't use doubles if you want exact answers. Use either decimals or integer arithmetic (by converting to cents).
I'm not going to provide full source code as this looks like homework or a learning exercise, so instead I'll just give a few hints.
To find out how many notes of a certain denomination you need, use division:
int number = (int)(total / sizeOfBill);
Start with the largest bills and work downwards to the smallest to get a small number of notes/coins, otherwise you could end up with thousands of cent coins instead of a few bills.
Not an answer: a harder version of the problem for you to consider.
The coinage system you describe has a nice property that when you repeatedly "take out" the largest denomination from the remaining total, you end up with the solution that has the smallest number of bills/coins. FYI, an algorithm which operates by repeatedly choosing the largest thing is called a "greedy algorithm"; in this case, the greedy algorithm give an optimal result, if you're optimizing for the smallest number of bills/coins.
Can you solve the problem for a coinage system where the coins are:
1 crown = 60 pence ("pence" is the plural of "penny")
1 half-crown = 30 pence
1 florin = 24 pence
1 shilling = 12 pence
1 tanner = 6 pence
The greedy algorithm for making change now does not work if you are optimizing for the smallest number of coins. For example, 48 pence by the greedy algorithm goes
take out a half-crown, leaving 18 pence
take out a shilling, leaving 6 pence
take out a tanner, leaving nothing
Three coins. But obviously 48 pence is two florins, which is only two coins.
Can you come up with an algorithm that handles this coinage system and gives the least number of coins possible for every problem?
(Note that the pre-decimal British coinage system is suitable for neither decimal nor double arithmetic; do it all in integers!)
PLEASE use decimal for this; double is rarely suitable for money types:
double value = 0.3;
value -= 0.1;
value -= 0.1;
value -= 0.1;
Console.WriteLine(value); //**not** zero
Anyway, a very crude approach (also assumes that the coins are sorted descending and that all values are non-negative) is below. It gets trickier if you don't have coins for the lowest values (i.e. you have 0.5M and 0.2M but no 0.1M and need to issue 0.8M - since this needs 4x0.2M, not 0.5M+0.2M+(damn))
decimal value = 10023.23M;
decimal[] CoinValue = { 500, 200, 100, 50, 20, 10, 5, 2, 1, 0.5M, 0.2M, 0.1M, 0.05M, 0.02M, 0.01M };
int[] counts = new int[CoinValue.Length];
for (int i = 0; i < CoinValue.Length; i++) {
decimal v = CoinValue[i];
while (value >= v) {
counts[i]++;
value -= v;
}
}
for (int i = 0; i < CoinValue.Length; i++) {
if (counts[i] > 0) {
Console.WriteLine(CoinValue[i] + "\t" + counts[i]);
}
}
Console.WriteLine("Untendered: " + value);
Given your array ... also works with decimals of course.
double[] CoinValue = { 500, 200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01 };
uint[] result = new uint[CoinValue.Length];
double ammount = 552.5;
double remaining = ammount;
for (int i = 0; i < CoinValue.Length; ++i) {
result[i] = (uint) (remaining / CoinValue[i]);
if (result[i] > 0)
remaining = remaining % CoinValue[i];
}