Given absolute value of angle between hour and minute hands.
We need to find all valid values of time (in hours and minutes, both non-negative integers) from midnight (inclusive) to noon (not inclusive) which satisfy the given angle.
It is to be noticed that time value is considered valid if the angle between the clock's hands for that value and the angle given has described differ by less than 1/120 degrees.
Also, the movement of the minute hand influences the hour hand. That is, every minute, it moves by 1/60th of the angular distance between two consecutive hour marks.
So how to solve this problem in good way. I wrote down a code with hell lot of if and else. So just wondering if there is clean way of finding all of them.
Example : If A=30 then it can be :
01:00
11:00
I'll try an idea in pseudocode
for minuteHand in [0,59]:
minuteAngle=angle(minuteHand) // gives the angle respect to the 0
hourAngle1 = minuteAngle+A //Should be modified to account for the precision
hourAngle2 = minuteAngle-A
if isValidTime(minuteAngle,hourAngle1): // check if the two hands express a valid time at this angle
found a valid time
if isValidTime(minuteAngle,hourAngle2):
found a valid time
Problem of currently going on competition in Codechef.
https://www.codechef.com/OCT15/problems/TIMEASR
I do not really understand what is your problem. "How to solve this?" is a bit to vague to give a short answer. However, the first thing I would do is to convert all values to the same units. 30 degrees corresponds to 1/12th of the full circle, ie in one minute one hand moves by 6 degrees (1/60 of a full turn) and the other one by 1/2 degree (30 degrees in a full hour). So you are basically trying to solve
abs( (t * 6) - (t*1/2) ) == 30 + n*360
where n = 0,1,2,.... That modulo part makes it a bit tedious to get a direct solution, but you can simply run a loop for any values of t to find the solutions. Hope this helps. If not, maybe you should consider showing some of your code....
This question shouldn't be answered right now as it's from a LOng contest being hosted by codechef. So , this is spoiling the problem for enthusiasts like us who wants to solve this on our own.
Related
Disclaimer: This is a very very difficult question about mathematics and algorithms (in my opinion) - so respect to anyone who makes this. I admire you.
I would like to evaluate the performance of my employees. I would like to do this by measuring the following parameters as percentages of the amount of time they spend working:
1. % of Time spent working
2. % of Time spent in meetings
3. % of Time spent travelling
I have a "preferred" set of percentages for each of these. This represents the ideal time that I would LIKE my employees to spend their time.
% Time spent in Meetings -> 30%
% Time spent Travelling -> 10%
% Time Spent Working -> 60%
total time spent on activities: 100%
So in words, I would like my employees to spend 30% of their time in meetings, 10% time travelling and 60% on a desk working.
I would ALSO like to add weights to these different percentages. The weight would represent how "lenient" I am with each percentage being different to what I desire. In other words, how important I find it for each variable to be closest to the desired percentages (30, 10, 60). I would like to apply the weights on a scale of.1 to 10, 10 being most important, 1 being least important.
Meetings -> 3
Travelling -> 9
Working -> 5
So given the percentage of time spent by an employee, and the weight of the importance of the time spent being close to the desired time spent, I would like to generate an index between 0 and 100 where 100 is the perfect time percentages and 0 is the worst. So a score of 100 would give the "preferred" percentages:
% Time spent in Meetings -> 30%
% Time spent Travelling -> 10%
% Time Spent Working -> 60%
How I would try to approach this:
Find out what the minimum and maximum ratios are
Calculate a value to tell how far away each value is from the desired value using the minimum and maximum ratios. Make sure this value is in the ratio 0-1 (corresponding to 0-100)
Calculate a weighted average.
I think you're trying something which is kinda like the H-score.
H-score is a scored we use in digital pathology to measure tumor positivity for a maker and it is meant to weight the number of positive cells by their intensity.
It's:
1* (% of positive cells with score 1) + 2*(% of positive cells with score 2) + 3*(% of positive cells with score 3)
You could calculate the same as:
3*(1-% of difference between actual worked hourse and planned ones)
9*(1-% of difference between actual worked hourse and planned ones)
5*(1-% of difference between actual worked hourse and planned ones)
Don't forget to use absolute value when you compute the difference.
I used 1-% so that a difference of 0.8 (as planned 0.ì and worked 0.9) will result in a score of 0.2. This will work for the opposite situation too (planned 0.9 and worked 0.1).
In this way, who perfectly matches the planned hourse will have a score of 1700%.
Then just:
Score/Total weights = score between 0-100%.
I've got the task to calculate the golden ratio (phi = (1+ sqrt(5))/2).
But I need to calculate it with about 50 decimal digits / decimal places and then round the result up to 30 decimal digits and print it on the console. I am allowed to use BigDecimal and MathContext.
Does anyone have an idea how to calculate it? I am lost right now.
Thanks
I won't try to solve your problem for you!
However I think to point you in a promising direction would be to look at the API:
https://docs.oracle.com/javase/9/docs/api/java/math/BigDecimal.html
and specifically at the constructor:
BigDecimal(BigInteger unscaledVal, int scale, MathContext mc)
I believe that if you experiment with these objects you can meet your goal.
Note: sqrt was only added to BigDecimal in Java 9.
Good luck.
I found this on the web. It can be used to verify your calculations.
String goldenRatio =
"1.61803398874989484820458683436563811772030917980576286213544862270526046281890" +
"244970720720418939113748475408807538689175212663386222353693179318006076672635";
You can verify the correctness of a regular calculation by
Verifying the length (don't forget the decimal point and the whole number digits).
verifying that it matches some initial part of the supplied answer.
To calculate normally, I used MathContext of precision = 30 and RoundingMode.HALF_UP.
This may not work for the way you are expected to do it. If you run into problems, folks here will be able to help.
I strongly suggest you post an attempt before asking for any additional help though.
If I calculate the difference between 2 LocalDate's in java.time using:
Period p = Period.between(testDate, today);
Then I get an output with the number of years, months, days like:
Days = 9
Months = 6
Years = 18
Does anyone know a clean way to represent that as a decimal type value (ie, above would be something around 18.5...)?
You mentioned in one of your comments that you need quarter year precision if you need the current quarter you can use IsoFields.QUARTER_YEARS:
double yearAndQuarter = testDate.until(today, IsoFields.QUARTER_YEARS) / 4.0;
This way you will actually use the time api, always get the correct result and #Mike won't have to loathe anything.
Please do not do this.
Representing the difference between two dates as a 'number of years' multiplier is problematic because the average length of a year between two dates is dependent on which dates you are comparing. It's easy to get this wrong, and it's much harder to come up with all the test cases necessary to prove you got it right.
Most programmers should never perform date/time calculations manually. You are virtually guaranteed to get it wrong. Seriously, there are so many ways things can go horribly wrong. Only a handful of programmers on the planet fully understand the many subtleties involved. The fact that you are asking this question proves that you are not one of them, and that's okay--neither am I. You, along with the vast majority of us, should rely on a solid Date/Time API like java.util.time.
If you really need a single numeric value, then the safest option I can think of is to use the number of days, because the LocalDate API can calculate that number for you:
long differenceInDays = testDate.until(today, ChronoUnit.DAYS)
Note that this difference is only valid for the two dates used to produce it. The round-trip conversion is straightforward:
LocalDate today = testDate.plus(differenceInDays, ChronoUnit.DAYS)
Do not attempt to manually convert a Period with year, month, and day components into a whole number of days. The correct answer depends on the dates involved, which is why we want to let the LocalDate API calculate it for us.
When precision isn't important
Based on your comments, precision isn't an issue for you, because you only want to display someone's age to the nearest quarter-year or so. You aren't trying to represent an exact difference in time; only an approximate one, with a rather large margin for error. You also don't need to be able to perform any round-trip calculations. This changes things considerably.
An approximation like #VGR's should be more than adequate for these purposes: the 'number of years' should be accurate to within 3 days (< 0.01 years) unless people start living hundreds of thousands of years, in which case you can switch to double ;).
#Oleg's approach also works quite well, and will give you a date difference in whole quarters, which you can divide by 4 to convert to years. This is probably the easiest solution to get right, as you won't need to round or truncate the result. This is, I think, the closest you will get to a direct solution from java.util.time. The Java Time API (and date/time APIs in general) are designed for correctness: they'll give you whole units, but they usually avoid giving you fractional approximations due to the inherent error involved in floating-point types (there are exceptions, like .NET's System.TimeSpan).
However, if your goal is to present someone's age for human users, and you want greater precision than whole years, I think 18 years, 9 months (or an abbreviated form like 18 yr, 9 mo) is a better choice than 18.75 years.
I would avoid using Period, and instead just calculate the difference in days:
float years = testDate1.until(today, ChronoUnit.DAYS) / 365.2425f;
Ok, I need to write a java algorithm which simulates the SMOOTH function written in IDL. But I'm not quite sure how that algorithm works. The smooth equation is given by:
I know there is already a similar post regarding boxcar averaging. But the algorithm seems to be different.
What I understand in this equation is that there is two states (if statement), the first one is calculating the weight average, the second one is to ignore the boundary.
In the first equation, I think I got the summation notation, it starts from 0 to (w - 1).
What I don't get is the one inside summation Ai+j-w/2.
The following is the sample data (just corner part of large data) that was calculated using IDL. I used weight 5 to calculate this.
Please, explain me how that algorithm works.
Thanks
You want the i'th average to be from a window around the i'th point. So it has to start before that point, and end after.
Subtracting off w/2 in the index causes j=0 to be the start of the window you want, and j=w-1 to be the end of the window you want.
It would be entirely equivalent to sum from j=-w/2 to j=w/2-1 instead.
I'm writing a Java program that automatically generates a certain amount of "units" for the user to do (Actual purpose not important in this question).
I'm struggling to find a good way to determine how many of these "units" to give the user for the next week.
Intentions of the calculation :
Gives "units" of a specific week
Calculates units for the week based on the actual day of the week (Mon-Fri)
Accounts for all of the units that month (Ex. If it is the last week of the month, give all possible units that entire week)
If estimating, should over-estimate (Due to the program's nature, under-estimating would be far worse.)
Units cannot be decimals (Hence the cast to int)
Variables I have :
The amount of "units" to do that month
I have tried to do this in a few different ways, and so far, the best way I have is this :
public static int getRemainingUnitsThisWeek() {
return (int) Math.round(((double) getUnitsThisMonth() / (((30 - (double) DateTime.now().getDayOfMonth()+1) / 7) < 1 ? 1 :
((30 - (double) DateTime.now().getDayOfMonth()+1) / 7))) / (double)DateTime.now().getDayOfWeek());
}
The problem that I end up (specifically, I'm still not happy with how it does it) with is that in the "units" given on the last week of the month is still divided by the day of the week (Which in turn gives you a much lower number each day - even though the user needs to receive all the "units" by the end of the month).
Any questions you might have, just ask!
PS. The library I am using in the DateTime.now() function is joda-time.
Your description is confusing, so I'm not sure I can answer it directly. Instead, I will answer a different question, which may help:
I have a bunch of units to do, and the rest of the month to do them.
How many should I do today?
I don't know about Joda, but using the standard Date API, you can use this answer to get a Date representing the end of the month, a similar technique to get a Date representing the end of today, and new Date() to get the current time. Then subtract their getTime()s. You can then apportion your units now that you know how many milliseconds to the end of the day and the end of the month.
units_today = total_units_to_do * milliseconds_to_end_of_today /
milliseconds_to_end_of_month;
I don't know java, so I won't attempt to write code, but I suggest you start by calculating daysLeftInMonth and daysLeftInWeek. Once you get those working perfectly, you have two simple cases: either the month will end before the week does, or else it won't.
In the first case the rest of the algorithm is trivial. In the second, calculate how many units there should be per day (rounding up), then multiply by the days left in the week.