I have two items in the cart item 1= $70 and item 2= $100 and i also have the total shipping i can charge, which is $15. While accepting this order Im trying to split the $15 shipping between item1 and item2 in a weighted manner based on the price. What is the best algorithm to split this and what is the logic/calculation look like ?
Any thoughts helpful, thanks !
I don't know Java, but since you included no Java code, I'll just give pseudocode to how to do this:
a = 70 / (70 + 100)
b = 100 / (70 + 100)
This normalizes the two values, and then you can just multiply a and b with $15 to get the proper ratio. In this case, a is 0.41 and b is 0.59
Then:
ratio_item_a = 15 * a
ratio_item_b = 15 * b
ratio_item_a is 6.18 and ratio_item_b is 8.82
Related
I were solving:
We know the content of the evaporator (content in ml), the percentage of foam or gas lost every day (evap_per_day) and the threshold (threshold) in percentage beyond which the evaporator is no longer useful. All numbers are strictly positive. The program reports the nth day (as an integer) on which the evaporator will be out of use.
My solution with recursion:
if (content > (initialContent / 100) * threshold) {
double postContent = content - (content / 100) * evap_per_day;
iterations++;
return recursiveEvaporator(postContent, evap_per_day, threshold, initialContent, iterations);
}
But then I found more sophisticated solution:
return (int)Math.ceil(Math.log(threshold / 100.0) / Math.log(1.0 - evap_per_day / 100.0));
Could you please explain me how does logarithms work here and why we choose natural logarithm?
First of all you have to obtain a clear image of e, that is the base of the natural logarithm.
e - is constant that represents approximation of (1 + 1/n)^n that we call for when speaking about constant growth
We see that newly appeared "addition" participated in further exponentiation.Roughly speaking: e^x is our income after x, where x is t*r (t-time; r-rate)
ln(y) is a reverse operation, we are aimed to know the time over rate we have to spend waiting for y income.
Bringing back the subject of your question
ln(threshold) - is t*r(time * rate)
ln(1 - evap_per_day) - is a t*r to evoparate 90% !but not initial, again we need ln because 90% is constantly decreasing and we chould include it into account.
We divide a product of ln(threshold) by ln(1 - evap_per_day) to get know the time.
So the correct solution is: (int)Math.ceil(Math.log(threshold / 100.0) / (ln(1.0 - evap_per_day / 100.0))
This is a case of using exponential decay and solving for time
The Exponential decay formula is A = A_o(1 - r)^t where A is the final quantity, A_o is the inital quantity, r is the rate of decay and t is the time.For this question we want to know the number of days until the intial amount is at or below a threshold percentage of the initail amount, evaperating at a cetain percentage per day. We can rewrite the equation as so:
(using the percent values for threshold and evapPerDay to make explaination easier)
A_o(threshold) = A_o( 1 - evapPerDay)^t
simplifies to:
threshold = (1 - evapPerDay)^t
now we use logs to solve for t
log(threshold) = log((1- evapPerDay)^t)
use one of the laws of logs to move the t
log(threshold) = t(log(1-evapPerDay))
solve for t
log(threshold)/log(1-evapPerDay) = t
Use ceiling to round up.
Write a program that reads the total number of pieces of oranges, eggs, apples, watermelons, and bagels they purchased. Calculate the total bill and subtotals for each item using the following prices:
a.Oranges: 10 for 2.99/0.50 each
b.Eggs: 12 for 1.69/0.25 each
c.Apples: 3 for 1.00/0.75 each
d.Watermelons: 4.39 each
e.Bagels: 6 for 3.50/0.95 each
I'm a little bit confused for on what method should I use to program/solve this problem? I'm thinking to use a If statement but I think it's not a good idea. How should i start my coding? This is my first time encountering a price system with (I think discount?) fix amount of price on each item. It's bothering me to think that how can i do a "2.99 for 10 apples" while one apple is 0.50?" should I use discount? My mind is bleeding right now -_-
Here is an algorithm for solving the problem. Go step by step and implement the logic. I am sure you will get the final result.
Take the count for one fruit and display it.
From the count, calculate the sub-total price by taking the rate as per piece. Display the sub-total.
Store the sub-total you got in 2nd step in a separate variable and display it.
Follow the steps 1 to 3 for other fruits now, storing the sub-total of each fruit in a separate variable.
Calculate the final total by adding the values of all sub-total variables.
For applying the discounts, you can use a simple if...else logic along with some arithmetic operators.
6.1 Divide the count by 10 (for oranges) and store it in a variable called tmp.
6.2 If tmp is greater than 0,
subTotal = tmp * price_of_10
count = count - (tmp * 10)
subTotal = subTotal + (count * price_of_1)
6.3 If tmp is equal to zero
subTotal = count * price_of_1
I can help you get started. I don't want to give you all the code because I still want you to learn from it.
//Read number of Oranges here
//Some code
if(number = 10) price = 2.99
else price = number*0.50
total += price
Repeat for other products, don't forget to change the price value
EDIT: if you want to buy more than 10 and still get the discount, you will need to do something like this
int ten = 0;
Double rest =0;
if(number/10 >= 1){
ten = number/10;
rest = number%10;
price = ten*2.99 + rest*0.50;
}else{
price = number*0.50
}
total += price
Right now I've got a method that can get data from a 2D array, throw it into a Arraylist and then lets me retrieve only the particular parts from that Arraylist that I want.
The code below loops through the races Arraylist and places the racers, the total times and how many events they take part in into an array, as of yet unordered in any way.
if (!Found && selected.equals(race.GetCat()))
{
ranking[j][0] = race.GetComp();
ranking[j][1] = race.GetCat();
ranking[j][2] = (GetSecs(race.GetRace1()))
+ (GetSecs(race.GetRace2()))
+ (GetSecs(race.GetRace3())) + "";
n++;
};
Found= false;
for (int i = 0; i < locations.size(); i++)
{
for (Race race: races)
{
if (race.GetComp().equals(array[i][0]) && option.equals(array[i][1]))
{
seconds += (GetSes(race.GetRace1()))
+ (GetSes(race.GetRace2()))
+ (GetSes(race.GetRace3()));
total= GetMin(seconds);
counter++;
}
ranking[i][2] = total2 + "";
ranking[i][3] = counter + "";
}
}
So ranking prints out like
RACER TOTAL TIME EVENTS TAKING PART IN
name 230.44 2
name 142.51 4
name 523.01 7
name 444.55 2
name 432.18 4
And ordering the rankings (String) array so that it is sorted via perhaps the number of events or the total time of the races would not be too difficult.
However, more than one racer will take part in the same number of events, so I was wondering what process or code I would have to go through in order to order the array based on the number of events, and then check to see which rankings share the number of events, and then switch them around based on which total time is lowest
So rankings sorted like
george 500 5
john 400 5
george 500 4
david 300 3
carl 200 3
is sorted like
john 400 5
george 500 5
george 500 4
carl 200 3
david 300 3
If something like that is possible. I can put them into an array, and even sort them by one particular column, but sorting them by one, and then by another if the first column has numbers are are the same is totally beyond me, if any of this post makes sense.
Check out:
Column Comparator. It allows you to sort on any column in an ArrayList.
Group Comparator. It allows you to sort on multiple columns at the same time.
Example 1:
Shop selling beer, available packages are 6 and 10 units per package. Customer inputs 26 and algorithm replies 26, because 26 = 10 + 10 + 6.
Example 2:
Selling spices, available packages are 0.6, 1.5 and 3. Target value = 5. Algorithm returns value 5.1, because it is the nearest greater number than target possible to achieve with packages (3, 1.5, 0.6).
I need a Java method that will suggest that number.
Simmilar algorithm is described in Bin packing problem, but it doesn't suit me.
I tried it and when it returned me the number smaller than target I was runnig it once again with increased target number. But it is not efficient when number of packages is huge.
I need almost the same algorithm, but with the equal or greater nearest number.
Similar question: Find if a number is a possible sum of two or more numbers in a given set - python.
First let's reduce this problem to integers rather than real numbers, otherwise we won't get a fast optimal algorithm out of this. For example, let's multiply all numbers by 100 and then just round it to the next integer. So say we have item sizes x1, ..., xn and target size Y. We want to minimize the value
k1 x1 + ... + kn xn - Y
under the conditions
(1) ki is a non-positive integer for all n ≥ i ≥ 1
(2) k1 x1 + ... + kn xn - Y ≥ 0
One simple algorithm for this would be to ask a series of questions like
Can we achieve k1 x1 + ... + kn xn = Y + 0?
Can we achieve k1 x1 + ... + kn xn = Y + 1?
Can we achieve k1 x1 + ... + kn xn = Y + z?
etc. with increasing z
until we get the answer "Yes". All of these problems are instances of the Knapsack problem with the weights set equal to the values of the items. The good news is that we can solve all those at once, if we can establish an upper bound for z. It's easy to show that there is a solution with z ≤ Y, unless all the xi are larger than Y, in which case the solution is just to pick the smallest xi.
So let's use the pseudopolynomial dynamic programming approach to solve Knapsack: Let f(i,j) be 1 iif we can reach total item size j with the first i items (x1, ..., xi). We have the recurrence
f(0,0) = 1
f(0,j) = 0 for all j > 0
f(i,j) = f(i - 1, j) or f(i - 1, j - x_i) or f(i - 1, j - 2 * x_i) ...
We can solve this DP array in O(n * Y) time and O(Y) space. The result will be the first j ≥ Y with f(n, j) = 1.
There are a few technical details that are left as an exercise to the reader:
How to implement this in Java
How to reconstruct the solution if needed. This can be done in O(n) time using the DP array (but then we need O(n * Y) space to remember the whole thing).
You want to solve the integer programming problem min(ct) s.t. ct >= T, c >= 0 where T is your target weight, and c is a non-negative integer vector specifying how much of each package to purchase, and t is the vector specifying the weight of each package. You can either solve this with dynamic programming as pointed out by another answer, or, if your weights and target weight are too large then you can use general integer programming solvers, which have been highly optimized over the years to give good speed performance in practice.
In my class, i have to calculate prices of 18 different building which have different prices and income. They also have changes in price when the money of quantity of the building increases.
For example: The building starts at 40 dollars when the quantity is 0. The price increments by 4 for each quantity. So if you own 1, the price to buy the next same building will be 44 in state of 40. So this is the method that will calculate the price just fine.
public float getBuildingPrice(float quantity)
{
float buildingNum = quantity;
float startingPrice = 40;
float costIncrease = 4;
float finalPrice;
finalPrice = startingPrice + (costIncrease*buildingNum);
return finalPrice;
}
The method above returns the price and i divided the calculated price with the income that comes to the building like this. 10 is the income
float storageWorth = buildingPrice/10;
The thing i am unable to do is to find out the amount of different building the user can buy in the most efficient way ( meaning highest income but lowest spending ) So it should be the lowest Price / income that should be fulfilling the condition but also keeping in mind that it must be in the budget that the user keys in. There is always a change in the price and i do not know how to compare multiple values ( 18 values ) with the extra condition to keep in the budget.
For example
Farm
Income - 1
5 buildings
Increment of 4
Price 40 + (5 * 4) = 60
Price over income = 60
Pen
Income - 5
4 Buildings
Increment of 20
Price 200 + (4 * 20) = 280
Price over income 280/5 = 56
So meaning to say the next building the user should buy is a pen because it has lower price/income. There is also chances that the price over income of both building is the same like if the building reaches 5 for pen building, both price over income of pen and farm will be 60.
This is a formulation of your problem that ends up a mixed integer and non linear programming problem:
For all building type i let's define:
Pi : price of building type i
Ci : Price increment of building type i
Mi : income for building type i
B : Budget
Ni : Number of buildings of type i purchased.
Purchasing Ni building of type i equals:
Sum for j=1 to Ni Pi + (j - 1) × Ci = Ni (Pi + ( Ni - 1) / 2 × Ci)
Mixed integer non linear programming formulation:
Maximise Sum for i Ni × Mi
Subject to : sum for i Ni (Pi + (Ni - 1) / 2 ×Ci) <= B
Note that Pi, Ci, Mi and B are constants. Decision variables are Ni
An other solution is to purchase a building at a time selecting the one with the maximum income per invested money as per the following ratio:
Mi / (Ni (Pi + ( Ni - 1) / 2 × Ci))
At each step you calculate the building with the maximum ratio, purchase a building, deduct the price of the budget and repeat until the budget is exhausted. I do not have a proof that you will get an optimum my following this algorithm.
Third solution pseudocode (brute force):
(income, index_list) function maximize_income(i, b)
if i > last_building_type
return 0, []
endif
max_income = 0
max_income_index = 0
while b >= P(i) - (j-1) * C(i)
b = b - P(i) - (j-1) * C(i)
(income, index_list) = maximize_income(i+1, b)
income = income + j * M(i)
if income > maximum_income
maximum_income = income
maximum_income_index = j
endif
endwhile
add maximum_income_index to index_list
return maximum_income, index_list
end function
index_list is an array containing the number of each type of building
Your problem is a linear programming problem. Such problems don't have easy answers.
To solve such problems, people have invented many smart algorithms like the Simplex Algorithm.
These alogrigthms work on a represenation of the problem that basically is a set of mathematical linear equations. You have to think hard about your problem and formulate these equations.
A C library to solve a LP problem forumlated this way is the GLPK (GNU Linear Programming Kit). There are frontends for Python and for Java.
Your question is not a programming problem. It is a mathematical problem that can be solved in any language. Give enough time, it can even be solved on paper.