Challenge with the inverse of time [closed] - c++

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm assigned with creating the inverse of a program I wrote a program that gave me the total number of seconds
when I put in the hour minutes and seconds
(ex) 1hr28m42s=5322seconds
-now I need to make it so that when i put in the seconds it
tells me the time, (ex)9999seconds=2h46m39s
I've tried to google the inverse of numbers, but alot of results
just come up with the inverse of points or matrixes, i tried searching
on stackoverflow with the tag inverse but i dont know if im doing it right
if you guys have seen this question asked already im sorry and please
redirect me!
So far i only assigned variables for second coversion and not minutes and hours
but even that is no good, i could post my other code for my first ask converting
time into seconds if anything
How do I cap off an integer at a certain point so that it resets after?
(example) if x goes over 60 it goes back to 1? thanks guys
code so far:
//Assigned variables to distinguish time
int second = 1;
int minute = second + 59;
int hour = minute * 60;
int x; // x tells you the time
//Enters the seconds for conversion
System.out.println ("Enter the seconds to be converted: ");
second = scan.nextInt();
//This print tells you the above information in terms
//of total seconds capping off at 60
x = second + (second /60) + (second/60/60);
System.out.println ("The total time in seconds is " +x);

You want to approach it differently (at least using most programming languages).
You already know that going from 2 hours, 12 minutes and 5 seconds you take the number of seconds in 2 hours, add the number of seconds in 12 minutes and then add the last 5 seconds.
For the other way around you do it this way.
You start with 7925 seconds.
Check how many whole hours fits in this interval (2 hours).
Calculate how many seconds remains (725).
From the remaining seconds, check how many whole minutes fit in this interval (12).
Calculate the number of remaining seconds (5).
Now you are done and have 2 hours, 12 minutes and 5 seconds.

Related

Why is my formula for converting minutes in to days hours and minutes returning incorrect results and how can I fix? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am new to programming and cannot figure out why my program is returning the wrong answer. We are supposed to convert a given amount of minutes (in this case 1540) into days hours and minutes. The correct output should be 1 day 1 hour and 20 minutes but I am getting 40 minutes instead while everything else is correct. This also doesn't happen with all inputted minutes, for some problems it also returns the correct answer which confuses me more. The problem is clearly the formula I am using but I don't understand why it returns 40 minutes instead of 20 in this given example. I left out everything but the formula and the number of minutes that I need to be converted.
int totalTime = 1540;
daysWatched = totalTime / minutesInDay; //1440 minutes in a day
totalTime %= minutesInDay;
hoursWatched = totalTime / minutesInHour; //60 minutes in an hour
totalTime %= minutesInHour;
minutesWatched = totalTime;
The correct output is 1 day 1 hour and 40 min. First, when you divide 1540/1440 you will get 1, and then when you use 1540%1440 you will get 100 which is 60min=1 hour and 40 min left that's why the output is 40, not 20 if you think that the output should be 1 day 1 hour and 20 min then your totalTime=1520, not 1540.

number of seconds since start of week?

I've been trying out Howard's date library. There are many examples for getting the number of seconds since midnight of a certain day, but not since the start of week to which the day belongs. Following the examples I produced this code:
using timepoint_t = std::chrono::time_point<
std::chrono::system_clock,
std::chrono::nanoseconds
>;
timepoint_t tp; // input
auto dp = std::chrono::floor<date::weeks>(tp); // output, should point to start of week?
But the results are wrong. For example, tp:
2018-10-25T11:26:00.397836134Z
will produce dp:
2018-10-25T00:00:00.000000000Z
which is midnight of the 25th, not midnight of the 21th. What is the most direct way to produce the correct output?
I've upvoted user1095108's self answer as it gets the correct answer. But I wanted to add more information that wouldn't all fit in a comment.
The "start of the week" is not universally agreed upon. Some countries obverse Monday as the start of the week, as does the ISO standard. And other countries observe Sunday as the start of the week. This library tries to stay as neutral as possible on this issue.
Even once you nail down which weekday you're aiming for, you also need to nail down where on the planet you want to consider when finding the second the week starts.
Judging from your code, I'm going to assume:
The week starts on Sunday.
We want to find the start of the week according to UTC.
For the following code, assume:
using namespace date;
using namespace std::chrono;
just to keep things from getting overly verbose.
The first thing I would do is transform the input into a time_point with a precision of seconds:
auto tp = floor<seconds>(system_clock::now());
Then, in order to do weekday computations, such as finding the weekday of the input tp, one is going to need another time_point with a precision of days:
auto dp = floor<days>(tp);
You can construct a weekday directly from a day-precision time_point (dp), instead of going through the more expensive computation of forming a year_month_weekday:
weekday{dp}
then (as you show) subtract off the number of days since the start of the week:
dp -= weekday{dp} - Sunday;
Now you have two time_points: Your input, and the start of the week. You can simply subtract them to get the number of seconds into the week:
std::cout << tp - dp << '\n';
Now the reason that floor<weeks>(tp) doesn't give you the desired result is that system_clock is Unix Time. This measure counts time since 1970-01-01 00:00:00 UTC (neglecting leap seconds). And 1970-01-01 was a Thursday. So truncating a system_clock::time_point to a precision of weeks defines the "start of the week" as Thursday.
For even more fun, compute the number of seconds since the start of the week in a local time, which may involve daylight savings adjustments. In this case the computation has more than one right answer: Do you count physical seconds, which makes some weeks not have exactly 604800s, or do you count "calendrical seconds"? For example is Nov/4/2018 1:00 EST (America/New_York) 1 or 2 hours into the week? Once you decide which is the right answer, this library can compute it.
Most of Howard's calendar calculations seem to be based off of date:days. So you're out of luck with date::weeks, it seems. One possible answer is:
auto dp(std::chrono::floor<date::days>(tp));
dp -= date::year_month_weekday(dp).weekday() - date::Sunday;
The number of seconds is then obtained as the customary std::chrono::duration_cast<std::chrono::seconds>(tp - dp).count(). Could it be the lack of support for date::weeks in std::chrono, that the date::weeks cast does not work? Howard's date::floor() gives the same output as std::chrono::floor() though.

