i am trying to make an if statment that adds 3 to an iteger every time the if statment is met. I know how to add 1 using coins++ but is there a way to add 3.
if (other.tag == "yes")
{
coins + 3;
}
coins += 3;
is a more compact way than coins = coins + 3;.
Related
Writing a program to solve problem four of project euler: Find the largest palindrome made from the product of two 2-digit numbers. Heres my reprex:
#include <iostream>
int reverseNumber(int testNum)
{
int reversedNum, remainder = 0;
int temp = testNum;
while(temp != 0)
{
remainder = temp % 10;
reversedNum = reversedNum * 10 + remainder;
temp /= 10;
}
return reversedNum;
}
int main()
{
const int MIN = 100;
int numOne = 99;
int product = 0;
for(int numTwo = 10; numTwo < 100; numTwo++)
{
product = numOne * numTwo;
if (reverseNumber(product) == product)
{
int solution = product;
std::cout << solution << '\n';
return 0;
}
}
return 0;
}
My main thought process behind this is that the for loop will go through every number from 10 to 99 and multiply it by 99. My intended outcome is for it to print 9009 which is the largest palindrome with 2 factors of 2 digits. So what I think should happen here is the for loop will go from 10 to 99, and each loop it should go through the parameters of the if statement which reverses the number and sees if it equals itself.
I've made sure it wasn't a compiler issue, as this is recurring between different compilers. The reverseNumber() function returns the proper number every time I've tested it, so that shouldn't be the problem, however this problem only occurs when the function is involved in the logical comparison. By this I mean if that even I set it equal to a variable and put the variable in the if parameters, the issue still occurs. I'm pretty much stumped. I just hope it's not some silly mistake as I've been on this for a couple days now.
int reversedNum, remainder = 0;
You should be aware that this gives you (in an automatic variable context) a zero remainder but an arbitrary reversedNum. This is actually one of the reasons some development shops have the "one variable per declaration" rule.
In other words, it should probably be:
int reversedNum = 0, remainder;
or even:
int reversedNum = 0;
int remainder;
One other thing that often helps out is to limit the scope of variable to as small an area as possible, only bringing them into existence when needed. An example of that would be:
int reverseNumber(int testNum) {
int reversedNum = 0;
while (testNum != 0) {
int remainder = testNum % 10;
reversedNum = reversedNum * 10 + remainder;
testNum /= 10;
}
return reversedNum;
}
In fact, I'd probably go further and eliminate remainder altogether since you only use it once:
reversedNum = reversedNum * 10 + testNum % 10;
You'll notice I've gotten rid of temp there as well. There's little to gain by putting testNum into a temporary variable since it's already a copy of the original (as it was passed in by value).
And one other note, more to do with the problem rather than the code. You seem to be assuming that there is a palindrome formed that is a multiple of 99. That may be the case but a cautious programmer wouldn't rely on it - if you're allowed to assume things like that, you could just replace your entire program with:
print 9009
Hence you should probably check all possibilities.
You also get the first one you find which is not necessarily the highest one (for example, let's assume that 99 * 17 and 99 * 29 are both palindromic - you don't want the first one.
And, since you're checking all possibilities, you probably don't want to stop at the first one, even if the nested loops are decrementing instead of incrementing. That's because, if 99 * 3 and 97 * 97 are both palindromic, you want the highest, not the first.
So a better approach may be to start high and do an exhaustive search, while also ensuring you ignore the palindrome check of candidates that are smaller that your current maximum, something like (pseudo-code)
# Current highest palindrome.
high = -1
# Check in reverse order, to quickly get a relatively high one.
for num1 in 99 .. 0 inclusive:
# Only need to check num2 values <= num1: if there was a
# better palindrome at (num2 * num1), we would have
# already found in with (num1 * num2).
for num2 in num1 .. 0 inclusive:
mult = num1 * num2
# Don't waste time doing palindrome check if it's
# not greater than current maximum - we can't use
# it then anyway. Also, if we find one, it's the
# highest possible for THIS num1 value (since num2
# is decreasing), so we can exit the num2 loop
# right away.
if mult > high:
if mult == reversed(mult):
high = mult
break
if high >= 0:
print "Solution is ", high
else:
print "No solution"
In addition to properly initializing your variables, if you want the largest palindrome, you should switch the direction of your for loop -- like:
for(int numTwo = 100; numTwo > 10; numTwo--) {
...
}
or else you are just printing the first palindrome within your specified range
https://en.wikipedia.org/wiki/Yacht_(dice_game)
I created 5 dice in my c++ program and they each roll random numbers from 1-6.
So if you get all 1's its really simple. It's just:
if (dice1 == 1 && dice2 == 1 && dice3 == 1 && dice4 == 1 && dice5 == 1)
{
int total = 50;
}
Also, summing all the dice is easy too. But how could you write the if-statement for "if two to four dice are the same then sum up those dice"? Is there a simple way you could do that?
Try to use tables and make variable which count 1 in table. Then u can compare it.
import math
def is_prime(num):
if num < 2:
return False
for i in range(2, int(math.sqrt(num))+ 1):
if num % i == 0:
return False
return True
Primes seems to be a popular topic but in the book in which I am learning Python, I am on chpt 6 out of 21 and in the iteration chapter which it teaches while loops. I have not learned for loops yet although I understand what they do. So, let's say I have not learned for loops yet and am given only if/elif/else statements and the while loops as my tools. How can I change the for line of code into something more simple using the above tools? While asking this question I quickly came up with this code:
def formula(num):
i = 2
while i >= 2:
return int(math.sqrt(num)+ 1)
def is_primetwo(num):
i = 2
if num < 2:
return False
formula(num)
if num % i == 0:
return False
return True
It works but would this be a simple version of the for loop or is there something even more simple where I do not have to wrap a function within a function?
Absolutely, you do not need a function to replace a for loop.
So you've got this
for i in range(2, int(math.sqrt(num))+ 1):
which is your for loop. Take a second to think what it's doing.
1.) It's taking the variable i, and it's starting it at a value of 2.
2.) It's checking whether to do the loop every time by checking if i is less than the (square root of num) plus 1
3.) Every time through the loop, it adds one to i.
We can do all of these things using a while loop.
Here's the original
for i in range(2, int(math.sqrt(num))+ 1):
if num % i == 0:
return False
let's rename the second and third lines loop contents just so we're focusing on the looping part, not what logic we're doing with the variables i and num.
for i in range(2, int(math.sqrt(num))+ 1):
loop contents
ok, now let's just rearrange it to be a while loop. We need to set i to 2 first.
i = 2
Now we want to check that i is in the range we want
i = 2
while i <= int(math.sqrt(num) + 1):
loop contents
Now we're almost set, we just need to make i actually change, instead of staying at a value of 2 forever.
i = 2
while i <= int(math.sqrt(num) + 1):
loop contents
i = i + 1
Your example seemed to do some of these elements, but this way is a simple way to do it, and no extra function is necessary. It could be the range() function that is confusing. Just remember, the for loop is doing three things; setting a variable to an initial value, checking a condition (one variable is less than another), and incrementing your variable to be one large than previously to run the loop again.
How about something like:
from math import sqrt
def is_prime(num):
if (num < 2):
return False
i = 2
limit = int(sqrt(num) + 1)
while (i <= limit):
if num % i == 0:
return False
i = i + 1
return True
Not sure if this is what you want, but the for loop:
for i in range(2, int(math.sqrt(num))+ 1):
if num % i == 0:
return False
return True
can be expressed as:
i = 2
while i < int(math.sqrt(num))+ 1):
if num % i == 0:
return False
i += 1
return True
Probably a good idea to determine int(math.sqrt(num))+ 1) once:
i = 2
n = int(math.sqrt(num))+ 1)
while i < n:
if num % i == 0:
return False
i += 1
return True
I am making a simple (terminal) slot machine project, in which 3 fruit names will be output in the terminal, and if they are all the same then the player wins.
I cannot figure out how to make a set probability that the player will win the round (roughly 40% chance for example). As of now I have:
this->slotOne = rand() % 6 + 1; // chooses rand number for designated slot
this->oneFruit = spinTOfruit(this->slotOne); //converts rand number to fruit name
this->slotTwo = rand() % 6 + 1;
this->twoFruit = spinTOfruit(this->slotTwo);
this->slotThree = rand() % 6 + 1;
this->threeFruit = spinTOfruit(this->slotThree);
which picks a "fruit" based on the number, but each of the three slots has a 1 in 6 chance (seeing that there are 6 fruits). Since each individual slot has a 1/6 chance, overall the probability of winning is incredibly low.
How would I fix this to create better odds (or even better, chosen odds, changing the odds when desired)?
I thought of changing the second two spins to less options (rand()%2 for instance), but that would make the last two slots choose the same couple fruits every time.
The link to my project: https://github.com/tristanzickovich/slotmachine
Cheat.
Decide first if the player wins or not
const bool winner = ( rand() % 100 ) < 40 // 40 % odds (roughly)
Then invent an outcome that supports your decision.
if ( winner )
{
// Pick the one winning fruit.
this->slotOne = this->slotTwo = this->slotThree = rand() % 6 + 1;
}
else
{
// Pick a failing combo.
do
{
this->slotOne = rand() % 6 + 1;
this->slotTwo = rand() % 6 + 1;
this->slotThree = rand() % 6 + 1;
} while ( slotOne == slotTwo && slotTwo == slotThree );
}
You can now toy with the player's emotions like the Vegas best.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am new to c++. The problem consists in minimizing the number of coins required to give the exact change I have 25 10 5 and 1 cent coins.
For example if a customer is owed $3.20 the number of coins to give would be 14 (12 of 25 and 2 of 10).
My problem:
A number like 4.20 says you need 22 coins instead of 18. I know the problem is generated when it multiplies change by 100. I get 419 instead of 420.
Here is my code.
int coins = change * 100;
//How many 25 cent coins you need
if (coins >= 25)
{
quarter = coins / 25;
coins = coins % 25;
}
//How many 10 cent coins you need
if (coins >= 10)
{
dimes = coins / 10;
coins = coins % 10;
}
//How many 5 cent coins you need
if (coins >= 5)
{
nickels = coins / 5;
coins = coins % 5;
}
//How many 1 cent coins you need
if (coins >= 1)
{
pennies = coins / 1;
coins = coins % 1;
}
NumCoins = quarter + dimes + nickels + pennies;
printf("%d \n", NumCoins);
Thanks for your help.
#include<iostream>
using namespace std;
int main()
{
int amount = 420;
int coins[] = { 25, 10, 5, 1 };
int ncoins = 0;
for( int i=0 ; i<sizeof(coins)/sizeof(int) ; ++i )
{
ncoins += amount / coins[i];
amount %= coins[i];
}
cout << "You need " << ncoins << " coin(s)." << endl;
}
You need 18 coin(s).
It is easy to track which specific coins are needed in the for loop. I assume the reader can adjust the code as needed to suit their purposes.
From my understanding of the problem my suggestion on how to do this is essentially having two variables. change (This is the change you have in cents.) as well as coins (This is the total number of coins you need to make change.)
Then once you have the change, you keep subtracting the quarters (that is 25), from the change variable until it is less than 25, then you move onto dimes, nickels and finally pennies. At the same time you decrement the change variable, you increment the coins in order to keep track of the minimum number of coins you need. This should be much cleaner and simpler than keeping track of all these other variables.
Some pseudocode could look like this:
declare variables
do loop of change > 25
change = change - 25
coins = coins + 1
do loop of change > 10
...
(keep doing this for dimes, nickels and pennies)
...
display number of coins needed.