I am trying to make a simple java program, that calculates how much tickets would cost.
1 adult ticket is 10$, a child cost 5$ but a family ticket (2 adults and 2 children) is 26$. An obvious saving
So when input from the user, it needs to calculate how many family tickets (if applicable) and then pricing of items if they dont fit into a family bundle.
I.e.
Number of adults: 2
Number of children: 4
Number of family tickets: 1
Number of child tickets: 2
Total cost: $36
I cannot figure out the logic behind getting the pairings, comparing and taking out the extra items from both adults and children if needed. Here is what ive gotten so far:
double adultPairs,childPairs;
if (numberAdults <= 1) {
adultPairs = 0;
}
else if (isEven(numberAdults)) {
adultPairs = numberAdults / 2;
adultTickets = 0;
}
else {
adultPairs = numberAdults / 2;
adultTickets = 1;
}
if (numberChildren <= 1) {
childPairs = 0;
}
else if (isEven(numberChildren)) {
childPairs = numberChildren / 2;
childTickets = 0;
}
else {
childPairs = numberChildren / 2;
childTickets = 1;
}
What about this one?
int familyTickets = Math.min(adults/2, childs/2);
int adultTickets = adults - familyTickets*2;
int childTickets = childs - familyTickets*2;
First line compares the half of adults and childs (rounded down) and returns the minimum value of it. For example, if you have 9 adults and 25 children, it takes 9/2 and 25/2 which is 4 and 12, therefore it returns 4. And thats how much family tickets you want.
In next two lines, you just takes all adults/children and substract the adults/children family tickets, which is number of family tickets multiplied by two.
Even without Math.min method, it is quite easy :
int familyTickets = 0;
if (adults > childs){
familyTickets = childs/2;
} else {
familyTickets = adults/2;
}
int adultTickets = adults - familyTickets*2;
int childTickets = childs - familyTickets*2;
PS : Also note, that in Java, if you divide integer with integer, it returns another integer "rounded" down (it is not technically rounded, it just cut off anything less than 1) and it is what we need here. This is reason why I do not use double.
Related
So I have the following code
for (int i = 0; i <= numberOfTickets; i++)
{
System.out.println("Please enter your age or if you are a student enter -1");
int age = input.nextInt();
if ((age < 10) && (age > 0))
{
cost = (cost / 4);
}
else if ((age < 16) && (age >= 10))
{
cost = (cost / 2);
}
else if (age > 60)
{
cost = (cost / 2.5);
}
else if (age == -1)
{
cost = (cost / (4/3));
}
System.out.println(cost);
}
the problem is say that initially the cost is £10 and the user enters an age of 12 I want the value of £5 to be saved as say int ticketCost1 before continuing the for loop but starting with 10 again.
In essence i want to at the end of the loop have all the costs of the tickets with the individual discounts applied and to be then able to dd them all together and have a final cost.
P.S. I intend to add more so that for every child i.e. age 0 to 10 then they go free with anyone over the age of 16.
In java.
Make a new double, for now lets call it sum. Now instead of writing:
cost = (cost/whatever);
do this:
sum+= (cost/whatever);
now you save all them in 1 number summed, and cost stays as 10; while all the discounts are applied. Just make sure you initialize sum to 0 OUTSIDE and before the for loop
If I understand you correctly, you have a group of people of varying ages, and you want to find the total cost of all the tickets purchased by the group. You can have two lists, then: one to store the ages, and one to store the ticket costs. The cost of the group will be the total cost stored in the second list.
static final TICKET_PRICE = 10;
int getTotalCost(List<Integer> ages) { // populated list of ages
List<Integer> costs = new ArrayList<>();
for (int i : ages)
costs.add(getTicketPrice(int age));
int totalCost = 0;
for (int curr_cost : costs)
totalCost += curr_cost;
return totalCost;
}
int getTicketPrice(int age) {
int price;
if (age > 60) price = TICKET_PRICE/2.5;
... // all the other conditions, e.g. for students, children under 10, etc.
else price = TICKET_PRICE; // if no special condition applies
return price;
}
For the more complicated conditions (e.g. a child under 10 goes free with another person over the age of 16), it's best if you have a separate method to compute the total cost. Keep in mind that as you increase these conditions that depend not just on the individual, but on the age-distribution of the whole group, the optimal cost computation will start to resemble quite a complex problem in and of itself.
http://projecteuler.net/problem=1
Hey. I'm a high schooler trying to get a good grasp on programming problems, so I visited Project Euler. For Problem 1, I wrote up some code in Java that would of solved it, but something is evidently going wrong. Can I get some insight as to what?
Explanation:
I stop everything at the index value of 332 because Java counts from 0, and 333 * 3 is 999 which is below 1,000. Apples is a seperate class with pretty much the same code, although it counts for 5. At the end, I manually add together the two answers, but it wasn't right. What am I doing wrong?
The two final sums are:
Three: 164838
Five: 97515
public class Learning {
public static void main(String[] args){
int three[] = new int[333];
int counter = 0;
three[332] = 0;
int totalthree = 0;
int threeincrementer = 1;
int grandtotal;
boolean run = true;
boolean runagain = true;
for (counter = 1; counter<=332; counter++){
three[counter] = 3 * counter;
if (!(three[332] == 0)){
System.out.println("Finished three.");
while (run == true){
totalthree = totalthree + three[threeincrementer];
threeincrementer++;
if (threeincrementer >= 332){
run = false;
System.out.println("Three final is: " + totalthree);
}
}
}
if (runagain == true){
apples ApplesObject = new apples();
ApplesObject.rerun(0);
runagain = false;
}
}
}
}
Some numbers are at the same time multiplication of 3 AND 5 like 15 so you shouldn't separately calculate sum of all multiplications of 3 and multiplications of 5 and than add them because you will end up doing something like
sum3 = 3,6,9,12,15,...
sum5 = 5,10,15,...
so first sum3 will include 15, and sum5 will also include it which means you will add 15 two times. Now to balance your calculations you will need to subtract from your sum3+sum5 sum which will add all multiplications of 15
sum15 = 15,30,45,...
So using your approach your final formula should look like sum3+sum5-sum15.
But simpler solution for this problem can look like
sum = 0
for each X in 1...999
if (X is multiplication of 3) OR (X is multiplication of 5)
add X to sum
To check if some number X is multiplication of number Y you can use modulo operator % (example reminder = X % Y) which finds the remainder of division of one number by another.
You can find more Java operators here
As the title says, given a stock of integers 0-9, what is the last number I can write before I run out of some integer?
So if I'm given a stock of, say 10 for every number from 0 to 9, what is the last number I can write before I run out of some number. For example, with a stock of 2 I can write numbers 1 ... 10:
1 2 3 4 5 6 7 8 9 10
at this point my stock for ones is 0, and I cannot write 11.
Also note that if I was given a stock of 3, I could still write only numbers 1 ... 10, because 11 would cost me 2 ones, which would leave my stock for ones at -1.
What I have come up so far:
public class Numbers {
public static int numbers(int stock) {
int[] t = new int[10];
for (int k = 1; ; k++) {
int x = k;
while (x > 0) {
if (t[x % 10] == stock) return k-1;
t[x % 10]++;
x /= 10;
}
}
}
public static void main(String[] args) {
System.out.println(numbers(4));
}
}
With this I can get the correct answer for fairly big stock sizes. With a stock size of 10^6 the code completes in ~2 seconds, and with a stock of 10^7 numbers it takes a whole 27 seconds. This is not good enough, since I'm looking for a solution that can handle stock sizes of as big as 10^16, so I probably need a O(log(n)) solution.
This is a homework like assignment, so I didn't come here without wrestling with this pickle for quite some time. I have failed to come up with anything similiar by googling, and wolfram alpha doesn't recognize any kind of pattern this gives.
What I have concluded so far is that ones will allways run out first. I have no proof, but it is so.
Can anyone come up with any piece of advice? Thanks a lot.
EDIT:
I have come up with and implemented an efficient way of finding the cost of numbers 1...n thanks to btilly's pointers (see his post and comments below. also marked as a solution). I will elaborate this further after I have implemented the binary search for finding the last number you can write with the given stock later today.
EDIT 2: The Solution
I had completely forgotten about this post, so my apologies for not editing in my solution earlier. I won't copy the actual implementation, though.
My code for finding the cost of a number does the following:
First, let us choose a number, e.g. 9999. Now we will get the cost by summing the cost of each tens of digits like so:
9 9 9 9
^ ^ ^ ^
^ ^ ^ roof(9999 / 10^1) * 10^0 = 1000
^ ^ roof(9999 / 10^2) * 10^1 = 1000
^ roof(9999 / 10^3) * 10^2 = 1000
roof(9999 / 10^4) * 10^3 = 1000
Thus the cost for 9999 is 4000.
the same for 256:
2 5 6
^ ^ ^
^ ^ roof(256 / 10^1) * 10^0 = 26
^ roof(256 / 10^2) * 10^1 = 30
roof(256 / 10^3) * 10^2 = 100
Thus the cost for 256 is 156.
Implementing with this idea would make the program work only with numbers that have no digits 1 or 0, which is why further logic is needed. Let's call the method explained above C(n, d), where n is the number for which we are getting the cost for, and d is the d'th digit from n that we are currently working with. Let's also define a method D(n, d) that will return the d'th digit from n. Then we will apply the following logic:
sum = C(n, d)
if D(n, d) is 1:
for each k < d, k >= 0 :
sum -= ( 9 - D(n, k) ) * 10^(k-1);
else if D(n, d) is 0:
sum -= 10^(d-1)
With this the program will calculate the correct cost for a number efficiently. After this we simply apply a binary search for finding the number with the correct cost.
Step 1. Write an efficient function to calculate how much stock needs to be used to write all of the numbers up to N. (Hint: calculate everything that was used to write out the numbers in the last digit with a formula, and then use recursion to calculate everything that was used in the other digits.)
Step 2. Do a binary search to find the last number you can write with your amount of stock.
We can calculate the answer directly. A recursive formula can determine how much stock is needed to get from 1 to numbers that are powers of ten minus 1:
f(n, power, target){
if (power == target)
return 10 * n + power;
else
return f(10 * n + power, power * 10, target);
}
f(0,1,1) = 1 // a stock of 1 is needed for the numbers from 1 to 9
f(0,1,10) = 20 // a stock of 20 is needed for the numbers from 1 to 99
f(0,1,100) = 300 // a stock of 300 is needed for the numbers from 1 to 999
f(0,1,1000) = 4000 // a stock of 4000 is needed for the numbers from 1 to 9999
Where it gets complicated is accounting for the extra 1's needed when our calculation lands after the first multiple of any of the above coefficients; for example, on the second multiple of 10 (11-19) we need an extra 1 for each number.
JavaScript code:
function f(stock){
var cs = [0];
var p = 1;
function makeCoefficients(n,i){
n = 10*n + p;
if (n > stock){
return;
} else {
cs.push(n);
p *= 10;
makeCoefficients(n,i*10);
}
}
makeCoefficients(0,1);
var result = -1;
var numSndMul = 0;
var c;
while (stock > 0){
if (cs.length == 0){
return result;
}
c = cs.pop();
var mul = c + p * numSndMul;
if (stock >= mul){
stock -= mul;
result += p;
numSndMul++;
if (stock == 0){
return result;
}
}
var sndMul = c + p * numSndMul;
if (stock >= sndMul){
stock -= sndMul;
result += p;
numSndMul--;
if (stock == 0){
return result;
}
var numMul = Math.floor(stock / mul);
stock -= numMul * mul;
result += numMul * p;
}
p = Math.floor(p/10);
}
return result;
}
Output:
console.log(f(600));
1180
console.log(f(17654321));
16031415
console.log(f(2147483647));
1633388154
So I have this program about a robber who walks into a bank. He finds N gold bars. He can carry M bars at a time and he takes T seconds to go between his car and the bank.
Input
3
3 2 10
35 68 42
25 70 1
First line is how many times the program will run/how many robberies.
First line of the first run (3 2 10), the 3 represents N, the number of gold bars. 2 represents M, number of bars the robber can carry at a time and 10 represents T, the time it takes for the robber to travel between his car and the bank.
Output
30
42
1
This was my logic to it but according to the graders of this program, it failed their test data (they have a different input). I tried many combinations of numbers and the answers still came out right. Does anyone see what could be wrong with this?
/* NOTE:
1 <= First line of input <= 10
1 <= N <= 100
1 <= M <= 100
1 <= T <= 100 */
public class Stealing
{
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner (new File ("stealing.dat"));
int numRuns = scan.nextInt();
int time = 0;
for (int i = 0; i < numRuns; i++)
{
int N = scan.nextInt();
int M = scan.nextInt();
int T = scan.nextInt();
if (M >= N)
time = T;
else
{
while (N > 0)
{
if (M <= N)
time += (2*T);
else
time += T;
N -= M;
}
}
out.println(time);
time = 0;
}
}
}
The error in your logic shows up when N is a multiple of M, for example the input
6 3 1
produces 4, but it should produce 3.
The problem is with this condition:
if (M <= N)
it should be:
if (M < N)
By testing for equality too, the bank robber makes one more trip back to the bank, but there's nothing to collect, so the loop ends (with her at the bank, rather than at the car - another logic problem).
If I were doing this I would not use a loop - I would use purely numerical methods (an exercise for the reader, but hover over the following to see my solution):
int time = (N / M) * 2 * T + (N % M == 0 ? -T : T);
I am developing a sport torunament in Java based on round robin scheduling algorithm. For n teams I want to generate 2(n-1) rounds with n/2 matches. That is that every team must play a match in a round, and every 2 teams meet twice, once away and once home. I managed to implement the algoritm except for the home/away part. I am able to generate the rounds, but can not "swap" the teams in the second half of rounds so they play both away and home.
Here is what I have so far:
public class sports {
public static void main(String[] args) {
//obtain the number of teams from user input
Scanner input = new Scanner(System.in);
System.out.print("How many teams should the fixture table have?");
int teams = input.nextInt();
// Generate the schedule using round robin algorithm.
int totalRounds = (teams - 1) * 2;
int matchesPerRound = teams / 2;
String[][] rounds = new String[totalRounds][matchesPerRound];
for (int round = 0; round < totalRounds; round++) {
for (int match = 0; match < matchesPerRound; match++) {
int home = (round + match) % (teams - 1);
int away = (teams - 1 - match + round) % (teams - 1);
// Last team stays in the same place
// while the others rotate around it.
if (match == 0) {
away = teams - 1;
}
// Add one so teams are number 1 to teams
// not 0 to teams - 1 upon display.
rounds[round][match] = ("team " + (home + 1)
+ " plays against team " + (away + 1));
}
}
// Display the rounds
for (int i = 0; i < rounds.length; i++) {
System.out.println("Round " + (i + 1));
System.out.println(Arrays.asList(rounds[i]));
System.out.println();
}
}
}
Don't mind even/odd number of teams, for now I am only interested in even teams number.
To codify True Soft's answer,
String roundString;
if (round < halfRoundMark) {
roundString = ("team " + (home + 1)
+ " plays against team " + (away + 1));
} else {
roundString = ("team " + (away + 1)
+ " plays against team " + (home + 1));
}
rounds[round][match] = roundString;
where
int halfRoundMark = (totalRounds / 2);
You have to see when you get to the half of the rounds, and then switch the home and away teams.
Pleas Refer this link which described Round Robin Algorithm for "Odd-Number of teams" as well as "Even-Number of teams".
Ref this link:- https://nrich.maths.org/1443
1) Odd Number of teams :-
For Odd number of teams, Consider following formulas and conditions
Abbreviations :-
TNR = Total Number Of Rounds
NOT = Number Of Teams
MPR = Match Per Round
Formulas :-
Total Number Of Rounds = Number Of Teams
Match Per Round = [ ( Number Of Teams - 1 ) / 2 ]
Conditions :- There must be only one team in round, which gets bye(would not play game). So each round has only one bye and each team will play once in round with other team.
Lets consider this algorithm's implementation in c# (Odd-Number Of Teams)
Suppose we have 5 Teams
Teams :-
Barcilona (0)
Brazil (1)
Madrid (2)
Colambo (3)
Woshington DC (4)
Here ,
Number Of Teams (NOT)= 5
Total Number Of Rounds (TNR) = 5
Matches Per Round (MPR) = [ ( NOT - 1 ) / 2 ] = [ ( 5 - 1 ) /2 ] = 2
Now Conside the link in which each round has one team which gets bye, and other team play once in round with another team.
now put all teams in array named Teams
int[] teams = new int[NOT];
so, int[] teams = new int[5];
now teams = [0,1,2,3,4]
now we will rotate array by 1 step left while moving on next round and teams[0] will always gets By and play games between other team but the problem is that how we can decide which team plays game with which team. so to resolve those issue, refere Reference Link. So you can identify that In round 0, matched will be played with following teams
Teams[0] = 0 = Barcilona Gets Bye(Not played game)
Teams[1] - Teams[4] = (Brazil - Woshington DC)
Teams[2] - Teams[3] = (Madrid - Colambo)
so, consider the following implementation
public class Teams {
public int Team1 { get; set; }
public int Team2 { get; set; }
}
//Dictionary< round , matches >
var matchScheduling = new Dictionary<int, List<Teams>>();
for (int round = 0; round < TNR; round++) {
List<Teams> matches = new List<Teams>();
int team1 = teams[0];
int team2 = -1;
matches.Add(new Teams() { Team1 = team1, Team2 = team2 });
for (int match = 0; match < MPR; match++) {
team1 = teams[match + 1];
team2 = teams[(NOT.Length - 1) - match];
roundTeams.Add(new Teams() { Team1 = team1, Team2 = team2 });
}
matchScheduling.Add(round, roundTeams);
//Now for next round, Rotate team Array
int length = teams.Length;
int tmp = teams[length - 1];
for (int i = length - 1; i > 0; i--) {
teams[i] = teams[i - 1];
}
teams[0] = tmp;
}