growth rate calculation with a loop

So I was asked to solve this problem which I don't fully understand that's why I have difficulties starting with it since I'm still a beginner. here it is :
There are approximately 2.5 billion people on the Internet as of
January 2013. Facebook reached one billion users in October of 2012. In this exercise, you’ll
write a program to determine when Facebook will reach 2.5 billion people if it were to grow at
fixed monthly percentage rates of 2%, 3%, 4% or 5%.
As u see I should compute 4 times with different rate and I should each time using a for loop , get month and year when it reach 2.5 billion user . I was given this hint from another exercise to use inside the for loop but I didnt understand how to use it .
amount = pow ( 1.0 * rate , year )
now let say u fixed the border of loop for ( int i = 1000000000 ; i <= 2500000000 ; here if I put ++i its not logical ! )
then inside the loop its easier I think I'm going to count month let say we start at 10 ( which is October 2012 ) if we reach 25 that mean 10 + 15 which mean the date will be January 2014 but the prob is on how to make a cout statement to the user of those information u see? can u help me get the right structure ? thanks
This can be solved via using a while loop (instead of a for loop), like so:
#include <iostream>
double GrowthRatio = 1.05d; // Using 5% growth in this example.
double nUsers = 1000000000;
int MonthsElapsed = 0;
while((nUsers *= GrowthRatio) < 2500000000)
MonthsElapsed++;
std::cout << MonthsElapsed;
Output:
18
Which means it took Facebook 18 months (from October 2012) to reach 2.5 billion users.

Shortest path without Dijkstra's [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need some ideas (not solutions) on how to go about solving the following problem.
So there's a guy who need to get to the phones on the top right hand corner of the building. It is guaranteed they will be at that location. We have to find the shortest path he can take to get there. See the image for an example.
The first thing that came to mind was using Dijkstra's algorithm. However, I have been told that it is unnecessary and that there are simpler alternatives.
On another note, if it is a last resort option, I wouldn't mind using Dijkstra's algorithm if someone can guide me through it. I have not much prior knowledge of graph theory, although I'm competent in the language I use (C++).
Explanation:
He takes the escalator from the left side of the ground floor to the right side of the first floor (14 seconds);
He sprints across the first floor from the right side to the left (5 seconds);
He takes the escalator from the left side of the first floor to the right side of the second floor (13 seconds);
He takes the escalator from the right side of the second floor to the left side of the top floor (11 seconds);
He runs from the left side to the right side of the top floor (5 seconds) to claim the phone!
The total time from the front doors to the sales desk is 14+5+13+11+5=48 seconds.
The input will be specified in the following format:
Each line will each contain three integers l f r separated by single spaces, where l represents the number of seconds required to travel from the left-hand side of the current floor to the right-hand side of the floor above, f the number of seconds to run from one side of the floor to the other, and r the number of seconds to travel from the right-hand side of the floor to the left-hand side of the floor above.
Example input:
14 10 15
13 5 22
13 7 11
5
This is a DP question.
f[n][left] = min{f[n-1][left] + time[go_from_left_to_right_on_floor_n-1] + time[escalator_from_right_side_up],
f[n-1][right] + time[escalator_from_right_side_up]}
f[n][right] = min{f[n-1][right] + time[go_from_right_to_left_on_floor_n-1] + time[escalator_from_left_side_up],
f[n-1][left] + time[escalator_from_left_side_up]}
If you want to go to third floor, left side, you can either start from the second floor, left side, go to right side, and take the escalator; or start from the second floor, right side, take the escalator. Choose the way that you use the minimum of time, and keep doing this use a loop(or recursion :) )
The solution should be O(n)
If the problem stays as small as the one you posted, I guess choyukchow's answer will work.
But if the problem gets considerably big, you may want to use heuristics. Example here.

