Pascal problem: only 1 in 20 testcases were correct [closed] - pascal

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 15 days ago.
Improve this question
I found a hard problem:
The OP phone company recently plans to switch to a smart band with some functions such as measuring heart rate, blood oxygen levels and monitoring and assessing sleep quality. Currently, the problem of sleep deprivation due to the nature of work is getting heavier, so OP company wants to focus mainly on evaluating and improving sleep for users. The evaluation criteria are as follows: sleeping less than 6 hours will be sleep deprivation (short); from 6 to 9 hours is normal; Over 9 hours is a lot of sleep (long). To test the accuracy of the bracelet, this company hired n people to check. Each person will wear a bracelet before going to bed. The time to start sleeping can vary from person to person and a person does not sleep more than a day (sleeping less than 24 hours). Write a program to calculate and evaluate sleep for this company.
INPUT:
The first line contains an integer n representing the number of test participants (1≤n≤20000).
The next n lines record the hours, minutes, seconds (hh1 mm1 ss1) the ith person sleeps and the hours minutes seconds wake up (hh2 mm2 ss2) (0 ≤ i < n; 0 ≤ hh1, hh2 ≤ 23; 0 ≤ mm1, mm2 < 60 ; 0≤ ss1, ss2 < 60) (separated by a space).
OUTPUT:
A single line of assessors' sleep status (short, normal, long) (separated by a space).
This is my Pascal code. I tried so much but it is only correct for 1 in 20 testcases of the problem:
uses crt;
var i,n,j:integer;
a,b:longint;
s:array[1..6] of byte;
c:array[1..30000] of string;
begin
readln(n);
for i:=1 to n do
begin
fillchar(s,sizeof(s),0);
for j:=1 to 6 do read(s[j]);
a:=s[3]+s[2]*60+s[1]*3600;
if s[4]<s[1] then s[4]:=s[4]+24;
b:=s[6]+s[5]*60+s[4]*3600;
writeln(b-a,s[4]);
if b-a<21600 then c[i]:='short'
else if b-a<32400 then c[i]:='normal'
else c[i]:='long'
end;
for i:=1 to n do write(c[i],' ');
end.

Related

Minimize the number of trips or Group maximum possible orders

We have one distribution center ( ware house ) and we are getting orders in real time whose time/distance from ware house and other order locations is known.
time matrix=
W O1 O2 O3
W 0 5 20 2
O1 5 0 21 7
O2 20 21 0 11
O3 2 7 11 0
order time of O1= 10:00 AM
order time of O2= 10:20 AM
order time of O3= 10:25 AM
I want to club as many as order possible such that delivery time of any order does not exceed by 2 hours of its order time. Thus the question is to reduce the number of trips(Trip is when delivery agent goes for delivery).
I am trying to come up with algorithm for this. there are two competing factors when
We can combine all the orders in the sequence as they are coming till it satisfies the constraint of delivery of the order within 2 hours of its ordering time.
We can modify above approach to find the bottleneck order(due to which we can not club more order now in approach 1). and pull it out from trip1 and make it a part of trip 2(new order) and wait for other orders to club it with trip1 or trip2 depending.
All the orders are coming in realtime. What will be the best approach to conquer this situation. Let me know if you need more clarity on this.
Very safe and easy algorithm which is guaranteed to not exceed the maximal waiting time for an order:
Let TSP() be a function which returns the estimate of time spent to visit given places. The estimate is pessimistic, i.e. the actual ride time can be shorter or equals to estimate, but not longer. For the good start you can implement TSP() very easily in a greedy way: from each place go to the nearest place. You can subtract the length of the longer edge coming out from W to have better estimate (so a car will always take the shorter edge coming out of W). If TSP() would happen to be optimal, then the whole algorithm presented here would be also optimal. The overall algorithm is as good as TSP() implementation is, it highly depends on good estimation.
Let earliestOrderTime be a time of the earliest not handled yet order.
Repeat every minute:
If there is a new order: If s is empty, set earliestOrderTime to current time. Add it to a set s. Calculate t = TSP(s + W).
If (current time + t >= earliestOrderTime + 2 hours): send a car for a TSP(s + W) trip. Make s an empty set.
Example
For your exemplary data it will work like this:
10:00. earliestOrderTime = 10:00. s = {O1}. t = TSP({01, W}) = 10 - 5 = 5.
10:00 + 0:05 < 10:00 + 2:00, so we don't send a car yet, we wait.
...
10:20. s = {O1, O2}. t = 46 - 20 = 26.
10:20 + 0:26 < 10:00 + 2:00, so we wait.
...
10:25. s = {O1, O2, O3}. t = 2 + 7 + 21 + 20 - 20 = 30.
10:25 + 0:30 < 10:00 + 2:00, so we wait.
...
11.30.
11:30 + 0:30 >= 10:00 + 2:00, so we send a car to go to O3, O1, O2 and back to W. He visits orders at 11:32, 11:39, 12:00 and come backs at 12:20. Guys where waiting 67, 99 and 100 minutes.

