I was given a problem. In the problem I am suppose to take input current month, current year and current water level of a dam from user. There is a scale that from month march to august the water level increase by 150 feet each month and from sep to feb it decreases by 200 feet. Now I am supposed to tell in which month and year the Dam will have no water or 0 feet water level. I have made the below program using loops but I have to it with out loops/recursive function. I got the year by dividing the water level with avg_decrease in water level.You cans see the program that does what I want with loop.
#include<iostream>
using namespace std;
int main(){
int c_month, c_year, wlevel, avg_decrease;
cout<<"Enter current month number: ";
cin>>c_month;
cout<<"Enter current water level: ";
cin>>wlevel;
cout<<"Enter current year: ";
cin>>c_year;
avg_decrease = 300; //-25 each month, -300 each year
cout<<wlevel/avg_decrease<<endl;
int m = c_month, level = wlevel, y = c_year;
while(true){
if(x)
break;
for(int i =0;i<=12;i++){
if(level < 0){
x = true;
break;
}
else if(m >= 3 && m<=8){
level = level +150;
m++;
}
else{
level = level -200;
if(m == 12)
m=1;
else
m++;
}
}
y++;
}
cout<<y<<"\t"<<m<<endl;
}
I want to get the month and year in which the water level is 0 feet which is being printed in the last line without using the loops. I dont know how to implement the above program without using loops. If any one can help, it would be great.
Thanks in advance
test this and change code if my logic is wrong
#include<iostream>
using namespace std;
int main(){
int m, y, lev;
cout << "Enter current month number: ";
cin >> m;
cout << "Enter current year: ";
cin >> y;
cout << "Enter current water level: ";
cin >> lev;
int avg_year = 300; // average year decrease
int year_count = lev/avg_year; // how many entire years we will be decreasing for sure
lev = lev % avg_year; // how much level we still have after entire years have pass
if ((lev > 0) && (m <= 8) && (m >=2)) // march - aug we are adding +150 each month
{
int delta = (6 - m + 2); // how much times we should add +150
lev = lev + 150*delta;
m = m + delta;
}
if((lev > 0) && (m == 8)) // end of aug (sep = -200)
{
m++;
lev = lev - 200;
}
if((lev > 0) && (m == 9)) // end of sep (oct = -200)
{
m++;
lev = lev - 200;
}
if((lev > 0) && (m == 10)) // end of oct (nov = -200)
{
m++;
lev = lev - 200;
}
if((lev > 0) && (m == 11)) // end of nov (dec = -200)
{
m++;
lev = lev - 200;
}
if((lev > 0) && (m == 12)) // end of dec (jan = -200)
{
m = 1;
year_count++;
lev = lev - 200;
}
/*
in case at the beginning of the program m== 1 AND Level == (801 - 899)
2 years past and we are at m == 1 with level == (201 - 299)
februarry gives -200. So at the end of m==2, level == (1 - 99)
when we do march-december we gain +100 level
so in the beginning of the next year jan level will be 101-199
and since jan takes -200 from level. It is definitely next years jan
so we are just increasing year count
*/
if((lev > 0) && (m == 1)) // enf of jan (feb = -200)
{
lev = lev - 200;
if(lev <= 0)
m++;
else
year_count++;
}
cout << (y + year_count) << "\t" << m << endl;
}
UPD
this is bellow I think the right solution as I would do it with all the loops. I doubt it can be achieved just by plain code with no loops or recursion
#include<iostream>
using namespace std;
int level_func(int m, int y, int lev)
{
int ar[] = { -200, -200, 150, 150, 150, 150, 150, 150, -200, -200, -200, -200 };
int m_count = 0;
while (lev > 0)
{
m++;
m_count++;
if (m > 12)
m = 1;
lev = lev + ar[m - 1];
}
return m_count;
}
int main() {
int m, y, lev;
cout << "Enter current month number: ";
cin >> m;
cout << "Enter current year: ";
cin >> y;
cout << "Enter current water level: ";
cin >> lev;
int month_count = level_func(m, y, lev);
y = y + month_count / 12;
m = m + month_count % 12;
if (m > 12)
{
y++;
m = m - 12;
}
cout << y << "\t" << m << endl;
}
I worked on the solution myself and found a very efficient way to do it. I calculated total months required and got the total years from the month.The code is below
#include<iostream>
using namespace std;
int main(){
int exact_months,year = 0;
int c_month, c_year, wlevel, avg_decrease;
cout<<"Enter current month number: ";
cin>>c_month;
cout<<"Enter current water level: ";
cin>>wlevel;
cout<<"Enter current year: ";
cin>>c_year;
int mn;
exact_months = wlevel/25;
mn = (c_month+exact_months)%12;
if ((c_month+exact_months)%12 !=0 && c_month != 1)
year = 1;
year = exact_months/12+year;
cout<<"Date: "<<year+c_year<<":"<<mn;
}
Related
I have this program, which should give me the smallest original price of the item based on the input from the user.
There are some conditions, for example, if the quantity of the mask is more than 9 the price will be discounted by 10%, 15% if its more than 30 and 20% if it's more than 50. The result should give the answer Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int mprice; //price input
int mquantity; //quantity input
int n; //first input
int fee = 2000; //const fee
float finalprice;
float maskCalc(int price, int quantity) {
float holder = (float)(price - fee) / (float)(quantity);
if (quantity > 0) {
finalprice = holder;
}
//if between 10 and 30
else if (quantity > 9) {
finalprice = holder / 0.9;
}
//between 30 and 49
else if (quantity > 30) {
finalprice = holder / 0.85;
}
//more than 50
else if (quantity > 49) {
finalprice = holder / 0.8;
}
//less than ten
else {
finalprice = holder;
}
return finalprice;
}
int main()
{
cin >> n;
float arr[n];
// Input oruulah loop
for (int i = 0; i < n; i++) {
cin >> mprice >> mquantity;
x = maskCalc(mprice, mquantity);
arr[i] = x;
}
for (int i = 1; i < n; i++) {
if (arr[0] > arr[i]) {
arr[0] = arr[i];
}
}
printf("%.2f", arr[0]);
return 0;
}
I gave the input
3
5000 3
7000 10
3000 1
the answer was 555.56 which is correct, but when I give something like
3
2500 1
7000 10
3000 1
it is giving me 0.00 while I was expecting this to give me 500.00. Any help will be appreciated.
You need to check for the highest quantity first in your if-else switch, otherwise you always fall into the default (<10) case.
//more than 50
if (quantity >= 50) {
finalprice = holder / 0.8;
}
//between 30 and 49
else if (quantity >= 30) {
finalprice = holder / 0.85;
}
//if between 10 and 30
else if (quantity >= 10) {
finalprice = holder / 0.9;
}
//less than ten
else {
finalprice = holder;
}
This is what I have so far but I am not getting the right outputs.
#include <iostream>
using namespace std;
int main(void) {
int year_number, month_number, day_number;
cout << "What year were you born in?\n";
cin >> year_number;
cout << "What month were you born in?\n";
cin >> month_number;
cout << "What day were you born on?\n";
cin >> day_number;
month_number -= 2;
if (month_number < 0) {
month_number += 12;
year_number -= 1;
}
month_number *= 83 / 32;
month_number += day_number;
month_number += year_number;
month_number += (year_number / 4);
month_number -= (year_number / 100);
month_number += (year_number / 400);
day_number = month_number % 7;
cout << "The weekday number you were born on is " << day_number << endl;
return 0;
}
Here are the instructions:
Decrease month number by 2;
if month number becomes less than 0, increment it by 12 and decrement year by 1;
take month number and multiply it by 83 and divide it by 32;
add day number to month;
add year number to month;
add year/4 to month;
subtract year/100 from month;
add year/400 to month;
find the remainder of dividing month by 7;
I am not sure where you got those instructions for Zellers congruence. But here is an implementation that follows the formula of wikipedia.
#include <iostream>
#include <math.h>
int main(void) {
std::string days[7] = { "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
int year_number = 2020;
int month_number = 1;
int day_number = 22;
if( month_number < 3 ){
month_number += 12;
year_number -= 1;
}
int century_number = year_number / 100;
year_number = year_number % 100;
int day = day_number + floor( (month_number + 1) * 13.0 / 5.0 ) +
year_number + floor( year_number / 4.0 ) +
floor( century_number / 4.0 ) -
2 * century_number;
day = day % 7;
std::cout << "The weekday you were born on is " << days[day] << std::endl;
return 0;
}
Live Demo
Another of your problems is probably that you don't floor your intermediate results where you should.
I'm practicing C++ solving some exercises, but after the whole day, I couldn't solve on of them. Here's the exercise:
There are 100 hay and 100 cows divided into 3 groups.
-Group A: 1 cow needs 5 hay to be full
-Group B: 1 cow needs 3 hay to be full
-Group C: 3 cow needs 1 hay to be full
Calculate the number of cows in each group.
If all of them eat at the same time at the same speed then the code is not very hard.
#include <iostream>
using namespace std;
int main()
{
int a, b, c;
for (a = 1; a <= 20; a++)
{
for (b = 1; b <= 32; b++)
{
c = 3 * (100 - 5 * c - 3 * c);
if ((a + b + c == 100))
cout << "Group A " << a << ", group B " << b << ", group c " << c << endl;
}
}
}
However since they eat at different speeds and some groups may start eating slower than others, some of them won't get full before the hay runs out. Input can be the time begin to eat of each group (BeginA, BeginB, BeginC) (Eg: 0mins, 10mins, 5mins) and the speed of each group (SpeedA, SpeedB, SpeedC) (measure in minutes per hay). And there are at least 2 groups are full. How can you find the numbers of cows in each group?
Edit: I have set up a test case:
BeginA=0, BeginB=10, BeginC=15
SpeedA=5, SpeedB=5, SpeedC=10
After 5 mins, x hay have been eaten.
10 mins, 2x hay have been eaten (100-2x hay).
15 mins, 2x + y hay have been eaten.
20 mins, 3x + 2y hay have been eaten.
Repeat until 2 groups are full
5x+3y+2/3z hay have been eaten
Then I stucked here: If x+y+z=100 and the hay have been eaten=100 then we have the answer.
Edit 2: Welp, still going nowhere, stuck in an infinite loop:
#include <iostream>
using namespace std;
int numCow(int a,int b,int c) {
int x=0, y=0, z=0;
for (x = 1; x < 100; x++)
{
for (y = 1; y < 100; y++)
{
for (z = 1; z < 100; z++)
if ((x + y + z == 100) && (a * x + b * y + c * z == 300))
cout << "Group A " << x << ", Group B " << y << ", Group C " << z << endl;
}
}
return 0;
}
int main()
{
int x, y, z, a=0, b=0, c=0, counter;
int Sx = 0, Sy = 0, Sz = 0, Bx, By, Bz;
x = 0; y = 0; z = 0;
counter = 0;
cout << "Begin time (s): ";
cin >> Bx >> By >> Bz;
cout << "Speed: ";
cin >> Sx >> Sy >> Sz;
Bx += Sx;
By += Sy;
Bz += Sz;
while (true) {
if (a!=15)
if (Bx == counter)
{
a++;
Bx += Sx;
}
if (b != 9)
if (By == counter)
{
b++;
By += Sy;
}
if (c!=3)
if (Bz == counter)
{
c++;
Bz += Sz;
}
if (a == 15 && b == 9) {
numCow(a, b, c);
break;
}
if (a == 15 && c == 3) {
numCow(a, b, c);
break;
}
if (c == 3 && b == 9) {
numCow(a, b, c);
break;
}
if (a == 15 && b == 9 && c == 3)
{
numCow(a, b, c);
break;
}
counter++;
}
}
This project I'm working on is forcing me to use Visual C++-6.0 and it seems like everytime I compile this code it causes errors in not only this segment of code but elsewhere that is unrelated to this portion.
Right now I am trying to calculate an expiration date that is 15 months from the date that would be given.
I've tried researching if this is a common issue after windows updates. I know 6.0 has been unsupported and phased out but its a "requirement" for this program. I swore it was working 2 months ago and since that point about 30 patches have been deployed to my Windows 10 device.
Currently in this snippit of code the date that is passed into the code is carried through unaltered. For example: Nov-01-2019 should become Feb-01-2021
void CalculateDates(int numIndex)
{
int tDay = 0, tMonth = 0, tYear = 0, exp_Months = 15;
char sTemp1[4], sTemp2[4], sTemp3[4], sTemp4[4], sDay[4], sYear[4], *p;
p = Database[numIndexCount].sIdentifier;
strncpy(Database[numIndexCount].sPreparedBy, Database[numIndexCount].sIdentifier, 3);
Database[numIndexCount].sPreparedBy[3] = 0;
strncpy(sTemp1, p + 3, 2);
sTemp1[2] = 0;
strncpy(sTemp2, p + 5, 2);
sTemp2[2] = 0;
strncpy(sTemp3, p + 7, 2);
sTemp3[2] = 0;
strcpy(sTemp4, "20");
SetDateMonth(sTemp1);
sprintf(Database[numIndex].sPreparedDate, "%s-%s-%s%s", sTemp2, sMonth1, sTemp4, sTemp3);
tDay = atoi(sTemp2);
tMonth = atoi(sTemp1);
tYear = atoi(sTemp3);
if (tMonth <= 9) {
if (tMonth == 9) {
tMonth = 12;
tYear++;
// cout << "Is the month printing right? ";
// cout<<tMonth;
// cout << "\n";
}
else {
tMonth = (tMonth + exp_Months) % 12;
tYear++;
//cout << "Is the month printing right? ";
//cout<<tMonth;
//cout << "\n";
}
}
if (tMonth == 4 || tMonth == 6 || tMonth == 9 || tMonth == 11) {
// cout << "This is reached";
// cout << "\n";
// cout << "The day value is: ";
// cout << tDay;
// cout << "\n";
if (tDay == 31)
{
tDay = 30;
}
}
if (tDay >= 29 && tMonth == 2 && tYear % 4 == 0) {
if (tYear % 100 != 0) {
tDay = 29;
}
else if (tYear % 100 == 0 && tYear % 400 == 0) {
tDay = 29;
}
}
else if (tYear % 4 != 0 && tMonth == 2) {
tDay = 28;
}
sprintf(sTemp1, "%i", tMonth);
if (tDay < 10) sprintf(sDay, "0%i", tDay);
else sprintf(sDay, "%i", tDay);
if (tYear < 10) sprintf(sYear, "0%i", tYear);
else sprintf(sYear, "%i", tYear);
SetDateMonth(sTemp1);
sprintf(Database[numIndex].sUseByDate, "%s-%s-%s%s", sDay, sMonth1, sTemp4, sYear);
sprintf(sUseByDate, "%s-%s-%s%s", sDay, sMonth1, sTemp4, sYear);
}
End results for the above for today were Nov-01-19 but should have been Feb-01-19
I'm trying to implement the Bulls & Cows game and I have a logic problem. I am explicitly checking if each digit is either equal to a digit in the corresponding index (bulls) or at other indexes (cows). The value that I check with (4321) should yield "0 bulls and 4 cows" but it instead gives me "0 bulls and 3 cows.
Here is my code (and I apologize for the code repetition. I am also wondering if anyone has recommendations to make this code smaller):
#include <iostream>
#include <vector>
using namespace std;
int main() {
int guessValue = 1234;
int guess;
int bulls = 0;
int cows = 0;
cout << "Enter a 4 digit guess: ";
cin >> guess;
int firstValue = (guess % 10000) / 1000;
int secondValue = (guess % 1000) / 100;
int thirdValue = (guess % 100) / 10;
int fourthValue = guess % 10;
if (firstValue == ((guessValue % 10000) / 1000)) {bulls += 1;}
else if(firstValue == ((guessValue % 1000) / 100) ||
firstValue == ((guessValue % 100) / 10) ||
firstValue == (guess % 10))
{cows += 1;}
if (secondValue == ((guessValue % 1000) / 100)) {bulls += 1;}
else if (secondValue == ((guessValue % 10000) / 1000) ||
secondValue == ((guessValue % 100) / 10) ||
secondValue == (guess % 10))
{cows += 1;}
if (thirdValue == ((guessValue % 100) / 10)) {bulls += 1;}
else if (thirdValue == ((guessValue % 10000) / 1000) ||
thirdValue == ((guessValue % 1000) / 100) ||
thirdValue == (guess % 10))
{cows += 1;}
if (fourthValue == (guessValue % 10)) {bulls += 1;}
else if (fourthValue == ((guessValue % 10000) / 1000) ||
fourthValue == ((guessValue % 1000) / 100) ||
fourthValue == (guessValue % 100) / 10)
{cows += 1;}
cout << bulls << " bulls and " << cows << " cows" << endl;
}
I am also wondering if anyone has recommendations to make this code smaller
First of all use std::vector to keep separate digits:
std::vector<int> split( int v )
{
std::vector<int> r;
while( v ) {
r.push_back( v % 10 );
v /= 10;
}
return r;
}
Second, use standard algo std::count_if:
auto bulls = std::count_if( guessv.begin(), guessv.end(),
[it = targetv.begin()]( int i ) mutable
{ return i == *it++; } );
auto cows = std::count_if( guessv.begin(), guessv.end(),
[s = std::set<int>{ targetv.begin(), targetv.end() }]( int i )
{ return s.count( i ); } );
second one is actually counts cows and bulls, so it needs to be adjusted:
cows -= bulls;
live example
2 concepts that absolutely you need to master: loops and functions. First create some helpful functions.
These are the functions you could built your program upon:
int get_digit(int number, int order)
with example test cases:
get_digit(7895, 0) == 5
get_digit(7895, 1) == 9
get_digit(7895, 2) == 8
get_digit(7895, 3) == 7
then:
bool has_digit(int number, int digit)
with example test cases:
has_digit(7895, 1) == false
has_digit(7895, 8) == true
has_digit(7895, 5) == true
has_digit(7895, 0) == false
has_digit(7000, 0) == true
then:
bool matches_digit(int a, int b, int order)
with test cases:
matches_digit(1239, 4269, 0) == true
matches_digit(1239, 4269, 1) == false
matches_digit(1239, 4269, 2) == true
matches_digit(1239, 4269, 2) == false
and finally:
int get_cow(int a, int b)
int get_bull(int a, int b)
int main()
This is a top-down design, bottom-up implementation approach. First you think of the big picture and figure out what small pieces you need (functions) and then start implementing from the smallest most independent functions and step by step combine then into higher functions until you reach main.
This is my solution and it works. Basically I had to create a function to extract each digit and store them into a vector that can be applied to both the model and the guess. Then I used the find() method of the <algorithm> library to see if the digits exist in the guess vector and if yes, at which position compared to the model vector. Same position equals 1 bull and different position equals 1 cow. I am going to add more to this program, such as generating the model randomly and looping the program after each round so the user doesn't have to restart the game.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> getDigits(int modelValue) {
vector<int> vectorValue;
int extractedDigit = 0;
int modulant = 10000;
int divisor = 1000;
for (int i = 0; i < 4; i++) {
extractedDigit = (modelValue % modulant) / divisor;
vectorValue.push_back(extractedDigit);
modulant /= 10;
divisor /= 10;
}return vectorValue;
}
int main() {
int model = 1234;
int guess = 0000;
int bulls = 0;
int cows = 0;
int counter = 1;
cout << "Enter a value to guess: ";
cin >> guess;
vector<int> modelVector = getDigits(model);
vector<int> guessVector = getDigits(guess);
for (int i = 0; i < 4; i++) {
if (find(modelVector.begin(), modelVector.end(), guessVector[i]) != modelVector.end()) {
if (modelVector[i] == guessVector[i]) {bulls += 1;}
else { cows += 1; }
}
}cout << "There are " << bulls << " bulls and " << cows << " cows"<< endl;
}