Trouble calculating correct decimal digits

I am trying to create a program that will do some simple calculations, but am having trouble with the program not doing the correct math, or placing the decimal correctly, or something. Some other people I asked cannot figure it out either.
Here is the code: http://pastie.org/887352
When you enter the following data:
Weekly Wage: 500
Raise: 3
Years Employed: 8
It outputs the following data:
Year Annual Salary
1 $26000.00
2 $26780.00
3 $27560.00
4 $28340.00
5 $29120.00
6 $29900.00
7 $30680.00
8 $31460.00
And it should be outputting:
Year Annual Salary
1 $26000.00
2 $26780.00
3 $27583.40
4 $28410.90
5 $29263.23
6 $30141.13
7 $31045.36
8 $31976.72
Here is the full description of the task:
8.17 ( Pay Raise Calculator Application) Develop an application that computes the amount of money an employee makes each year over a user- specified number of years. Assume the employee receives a pay raise once every year. The user specifies in the application the initial weekly salary, the amount of the raise (in percent per year) and the number of years for which the amounts earned will be calculated. The application should run as shown in Fig. 8.22. in your text. (fig 8.22 is the output i posted above as what my program should be posting)
Opening the template source code file. Open the PayRaise.cpp file in your text editor or IDE.
Defining variables and prompting the user for input. To store the raise percentage and years of employment that the user inputs, define int variables rate and years, in main after line 12. Also define double variable wage to store the user’s annual wage. Then, insert statements that prompt the user for the raise percentage, years of employment and starting weekly wage. Store the values typed at the keyboard in the rate, years and wage variables, respectively. To find the annual wage, multiply the new wage by 52 (the number of weeks per year) and store the result in wage.
Displaying a table header and formatting output. Use the left and setw stream manipulators to display a table header as shown in Fig. 8.22 in your text. The first column should be six characters wide. Then use the fixed and setprecision stream manipulators to format floating- point values with two positions to the left of the decimal point.
Writing a for statement header. Insert a for statement. Before the first semicolon in the for statement header, define and initialize the variable counter to 1. Before the second semicolon, enter a loop- continuation condition that will cause the for statement to loop until counter has reached the number of years entered. After the second semicolon, enter the increment of counter so that the for statement executes once for each number of years.
Calculating the pay raise. In the body of the for statement, display the value of counter in the first column and the value of wage in the second column. Then calculate the new weekly wage for the following year, and store the resulting value in the wage variable. To do this, add 1 to the percentage increase (be sure to divide the percentage by 100.0 ) and multiply the result by the current value in wage.
Save, compile and run the application. Input a raise percentage and a number of years for the wage increase. View the results to ensure that the correct years are displayed and that the future wage results are correct.
Close the Command Prompt window.
We can not figure it out! Any help would be greatly appreciated, thanks!
Do not store money as floating point. This will end only in tears. Store money as an integral number of cents.
The reason for this is that floating point math on a computer is necessarily inexact. You know that 0.40 / 2 = 0.20, but it's entirely possible that the computer will say it is 0.19999999999999, and that is not an error. The internal representation of floating point numbers makes it impossible for a computer to exactly represent some fractions, much like you cannot write out an exact decimal representation of 1/3 (without an infinite amount of paper).
When you are dealing with numbers that have fractional parts and for which inexactness is not acceptable (e.g. money), you must compute using fixed-point math. In general, you might use a fixed point library, but for an assignment like this, if you're not allowed to do so, an int that stores a number of pennies will do just fine, so long as you understand how integer division works. You will have to write more math code and account for the rounding yourself, though. But that's what you want. You want absolute control over rounding.
I changed your for loop to this:
cout << (i+1) << " $" << wage*52 << "\n";
wage = wage * (1+(raise/100.0));
And it did worked!. I see you didn't understand the language of the problem.
I think that the intention is to receive a 3% raise each year, but you are actually only adding 3% of the starting salary ($780 in this case) each year. You may want to explore modifying the wage value on each pass in the loop (I won't present a solution as I suspect that this is a homework problem, yes?).
The best way to catch this sort of problem is to run it in a debugger and step through each line looking for when the results don't match your expectations. It's usually pretty easy at that point to figure out where your logic went astray.
Your problem is that your program ignores compounding. You are calculating the dollar value of the raise once, and using that for each increase. Once you get your first raise, the value of your second raise needs to be calculated based on your new wage, not your original wage.