Need help on a problemset in a programming contest [closed]

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've attended a local programming contest on my country. The name of the contest is "ACM-ICPC Indonesia National Contest 2013".
The contest has ended on 2013-10-13 15:00:00 (GMT +7) and I am still curious about one of the problems.
You can find the original version of the problem here.
Brief Problem Explanation:
There are a set of "jobs" (tasks) that should be performed on several "servers" (computers).
Each job should be executed strictly from start time Si to end time Ei
Each server can only perform one task at a time.
(The complicated thing goes here) It takes some time for a server to switch from one job to another.
If a server finishes job Jx, then to start job Jy it will need an intermission time Tx,y after job Jx completes. This is the time required by the server to clean up job Jx and load job Jy.
In other word, job Jy can be run after job Jx if and only if Ex + Tx,y ≤ Sy.
The problem is to compute the minimum number of servers needed to do all jobs.
Example:
For example, let there be 3 jobs
S(1) = 3 and E(1) = 6
S(2) = 10 and E(2) = 15
S(3) = 16 and E(3) = 20
T(1,2) = 2, T(1,3) = 5
T(2,1) = 0, T(2,3) = 3
T(3,1) = 0, T(3,2) = 0
In this example, we need 2 servers:
Server 1: J(1), J(2)
Server 2: J(3)
Sample Input:
Short explanation: The first 3 is the number of test cases, following by number of jobs (the second 3 means that there are 3 jobs for case 1), then followed by Ei and Si, then the T matrix (sized equal with number of jobs).
3
3
3 6
10 15
16 20
0 2 5
0 0 3
0 0 0
4
8 10
4 7
12 15
1 4
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
4
8 10
4 7
12 15
1 4
0 50 50 50
50 0 50 50
50 50 0 50
50 50 50 0
Sample Output:
Case #1: 2
Case #2: 1
Case #3: 4
Personal Comments:
The time required can be represented as a graph matrix, so I'm supposing this as a directed acyclic graph problem.
Methods I tried so far is brute force and greedy, but got Wrong Answer. (Unfortunately I don't have my code anymore)
Could probably solved by dynamic programming too, but I'm not sure.
I really have no clear idea on how to solve this problem.
So a simple hint or insight will be very helpful to me.
You can solve this by computing the maximum matching in a bipartite graph.
The idea is you are trying to match job end times with job start times.
A matched end time x with start time y means that the same server will do job x and job y.
The number of servers you need will correspond to the number of unmatched start times (because each of these jobs will require a new server).
Example Python code using NetworkX:
import networkx as nx
G=nx.DiGraph()
S=[3,10,16] # start times
E=[6,15,20] # end times
T = [ [0, 2, 5],
[0, 0, 3],
[0, 0, 0] ] # T[x][y]
N=len(S)
for jobx in range(N):
G.add_edge('start','end'+str(jobx),capacity=1)
G.add_edge('start'+str(jobx),'end',capacity=1)
for joby in range(N):
if E[jobx]+T[jobx][joby] <= S[joby]:
G.add_edge('end'+str(jobx),'start'+str(joby),capacity=1)
print N-nx.max_flow(G,'start','end')

Test cases for algorithm puzzle

The following is the problem from Interviewstreet Can someone please give me a few test cases along with the output. My solution is within the time limit for all test cases but is giving Wrong Answer.
Circle Summation (30 Points)
There are N children sitting along a circle, numbered 1,2,...,N clockwise. The ith child has a piece of paper with number ai written on it. They play the following game:
In the first round, the child numbered x adds to his number the sum of the numbers of his neighbors.
In the second round, the child next in clockwise order adds to his number the sum of the numbers of his neighbors, and so on.
The game ends after M rounds have been played.
Input:
The first line contains T, the number of test cases. T cases follow. The first line for a test case contains two space seperated integers N and M. The next line contains N integers, the ith number being ai.
Output:
For each test case, output N lines each having N integers. The jth integer on the ith line contains the number that the jth child ends up with if the game starts with child i playing the first round. Output a blank line after each test case except the last one. Since the numbers can be really huge, output them modulo 1000000007.
Constraints:
1 <= T <= 15
3 <= N <= 50
1 <= M <= 10^9
1 <= ai <= 10^9
Sample Input:
2
5 1
10 20 30 40 50
3 4
1 2 1
Sample Output:
80 20 30 40 50
10 60 30 40 50
10 20 90 40 50
10 20 30 120 50
10 20 30 40 100
23 7 12
11 21 6
7 13 24
If it seems to do ok for small test-cases, but not all, I would guess you have an overflow problem.
Make sure you either...
Do the modulus after each addition, not just after adding all three numbers.
Use 64-bit numbers. This would still require modulus, but not as often.
1000000007 is pretty close to the limit of signed 32-bit numbers (214748367). You can add to modulated numbers without overflow, but not three.

Probability of event

Here is a probability problem: you observe .5 cars on average passing in front of you every 5 minutes on a road. What is the probability of seeing at least 1 car in 10 minutes?
I'm trying to solve this in 2 ways. The first way is to say: P(no car in 5 minutes) = 1 - .5 = .5. P(no car in first 5 minutes and no car in second 5 minutes) = P(no car in first 5 minutes) * P(no car in second 5 minutes) by independence. Therefore P(at least 1 car in 10 minutes) = 1 - .5*.5 = .75.
However, if I try the same, with a Poisson distribution with rate lambda = .5 per unit of time, for 2 units of time, I get: P(at least 1 car in 2 units of time) = 1 - exp(-2*lambda) = .63.
Am I doing something wrong? If not, what explains the discrepancy?
Thanks!
Your first calculation is incorrect. An average .5 cars / 5 minutes does not imply P(no car in 5 minutes) = 0.5. Consider for instance a process where every five minute, you see either no car with probability 90%, or 5 cars with probability 10%. On average you will see 0.5 cars every five minute, but the probability you see 0 cars in the next 5 minutes is clearly not 50%.
I haven't checked the computations for your second example; the calculation logic is looks correct, but the conclusion is incorrect: you are making an assumption about the distribution (Poisson) which is plausible but not implied by the problem statement.
If you take again my example, which is consistent with your problem description, the probability to see 0 cars in 10 minutes is 0.9 x 0.9 = 0.81, which gives you 19% of seeing one car or more. We could arbitrarily change my example to give you a wide variety of probabilities.
From your problem statement, the only thing you can say is that "in the long run, you'll see 0.5 cars every 5 minutes". Beyond that you can't make a statement on what should be expected within 10 minutes, unless you make some assumptions about the distribution of the cars arrivals.

Leap year calculation

In order to find leap years, why must the year be indivisible by 100 and divisible by 400?
I understand why it must be divisible by 4. Please explain the algorithm.
The length of a year is (more or less) 365.242196 days.
So we have to subtract, more or less, a quarter of a day to make it fit :
365.242196 - 0.25 = 364.992196 (by adding 1 day in 4 years) : but oops, now it's too small!! lets add a hundreth of a day (by not adding that day once in a hundred year :-))
364.992196 + 0,01 = 365.002196 (oops, a bit too big, let's add that day anyway one time in about 400 years)
365.002196 - 1/400 = 364.999696
Almost there now, just play with leapseconds now and then, and you're set.
(Note : the reason no more corrections are applied after this step is because a year also CHANGES IN LENGTH!!, that's why leapseconds are the most flexible solution, see for examlple here)
That's why i guess
There's an algorithm on wikipedia to determine leap years:
function isLeapYear (year):
if ((year modulo 4 is 0) and (year modulo 100 is not 0))
or (year modulo 400 is 0)
then true
else false
There's a lot of information about this topic on the wikipedia page about leap years, inclusive information about different calendars.
In general terms the algorithm for calculating a leap year is as follows...
A year will be a leap year if it is divisible by 4 but not by 100. If a year is divisible by 4 and by 100, it is not a leap year unless it is also divisible by 400.
Thus years such as 1996, 1992, 1988 and so on are leap years because they are divisible by 4 but not by 100. For century years, the 400 rule is important. Thus, century years 1900, 1800 and 1700 while all still divisible by 4 are also exactly divisible by 100. As they are not further divisible by 400, they are not leap years
this is enough to check if a year is a leap year.
if( (year%400==0 || year%100!=0) &&(year%4==0))
cout<<"It is a leap year";
else
cout<<"It is not a leap year";
a) The year is 365.242199 days.
b) If every year was 365 days, in 100 years we would lose 24.2199 days.
That's why we add 24 days per century (every 4 years EXCEPT when divisible by 100)
c) But still we lose 0.21299 days/century. So in 4 centuries we lose 0.8796 days.
That's why we add 1 day per 4 centuries (every fourth century we DO count a leap year).
d) But that means we lose -0.1204 days (we go forward) per quadricentennial (4 centuries). So in 8 quadricentennial (3200 years) we DO NOT count a leap year.
e) But that means we lose 0.0368 days per 3200 years. So in 24x3200 years (=76800years) we lose 0.8832 days. That's why we DO count a leap year.
and so on... (by then we will have destroyed the planet, so it doesn't matter)
What I cannot understand though, is why we don't count a leap year every 500 years instead of 400. In that way we would converge more rapidly to the correct time (we would lose 2.3 hours/500 years).
I'm sure Wikipedia can explain it better than I can, but it is basically to do with the fact that if you added an extra day every four years we'd get ahead of the sun as its time to orbit the sun is less than 365.25 days so we compensate for this by not adding leap days on years that are not divisible by 400 eg 1900.
Hope that helps
Here is a simple implementation of the wikipedia algorithm, using the javascript ternary operator:
isLeapYear = (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);
Return true if the input year is a leap year
Basic modern day code:
If year mod 4 = 0, then leap year
if year mod 100 then normal year
if year mod 400 then leap year
else normal year
Todays rule started 1582 AD
Julian calendar rule with every 4th year started 46BC but is not coherent before 10 AD as declared by Cesar.
They did however add some leap years every 3rd year now and then in the years before:
Leap years were therefore 45 BC, 42 BC, 39 BC, 36 BC, 33 BC, 30 BC, 27 BC, 24 BC, 21 BC, 18 BC, 15 BC, 12 BC, 9 BC, 8 AD, 12 AD
Before year 45BC leap year was not added.
The year 0 do not exist as it is ...2BC 1BC 1AD 2AD... for some calculation this can be an issue.
function isLeapYear(year: Integer): Boolean;
begin
result := false;
if year > 1582 then // Todays calendar rule was started in year 1582
result := ((year mod 4 = 0) and (not(year mod 100 = 0))) or (year mod 400 = 0)
else if year > 10 then // Between year 10 and year 1582 every 4th year was a leap year
result := year mod 4 = 0
else //Between year -45 and year 10 only certain years was leap year, every 3rd year but the entire time
case year of
-45, -42, -39, -36, -33, -30, -27, -24, -21, -18, -15, -12, -9:
result := true;
end;
end;
You really should try to google first.
Wikipedia has a explanation of leap years. The algorithm your describing is for the Proleptic Gregorian calendar.
More about the math around it can be found in the article Calendar Algorithms (PDF).
Will it not be much better if we make one step further.
Assuming every 3200 year as no leap year,
the length of the year will come
364.999696 + 1/3200 = 364.999696 + .0003125 = 365.0000085
and after this the adjustment will be required after around 120000 years.
In Java Below code calculates leap year count between two given year. Determine starting and ending point of the loop.
Then if parameter modulo 4 is equal 0 and parameter modulo 100 not equal 0 or parameter modulo 400 equal zero then it is leap year and increase counter.
static int calculateLeapYearCount(int year, int startingYear) {
int min = Math.min(year, startingYear);
int max = Math.max(year, startingYear);
int counter = 0;
for (int i = min; i < max; i++) {
if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) {
counter = counter + 1;
}
}
return counter;
}
PHP:
// is number of days in the year 366? (php days of year is 0 based)
return ((int)date('z', strtotime('Dec 31')) === 365);
Leap years are arbitrary, and the system used to describe them is a man made construct. There is no why.
What I mean is there could have been a leap year every 28 years and we would have an extra week in those leap years ... but the powers that be decided to make it a day every 4 years to catch up.
It also has to do with the earth taking a pesky 365.25 days to go round the sun etc. Of course it isn't really 365.25 is it slightly less (365.242222...), so to correct for this discrepancy they decided drop the leap years that are divisible by 100.
If you're interested in the reasons for these rules, it's because the time it takes the earth to make exactly one orbit around the sun is a long imprecise decimal value. It's not exactly 365.25. It's slightly less than 365.25, so every 100 years, one leap day must be eliminated (365.25 - 0.01 = 365.24). But that's not exactly correct either. The value is slightly larger than 365.24. So only 3 out of 4 times will the 100 year rule apply (or in other words, add back in 1 day every 400 years; 365.25 - 0.01 + 0.0025 = 365.2425).
There are on average, roughly 365.2425 days in a year at the moment (the Earth is slowing down but let's ignore that for now).
The reason we have leap years every 4 years is because that gets us to 365.25 on average [(365+365+365+366) / 4 = 365.25, 1461 days in 4 years].
The reason we don't have leap years on the 100-multiples is to get us to 365.24 `[(1461 x 25 - 1) / 100 = 365.24, 36,524 days in 100 years.
Then the reason we once again have a leap year on 400-multiples is to get us to 365.2425 [(36,524 x 4 + 1) / 400 = 365.2425, 146,097 days in 400 years].
I believe there may be another rule at 3600-multiples but I've never coded for it (Y2K was one thing but planning for one and a half thousand years into the future is not necessary in my opinion - keep in mind I've been wrong before).
So, the rules are, in decreasing priority:
multiple of 400 is a leap year.
multiple of 100 is not a leap year.
multiple of 4 is a leap year.
anything else is not a leap year.
Here comes a rather obsqure idea.
When every year dividable with 100 gets 365 days, what shall be done at this time? In the far future, when even years dividable with 400 only can get 365 days.
Then there is a possibility or reason to make corrections in years dividable with 80.
Normal years will have 365 day and those dividable with 400 can get 366 days. Or is this a loose-loose situation.
You could just check if the Year number is divisible by both 4 and 400. You dont really need to check if it is indivisible by 100. The reason 400 comes into question is because according to the Gregorian Calendar, our "day length" is slightly off, and thus to compensate that, we have 303 regular years (365 days each) and 97 leap years (366 days each). The difference of those 3 extra years that are not leap years is to stay in cycle with the Gregorian calendar, which repeats every 400 years. Look up Christian Zeller's congruence equation. It will help understanding the real reason. Hope this helps :)
In the Gregorian calendar 3 criteria must be taken into account to identify leap years:
The year is evenly divisible by 4;
If the year can be evenly divided by 100, it is NOT a leap year, unless;
The year is also evenly divisible by 400. Then it is a leap year. Why the year divided by 100 is not leap year
Python 3.5
def is_leap_baby(year):
if ((year % 4 is 0) and (year % 100 is not 0)) or (year % 400 is 0):
return "{0}, {1} is a leap year".format(True, year)
return "{0} is not a leap year".format(year)
print(is_leap_baby(2014))
print(is_leap_baby(2012))
Simply
Because year 2000 is a leap year and it is divisible by 100 and dividable by 4.
SO to guarantee it is correct leap we need to ensure it is divisible by 400.
2000 % 4 = 0
2000 % 100 = 0
According to algorithm it's not leap, but it is dividable by 400
2000 % 400 = 0
so it is leap.
I found this problem in the book "Illustrated Guide to Python 3". It was in a very early chapter that only discussed the math operations, no loops, no comparisons, no conditionals. How can you tell if a given year is a leap year?
Below is what I came up with:
y = y % 400
a = y % 4
b = y % 100
c = y // 100
ly = (0**a) * ((1-(0**b)) + 0**c) # ly is not zero for leap years, else 0
This is the most efficient way, I think.
Python:
def leap(n):
if n % 100 == 0:
n = n / 100
return n % 4 == 0
C# implementation
public bool LeapYear()
{
int year = 2016;
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ;
}
From 1700 to 1917, official calendar was the Julian calendar. Since then they we use the Gregorian calendar system. The transition from the Julian to Gregorian calendar system occurred in 1918, when the next day after January 31st was February 14th. This means that 32nd day in 1918, was the February 14th.
In both calendar systems, February is the only month with a variable amount of days, it has 29 days during a leap year, and 28 days during all other years. In the Julian calendar, leap years are divisible by 4 while in the Gregorian calendar, leap years are either of the following:
Divisible by 400.
Divisible by 4 and not divisible by 100.
So the program for leap year will be:
Python:
def leap_notleap(year):
yr = ''
if year <= 1917:
if year % 4 == 0:
yr = 'leap'
else:
yr = 'not leap'
elif year >= 1919:
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
yr = 'leap'
else:
yr = 'not leap'
else:
yr = 'none actually, since feb had only 14 days'
return yr
In shell you can use cal -j YYYY which prints the julian day of the year, If the last julian day is 366, then it is a leap year.
$ function check_leap_year
{
year=$1
if [ `cal -j $year | awk 'NF>0' | awk 'END { print $NF } '` -eq 366 ];
then
echo "$year -> Leap Year";
else
echo "$year -> Normal Year" ;
fi
}
$ check_leap_year 1900
1900 -> Normal Year
$ check_leap_year 2000
2000 -> Leap Year
$ check_leap_year 2001
2001 -> Normal Year
$ check_leap_year 2020
2020 -> Leap Year
$
Using awk, you can do
$ awk -v year=1900 ' BEGIN { jul=strftime("%j",mktime(year " 12 31 0 0 0 ")); print jul } '
365
$ awk -v year=2000 ' BEGIN { jul=strftime("%j",mktime(year " 12 31 0 0 0 ")); print jul } '
366
$ awk -v year=2001 ' BEGIN { jul=strftime("%j",mktime(year " 12 31 0 0 0 ")); print jul } '
365
$ awk -v year=2020 ' BEGIN { jul=strftime("%j",mktime(year " 12 31 0 0 0 ")); print jul } '
366
$
BIS will be 1 if the year is leap, otherwise 0 in this boolean logic:
BIS = A MOD 4=0 - (A MOD 100=0 AND A>1600) + (A MOD 400=0 AND A>1600)
just wrote this in Coffee-Script:
is_leap_year = ( year ) ->
assert isa_integer year
return true if year % 400 == 0
return false if year % 100 == 0
return true if year % 4 == 0
return false
# parseInt? that's not even a word.
# Let's rewrite that using real language:
integer = parseInt
isa_number = ( x ) ->
return Object.prototype.toString.call( x ) == '[object Number]' and not isNaN( x )
isa_integer = ( x ) ->
return ( isa_number x ) and ( x == integer( x ) )
of course, the validity checking done here goes a little further than what was asked for, but i find it a necessary thing to do in good programming.
note that the return values of this function indicate leap years in the so-called proleptic gregorian calendar, so for the year 1400 it indicates false, whereas in fact that year was a leap year, according to the then-used julian calendar. i will still leave it as such in the datetime library i'm writing because writing correct code to deal with dates quickly gets surprisingly involved, so i will only ever support the gregorian calendar (or get paid for another one).

Resources