Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I saw a problem where we had to find the wage. If the hours are less than 40 we pay regular wage ($100/hr) if there is overtime we give 1.5 times the original pay ($150/hr).
The challenge was to solve it without if-else/loops/or ternary operations.
It was solved like this
int hours = /*some_number*/;
int wage = (100*hours) + (50*(hours-40))*(hours>40);
This code works.
(hours>40) returns 1 if hours is greater than 40 and returns 0 if it is less.
I understand that it is some kind of boolean operation, but how does it work and what is this called exactly.
The right way to do it is straight-forward:
int hours = /*some_number*/;
int wage = 100*hours;
if (hours > 40) wage += 50 * (hours-40);
To squeeze it to a single expression, the example takes advantage of the fact that a boolean is either 1 or 0. So x*some_bool evaluates to either x or 0.
In your case, if (hours > 40) then
(50*(hours-40))*(hours>40) == (50*(hours-40)) * 1 == 50*(hours-40)
otherwise it is 0.
(50*(hours-40))*(hours>40) == (50*(hours-40)) * 0 == 0
In general it is less readable to write code this way. The only valid uses IMO are in advanced algebraic transformations used in cryptography or complexity theory.
Well you basically answered your question. The (hours > 40) returns 1 if hours is greater than 40 and returns 0 otherwise.
Maybe more tricky part is the fact that this boolean result is then converted to int implicitly before being multiplied by overtime payment, but that is out of the scope of the question.
So the whole code could be indeed expanded in this way
int hours = /* something */
int wage = 0;
int overtime = hours - 40;
if (hours > 40) {
wage = 100*hours + 50*overtime;
}
else {
wage = 100*hours
}
Related
I have a start date and an end date. I need to find the difference between these dates and group it under the following categories.
< 1 year, < 2 year and so on till X years.
I'm trying to write a unix C++ program for this problem.
I can easily find the unix time difference between start and end date and compare with the 1 year's time stamp (12 * 30 * 20 * 60 * 60) and so on.
Is there any C++ function that returns the difference in years given the start and end date? Also let's say, the difference is 8 years, I suppose I have to write conditions like this,
if((end_date - start_date) < 12 * 30 * 24 * 60 * 60)
group = " less than 1 year"
...
...
Until what point do I stop at, as I won't know what the maximum difference is between the dates?
Is there any easy way to compute this?
I know i'm confusing here, but i ve put all my efforts to explain the problem here. Thanks in advance.
Also note, this is not a assignment or anything.
Assuming "precise years" (in other words, all years are 365 days long) is not an issue, I would do something like this (counting the number of times each year happens in this case - since the original question doesn't really say WHAT to do with each year)
const int MAX_YEARS = 10;
const int YEAR_IN_SECONDS = 365 * 24 * 60 * 60;
std::array<int, MAX_YEARS+1> bins;
int years = static_cast<int>(difftime(end_date - start_date) / YEAR_IN_SECONDS);
// Outside of range, put it at the end of range...
// We could discard or do something else in this case.
if (years > MAX_YEARS)
{
years = MAX_YEARS;
}
bins[years]++; // Seen one more of "this year".
Obviously, what you do with "bins", and what/how you store data there really depends on what you actually are trying to achieve.
An alternative solution would be to use const double YEAR_IN_SECONDS = 365.25 * 24 * 60 * 60;, which would slightly better cover for leap-years. If you want to be precise about it, you'd have to find out if you are before or after each of the leapday in a particular year that is divisible by 4 (and keep in mind that there are special cases for years divisible by 100 and other rules at 400).
#include <chrono>
using years = std::chrono::duration<std::chrono::system_clock::rep, std::ratio<365 * 24 * 60 * 60, 1>>;
std::chrono::system_clock::time_point end_date = std::chrono::system_clock::now();
std::chrono::system_clock::time_point start_date = end_date - years(2);
years how_many = std::chrono::duration_cast<years>(end_date - start_date);
int how_many_as_int = how_many.count();
std::cout << how_many_as_int << std::endl;
std::unordered_map<int, std::list<whatever>> m;
m[how_many_as_int].push_back(...);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm very new to c++. I need help on how to:
get percentiles (which I think I'm doing right..?, and
how to add them to another number.
Here is part of my code, I'm not even sure if I'm including the right headers. Thanks.
#include <iostream>
#include <iomanip>
int main() {
double total, tipTotal, taxTotal, cost, tax, tip;
cost = 44, 50;
tax = 100 - 93.25;
tip = 100 - 85;
total = cost + tax + tip;
tipTotal = cost + tax + tip;
taxTotal = cost + tax;
// other code
return 0;
}
First, I think you have a typo.
I think you meant to say 44.50 (with a decimal point).
cost = 44.50;
Because the comma is a valid operator, the compiler does not catch this as an error.
Second, C++ does not handle percentages, so you have to specify percentages as a decimal value.
So 15% is not 15.0 but 0.15.
So your code should say
tax = 1.00 - 0.9325;
tip = 1.00 - 0.85;
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
inline int input()
{
int c;
int n = 0;
while ((c = getchar_unlocked()) >= '0' && c <= '9')
{
// n = 10 * n + (c - '0');
n = (n << 3) + ( n << 1 ) + c - '0';
}
return n;
}
Can someone explain how this way of inputting the number is working and how it is the fast way to input a number?
Compilers are generally very stupid, and have no understanding of the logic you're trying to implement. Moreover, they're often written by less-than-competent people who don't understand much of modern hardware.
The author of the code has realized this, and cleverly analyzed that 10 is the same as 8 + 2, and that 8 and 2 are both powers of two. For the flourish, he proceeded to turn the mathematics of exponentials into native, bitwise hardware instructions. This combination of mathematics and deep understanding of the hardware leads him to factor 10 * x as 8 * x + 2 * x and express the result in terms of instructions that are far more optimal than the naive "stupid multiplication" that would otherwise have taken place. Naturally, such optimizations are far beyond the reach of any kind of technology and cannot possibly be performed automatically.
The result is a vastly improved method of multiplying a number by ten.
Patent pending.
n << 3 equals n * 8
n << 1 equals n * 2
i.e. (n << 3) + ( n << 1 ) equals 10 * n
bitwise shift is faster than multiplication, though I'm not sure the whole thing should be faster.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I know you're supposed to post code of what you have started when asking questions, but honestly I am completely lost. I am reading a book on C++ to learn (I'm self taught), the book is Sams C++ Primer Plus. I have recently just finished the chapter on type conversions and type casts. Well, I was interested in trying to make the program that converts seconds to days/minutes/seconds. It's a very simple application. I could code the application perfectly, but for some reason the math stumps me. I need help with this, or at least starting the variables and such. Thanks.
Also, I'm sure I am supposed to use the modulo (in C++ modulus) somewhere within the program.
The output of the program is supposed to be similar to this:
"Enter the number of seconds: SECONDS"
"SECONDS seconds = 364 days, 46 minutes, 40 seconds.
The actual values in the output don't matter as long as the conversion is correct.
const int SECSPERDAY=84600;
const int SECSPERHOUR=3600;
const int SECSPERMIN=60;
int days=SECONDS/SECSPERDAY;
int hours=(SECONDS-(days*SECSPERDAY))/SECSPERHOUR;
int mins=(SECONDS-(days*SECSPERDAY)-(hours*SECSPERHOUR))/SECSPERMIN;
int secs=SECONDS%SECSPERMIN;
As your task is connected to type conversions and -casts I would suggest the learning outcome is that dividing with integers drops the remainder and you can get the remainder by modulu operation.
therefor you can use (given SECONDS is the input)
int sec = SECONDS % 60;
int min = (SECONDS / 60) % 60;
int hours = (SECONDS / (60 * 60)) % 24;
int days = (SECONDS / (60 * 60 * 24) % 365;
int years = (SECONDS / (60 * 60 * 24 * 365);
I did not use constants to show the direct depedencies even if this is considered bad practice.
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I'm coding a program to calculate the growth of a bacterial colony until certain point.
Given a "X", that will represent the initial number of bacteria. And given a "Y", that will represent the number limit desired of bacteria in the bacterial colony. Return the number of days and hours that the bacterial colony needs for reaching the limit.
The bacterial colony doubles each hour.
Example.1:
Input: 1, 8
Output: 0, 3
Example.2:
Input: 1000 , 1024000
Output:0, 10
Example.3:
Input: 123, 3453546624536
Output: 1, 10
If the hour calculated returns a fractional number, it must be rounded down.
So far I have written this code:
#include <iostream>
using namespace std;
int main(){
long int binitial, blimit, day, counter=0;
float hour;
cin >> binitial;
cin >> blimit;
while(binitial <= blimit){
binitial = binitial * 2;
counter++;
}
day = counter / 24;
cout << day << " ";
hour = (counter % 24) - 0.5;
cout << (int)hour;
return 0;
}
You can remove the loop by observing that the number of hours is Log2(Y/X). To calculate Log2(A) using the standard functions, calculate log(A)/log(2).
You may need to address precision issues when going from doubles to ints, because the calculations will be approximate. The final expression for the hours may look like this:
int hours = (log(Y/X) / log(2)) + 1E-8; // Add a small delta
Going from hours to days/hours is very simple, too:
cout << hours/24 << " " << hours % 24 << endl;
You can use a long int for hour if you do the following:
hour = counter - (day*24); // The total number of hours minus the number of hours that are in each day.
I don't have a compiler in front of me but you can probably also do something like this:
hour = counter % 24; // this will return the remainder when counter is divided by 24.
If blimit is always a multiple of binitial, the solution is simple:
counter%24 will be always an integer, so you don't have to round it.
In case of day days and hour hours, you only have to do is:
hour = counter%24
A note on the method of calculation: you don't need to iterate if you're only doubling each time. You're just looking for a value of n such that 2n gives the right result.
So, note that ngenerations = log2 blimit - log2 binitial
Once you have the number of generations (as a floating-point number) you can just truncate that to an integer number of hours.