In my Java Program I have a method:
private void giveMoney(int money) {
int notes[] = {10, 20, 50, 100, 200, 500};
StringBuffer cash = new StringBuffer();
int i = notes.length - 1;
while (i >= 0)
if (notes[i] > money)
i--;
else {
cash.append(notes[i]).append(" ");
money -= notes[i];
}
System.out.print(cash);
}
For, example, if
money == 990
the output will be: 500 200 200 50 20 20
I want to work out how to calculate how the cash will be dispensed using the following notes: 500, 200, 100, 50, 20, 10.
If I got your question correct, this is the line you want:
int amount = (int) Math.floor(money/banknotes[i]);
The whole function:
private void giveCash(int money) {
int banknotes[] = {10, 20, 50, 100, 200, 500};
StringBuffer cash = new StringBuffer();
int i = banknotes.length - 1;
while (i >= 0) {
if (banknotes[i] > money) {
i--;
} else {
int amount = (int) Math.floor(money/banknotes[i]);
cash.append(banknotes[i]).append("x").append(amount).append(" ");
money -= banknotes[i]*amount;
}
}
TextView tvCash = (TextView) findViewById(R.id.cash);
tvCash.setText(cash);
}
Output:
500x1 200x2 50x1 20x2
Basically get an int count of how many times each note goes into an adjusted total. i.e. you adjust the total to remove any value of that has been dispensed with larger notes.
Using modulus you get the remainder that is not divisible by that note and pass that value as the adjusted value to test for how many notes can be dispensed in that denomination.
I've given you the algorithm.
500_amounts = (int) amount/500
500_Leftover = amount % 500
200_amounts = (imt) 500_Leftover/200
200_Leftover = 500_Leftover % 200
100_amount = (int) 200_Leftover/100
100_Leftover = 200_Leftover % 100
// and so on
Note this is pseudo code and you cannot name your variable like this, nor will it run like this.
I should add for best practices it's best to use constants for the values of the denominations and as suggested in the other answer, as it is not explicit here, it would be good to loop through these.
Related
I am trying to create a method so that if the user enters a number of cents over 99, the updateMoney method will add dollars accordingly and then place the extra change once the cents goes under 100.
public void updateMoney(int cent) {
int addDollars = 0;
int change = 0;
if (cent > 99) {
for(int i = cent; i > 99; i -= 100)
{
addDollars += 1;
cent -= 100;
}
}
this.dollars = dollars + addDollars;
this.cents = cent;
}
public Money(int dol, int cent) {
if (cent < 0 || dol < 0) {
System.out.println("Invalid amount entered");
} else {
if (cent > 99) {
updateMoney(cent);
}
this.dollars = dol;
this.cents = cent;
}
}
This is the code I am currently working with.
I had originally tried a different method that ended up not working so I tried doing something like this instead but my outputs are still off.
In my driver I ran
Money money = new Money(15, 300); and the output was $15.00 when it should end up being $18.99
You should consider storing your dollars and cents in one long value. The following code takes your dollars and cents, combines them, adds the user's inputted cents correctly, and splits them up in dollars and cents again. But why not just keep them together all the time?
long dollarsWithCents = dollars * 100 + cents;
dollarsWithCents += parsedUserInput;
cents = dollarsWithCents % 100;
dollars = dollarsWithCents / 100;
I have been given min and max number,
e.g: min = 10 and max = 1000 now i want to split this number into equal parts and in result i should get 10 numbers.
like: 100, 200, 300, 400, 500, 600, 700 , 800 , 900, 1000
this we can do by dividing max with number we want e.g: 1000/10 and add 100 every time.
but, there is one scenario in which we have been given :
min = 14 and max = 1113 in this case if we divide 1113/10 then we will get 111
and the range will come like 0 , 113, 226, 339 ...
but, i don't want to show them like this . It would be better if i can display 110 or 115 or 120 even numbers (round off) instead of 113.
Can anyone help me.
In your example, when min=14 and max=1113 you divide 1113/10 to get 111. If you want to round 111 down to 110, you can perform 111 - (111 % 10) to get 110. Then simply iterate 10 times and multiply the beginning number by the current iteration.
There is a similar post to this here: How to round *down* integers in Java?
Depending on what numbers you want to display (either 110 or 115 or 120) you can approach this in a similar way.
That is an algorithm for scaling a diagram; distributing ticks on an axis.
However 10 ticks is then an over-estimate.
private int[] ticks(int min, int max) {
int gap = (max - min) / 10;
// Round gap up to a nice value - best calculatory:
if (gap < 1) {
gap = 1;
} else if (gap < 5) {
gap = 5;
} else if (gap < 10) {
gap = 10;
} else if (gap < 50) {
gap = 50;
} else if (gap < 100) {
gap = 100;
} else if (gap < 250) {
gap = 250;
...
}
int minTick = (min/gap) * gap;
if (minTick > min) { // For negative numbers.
minTick -= gap;
}
int maxTick = (max/gap) * gap;
if (maxTick > min) { // Negative, and ceiling.
maxTick += gap;
}
int ngap = (maxTick - minTick) / gap;
int[] ticks = new int[ngaps + 1];
for (int i = 0; i <= ngaps; ++i) {
ticks[i] = minTick + i * gap;
}
return ticks;
}
In the country of Rahmania, the cost of mailing a letter is 40 sinas for letters up to 30 grams. Between 30 g and 50 g, it is 55 sinas. Between 50 g and 100 g, it is 70 sinas. Over 100 g, it costs 70 sinas plus an additional 25 sinas for each additional 50 g (or part thereof). For example, 101 grams would cost 70 + 25 = 95 sinas. 149 g would also cost 95 sinas, because both of these packages only use the first 50 g over 100 g. Write a program that prompts the user for a mass and then gives the cost of mailing a letter having that mass.
This is the question and the only part I don't know how to do is the last part with the additional 25 sinas for each additional 50g.
Can someone show me how to write this part of the code?
I use netbeans btw.
Scanner input = new Scanner(System.in);
double l;
l = input.nextInt();
x = l >= 100 / 50 * 25 + 70;
if (l <= 30) {
System.out.println("40 Sinas");
}
if (l > 30 && l < 50) {
System.out.println("55 Sinas");
}
if (l > 50 && l < 100) {
System.out.println("70 Sinas");
}
if (l >= 100) {
System.out.println("");
}
Here's the important part of the code. As you can see I need help on the last part.
A solution:
Scanner input = new Scanner(System.in);
int l; // it should be int if read int
l = input.nextInt();
if (l <= 30) {
System.out.println("40 Sinas");
}
if (l > 30 && l < 50) {
System.out.println("55 Sinas");
}
if (l > 50 && l < 100) {
System.out.println("70 Sinas");
}
if (l >= 100) {
System.out.println(((((l - 100) / 50) + 1) * 25) + 70);
}
I just want to point out, there is one major problem with Krayo's solution. If the weight value is exactly 100, using that calculation, you will in fact charge the customer an extra 25 sinas. This is caused by the + 1 portion of the calculation.
If the weight is 100, then the number of 50 gram intervals above 100 is 0 (weight - 100 = 0). Therefore, the customer shouldn't be charge anything, since the wording of the question says Over 100 g.... However, because you're adding 1, before performing the additional cost calculation, the customer gets dinged an extra 25 sinas needlessly.
Instead, in order to insure the correct amount for this, and all other cases, I would use the Math.ceil(double) method instead. This method will round the value up to the nearest whole number. For example, 5.2 becomes 6.0, and 5.0 remains 5.0.
So your calculation would look like this instead:
int cost = (int) (Math.ceil((weight - 100) / 50.0f) * 25) + 70;
Note that we need use a floating point value to ensure we end up with a decimal value. And since Math.ceil returns a double, we simply cast it back to an integer.
This is a sample program to demonstrate this:
public class CalculationTesting {
public static void main(String[] args){
int weight = 100;
int good_cost = (int) (Math.ceil((weight - 100) / 50.0f) * 25) + 70;
int bad_cost = ((((weight - 100) / 50) + 1) * 25) + 70;
System.out.println("Weight = " + weight + "g");
System.out.println("Good cost calculation = $" + good_cost);
System.out.println("Bad cost calculation = $" + bad_cost);
}
}
You can change the weight value to experiment.
Which outputs:
Weight = 100g
Good cost calculation = $70
Bad cost calculation = $95
int Cnt(){
return Count (10);
}
int Count (int init){
int u = init % 10;
int t = (init % 100) - u;
int u2 = u * u;
int t2 = t * t;
int m = u2 + t2;
if(m <= 1)
System.out.println("Happy!");
else {
return Count (m);
}
This code should (in theory) check if number is Happy, and if it's not sets initial value to be same as the result and whole process repeats.
Infinite loop should occur if number is not happy.
However none of this happens, does anyone know how to make this work?
According to the Wiki article that you linked, you have to repeat the process of summing the digits of the digits in each number. For the example of 7:
7^2 = 49
49 = 4^2 + 9^2 = 16 + 81 = 97
97 = 9^2 + 7^2 = 81 + 49 = 130
130 = 1^2 + 3^2 = 10
10 = 1^2 = 1
I see a few problems with your code. First, you haven't divided your tens digit by 10, which means for the number 52, you will get u = 2, and t = 50, rather than 5. This part, I'm sure you can easily fix.
Second, it looks like you will never reach a conclusion if your number is unhappy. For example with the number 4, you will reach 16, 37, 72, 53, 34, 25, 29, 85, 89, 145, 42, 20, 4. But your program, since you have no way of checking that you've entered a loop, will run until you run out of memory.
Try using the approach as outlined in the article you referenced:
private static boolean isHappy(int number)
{
List<Integer> set = new ArrayList<Integer>();
while (number > 1 && !set.contains(number))
{
set.add(number);
number = sumSquaresOfDigits(number);
}
return number == 1;
}
private static int sumSquaresOfDigits(int number)
{
String numberString = Integer.toString(number);
int result = 0;
for (char character : numberString.toCharArray())
{
int digit = Character.digit(character, 10);
result += digit * digit;
}
return result;
}
This can be done more efficiently by computing the squares of all 10 digits (0-9) and storing the results in an integer array.
Since this is homework I am not putting in the answer... but here is the clue..
You are not handling 3 digit numbers well.
t=init%100-u computes to 10%100-0 = 10
and once m=u2+t2 i.e. m=0+100 reaches to 100 and your program doesn't handle 3 digit numbers. Hope this helps.
add following...
int h = init/100;
int h2 = h * h;
int m = u2+t2+h2;
and it should keep you going... :)
import java.io.*;
class happy_no
{
void happy(double n)
{
int c=0;
double s=0;
double d,p,i,_sa;
for(i=1;i<=n;i++)
{
while(n!=0)
{
d=n%10;
p=d*d;
s=s+p;
n=n/10;
}
if(s==1)
{
System.out.println("HAPPY NO.");
break;
}
else
{
n=s;
}
}
}
public static void main()throws IOException
{
InputStreamReader read=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(read);
double a;
System.out.println("ENTER A NO.");
a=Double.parseDouble(in.readLine());
happy_no obj=new happy_no();
obj.happy(a);
}
I'm trying to solve this problem, its not a homework question, its just code I'm submitting to uva.onlinejudge.org so I can learn better java trough examples. Here is the problem sample input :
3 100
34 100
75 250
27 2147483647
101 304
101 303
-1 -1
Here is simple output :
Case 1: A = 3, limit = 100, number of terms = 8
Case 2: A = 34, limit = 100, number of terms = 14
Case 3: A = 75, limit = 250, number of terms = 3
Case 4: A = 27, limit = 2147483647, number of terms = 112
Case 5: A = 101, limit = 304, number of terms = 26
Case 6: A = 101, limit = 303, number of terms = 1
The thing is this has to execute within 3sec time interval otherwise your question won't be accepted as solution, here is with what I've come up so far, its working as it should just the execution time is not within 3 seconds, here is code :
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int start;
int limit;
int terms;
int a = 0;
while (stdin.hasNext()) {
start = stdin.nextInt();
limit = stdin.nextInt();
if (start > 0) {
terms = getLength(start, limit);
a++;
} else {
break;
}
System.out.println("Case "+a+": A = "+start+", limit = "+limit+", number of terms = "+terms);
}
}
public static int getLength(int x, int y) {
int length = 1;
while (x != 1) {
if (x <= y) {
if ( x % 2 == 0) {
x = x / 2;
length++;
}else{
x = x * 3 + 1;
length++;
}
} else {
length--;
break;
}
}
return length;
}
}
And yes here is how its meant to be solved :
An algorithm given by Lothar Collatz produces sequences of integers, and is described as follows:
Step 1:
Choose an arbitrary positive integer A as the first item in the sequence.
Step 2:
If A = 1 then stop.
Step 3:
If A is even, then replace A by A / 2 and go to step 2.
Step 4:
If A is odd, then replace A by 3 * A + 1 and go to step 2.
And yes my question is how can I make it work inside 3 seconds time interval?
From Googling I found this thread where a couple of other people have had the same problem and the solution is to use 64-bit arithmetic instead of 32-bit arithmetic.
Try changing int to long and see if that helps.