Lecture collision boolean expression algorithm - boolean-logic

I am trying to write a lecture collision algorithm for a schedule application. Each lecture has a start and end date.
currentListElement is the existing lecture in my current schedule, and I want to add chosenLecture, and check if there is a collision between my current lectures. Therefore, this boolean expression should return true if collision occurs.
Thank you for your help
(currentListElement['startDate'] < chosenLecture['startDate']
|| currentListElement['startDate'] >= chosenLecture['endDate'])
&& (currentListElement['endDate'] <= chosenLecture['startDate']
|| currentListElement['endDate'] > chosenLecture['endDate'])

Actually there is a little mistake, try this:
(currentListElement['endDate'] < chosenLecture['startDate']
|| currentListElement['startDate'] > chosenLecture['endDate'])
There is no collision in two cases:
The lecture is set entirely before the current one. To check that, just make sure it ends before the current starts.
The lecture is set entirely after the current one. To check that, just make sure it starts after the current ends.

Related

Input within Functions - Python

I created a game that randomly picks a number, and the user has to guess that number. Normally, this would be easy, but I'm required to use functions to make it happen.
I have my code linked below. To explain:
get_num() function gives us a number (supposed to be 1 to 1000, but I have it 1 to 10 for troubleshooting)
ask_user() is an input that prompts the user to put in a number.
guess_check() is supposed to determine if your number it too high or too low.
num_guesses() is going to keep track of the number of times the user has guessed. But it's not done, you can ignore that for now.
I'm running PyCharm Community Edition 2021.3.2, for the record.
The problem: The program works fine, except it cannot tell if a number is too big or too small. When you keep guessing the same number, lets say "2", it will keep saying the number is too high and too low. Why? I have the If Statements perfect. If you look at the screenshot, the correct number is 7, and I have the proper if statement. Yet, it still recognizes 2 as higher than 7. Why?
Here is a picture for proof:
Here is the code:
def main():
answer = get_num()
guess = ask_user()
num_guesses = 0
while guess != answer:
check = guess_check(guess)
if check == 2:
print(f"Check is {check}. Your guess of {guess} is too high. Pick something lower. You're now on Guess {num_guesses}!\n")
guess = ask_user()
elif check == 1:
print(f"Check is {check}. Your guess of {guess} is too low. Pick something higher. You're now on Guess {num_guesses}! The correct answer is {answer}\n")
guess = ask_user()
print(f"Check is {check}. Congratulations! Your guess of {guess} is correct! \n\nNumber of Guesses: {num_guesses}")
# This function actually gives us the number to guess
def get_num():
# Randomly determines a number between 0 and 1000
import random
answer = random.randrange(1, 10)
return answer
def ask_user():
answer = int(input("Pick a number: "))
return answer
def guess_check(guess):
answer = get_num()
if guess > answer:
# Guess is too high, therefore value for guess_check() is 2
check = 2
elif guess < answer:
# Guess is too low, therefore value for guess_check() is 1
check = 1
else:
# Guess is right on, therefore value for guess_check() is 0
check = 0
return check
def num_guesses():
number = 1
guess = guess_check()
#If Statement for whether guess is too high (2) or too low (1). If it's 0, then the number of guesses will not increase.'
if guess == 1 or guess == 2:
number += 1
return number
main()
I've tried a few things to get around the problem:
I combined the ask_user() and guess_check() functions into 1 function. This did not make a difference.
Tried coding this exact same program without using functions. Ran just fine. The guess check part of the code ran without issues. So this tells me the functions are the reason this issue is happening.
Anyway, thanks so much for the help. You don't even know how much I appreciate this. I'm desperate.

What's the proper use of output property in Octave?

I am not sure what is the use of output while using fminunc.
>>options = optimset('GradObj','on','MaxIter','1');
>>initialTheta=zeros(2,1);
>>[optTheta, functionVal, exitFlag, output, grad, hessian]=
fminunc(#CostFunc,initialTheta,options);
>> output
output =
scalar structure containing the fields:
iterations = 11
successful = 10
funcCount = 21
Even when I use max no of iteration = 1 still it is giving no of iteration = 11??
Could anyone please explain me why is this happening?
help me with grad and hessian properties too, means the use of those.
Given we don't have the full code, I think the easiest thing for you to do to understand exactly what is happening is to just set a breakpoint in fminunc.m itself, and follow the logic of the code. This is one of the nice things about working with Octave, since the source code is provided and you can check it freely (there's often useful information in octave source code in fact, such as references to papers which they relied on for the implementation, etc).
From a quick look, it doesn't seem like fminunc expects a maxiter of 1. Have a look at line 211:
211 while (niter < maxiter && nfev < maxfev && ! info)
Since niter is initialised just before (at line 176) with the value of 1, in theory this loop will never be entered if your maxiter is 1, which defeats the whole point of the optimization.
There are other interesting things happening in there too, e.g. the inner while loop starting at line 272:
272 while (! suc && niter <= maxiter && nfev < maxfev && ! info)
This uses "shortcut evaluation", to first check if the previous iteration was "unsuccessful", before checking if the number of iterations are less than "maxiter".
In other words, if the previous iteration was successful, you don't get to run the inner loop at all, and you never get to increment niter.
What flags an iteration as "successful" seems to be defined by the ratio of "actual vs predicted reduction", as per the following (non-consecutive) lines:
286 actred = (fval - fval1) / (abs (fval1) + abs (fval));
...
295 prered = -t/(abs (fval) + abs (fval + t));
296 ratio = actred / prered;
...
321 if (ratio >= 1e-4)
322 ## Successful iteration.
...
326 nsuciter += 1;
...
328 endif
329
330 niter += 1;
In other words, it seems like fminunc will respect your maxiters ignoring whether these have been "successful" or "unsuccessful", with the exception that it does not like to "end" the algorithm at a "successful" turn (since the success condition needs to be fulfilled first before the maxiters condition is checked).
Obviously this is an academic point, since you shouldn't even be entering this inner loop when you couldn't even make it past the outer loop in the first place.
I cannot really know exactly what is going on without knowing your specific code, but you should be able to follow easily if you run your code with a breakpoint at fminunc. The maths behind that implementation may be complex, but the code itself seems fairly simple and straightforward enough to follow.
Good luck!

Simple examples for using while loops

I'm trying to write up some examples to explain when a while loop should be used, and when a for loop should be used.
When looking for 'interesting' cases to show young and novice programmers, I realized that the vast majority of textbook examples for while loops will look something like this:
i = 0
while i < 10:
do something
i = i + 1
'do something' might be printing the odd numbers, squaring i, etc... However all these are obviously easier written with a for loop!
I'm looking for more interesting examples. They would have to be:
Suitable for younger programmers (e.g. not too much math such as numerical root finding or the sequence in Collatz conjecture)
Easier (or more intuitive) to be solved with while loops rather than for.
Have some real use to it (e.g. I could do while random() < 0.95, but what's a real use for this?)
The only example I could come up with is when getting a list input from the user one-by-one (e.g. numbers to be summed), but the user will have to terminate it with a special input, and also this seems pointless as the user could just say in advance how many entries there will be in the sequence.
The fundamental difference between a FOR loop and a WHILE loop is that for a FOR loop, the number of iterations is bounded by a constant that is known before the loop starts, whereas for a WHILE loop, the number of iterations can be unbounded, unknown, or infinite.
As a result, a language offering only WHILE loops is Turing-complete, a language offering only FOR loops is not.
So, the first obvious thing that only a WHILE loop can do, is an infinite loop. Things that are easily modeled as infinite loops are, for example, a web server, a Netflix client, a game loop, a GUI event loop, or an operating system:
WHILE (r = nextHttpRequest):
handle(r)
END
WHILE (p = nextVideoStreamPacket):
frame = decode(p)
draw(frame)
END
WHILE (a = playerAction):
computeNextFrame(a)
END
WHILE (e = nextEvent):
handle(e)
END
WHILE (s = sysCall):
process(s)
END
A good example where the loop is not infinite, but the bound is not known in advance, is (as you already mentioned in your question) asking for user input. Something like this:
WHILE (askBoolean("Do you want to play again?")):
playGame()
END
Another good example is processing a C-like string, where the length of the string is unknown but finite. This is the same situation for a linked list, or for any data structure where there is a notion of "next", but not a notion of "size", instead there is some sentinel value that marks the end (e.g. NUL-terminated strings in C) or a way to check whether there is a next element (e.g. Iterator in Java):
WHILE ((element = getNext()) != END_MARKER):
process(element)
END
WHILE (hasNextElement):
process(getNext())
END
There are also situations that can be handled with a FOR loop, but a WHILE loop is more elegant. One situation I can think of, is that the bound for the number of iterations is known in advance, it is constant, but the known bound is ridiculously large, and the actual number of iterations required is significantly less than the bound.
Unfortunately, I cannot come up with a good real-life example of this, maybe someone else can. A FOR loop for this will then typically look like this, in order to skip the iterations from the actual number of iterations up to the upper bound:
FOR (i FROM 1 TO $SOME_LARGE_UPPER_BOUND):
IF (terminationConditionReached):
NOOP()
ELSE:
doSomethingInteresting()
END
END
Which would much better be expressed as
WHILE (NOT terminationConditionReached):
doSomethingInteresting()
END
Using the FOR loop could make sense in this situation, if the value of i is of interest:
FOR (i FROM 1 TO $SOME_LARGE_UPPER_BOUND):
IF (terminationConditionReached):
NOOP()
ELSE:
doSomethingInterestingWithI(i)
END
END
A last situation I can think of, where a WHILE loop is more appropriate than a FOR loop, even though the number of iterations is bounded by a known constant, is if that constant is not "semantically interesting" for the loop.
For example, a game loop for Tic-Tac-Toe only needs at most 9 moves, so it could be modeled as a FOR loop:
FOR (i FROM 1 TO 9):
IF (player1Won OR player2Won):
NOOP
ELSE:
makeMove()
END
END
But, the number "9" is not really interesting here. It's much more interesting whether one player has one or the board is full:
WHILE (NOT (player1Won OR player2Won OR boardFull)):
makeMove()
END
[Note: at least if playing against a child, this is also an example of the second-to-last situation, namely that the upper bound is known to be 9, but a lot of games will be shorter than 9 moves. However, I would still like to find an example for that, which is not also an example of a semantically un-interesting termination condition.]
So, we have two classes of situations here: one, where a FOR loop simply cannot be used (when the bound is unknown, non-existant, or infinite), and one, where a FOR loop can be used, but a WHILE loop is more intention-revealing.

AS3: Combining counter (score) variable from multiple objects in different classes

I am developing a fairly basic objective class space-shooter style flash game in AS3. The game originally contained 1 enemy target which had random variable parameters, such as speed and health, but the combined score counter remained predefined, one.
I have since expanded my game to where I have several enemy targets each having their own class, thus, they have their own variable parameter values. I also took the liberty of increasing the combined score, to reflect the difficulty of each enemy target.
The problem that I am running in to, is that my original line of code for combining the score counter is still set to "score++;", which just adds a value of 1 each time that "if statement" occurs.
My question, is how can I get my score counter to increase the score based on the value assigned for each respective class?
Here are a few bits of relevant code, with notes to help explain my view:
"If statement" (housed in my Level class) for when an enemy target is killed:
// if the bullet is touching the ship
if (MyMaths.hitTest(sh, bullets[bcount])) {
sh.health--; // lose 1 heath point
score++;
removeChild(bullets[bcount]); // remove the bullet from the screen
bullets.splice(bcount, 1); // remove the bullet from the list
}
Ship1 (housed in my Ship1 class) score value
public function Ship1() {
score=1; // set point value
}
Ship2 (housed in my Ship2 class) score value
public function Ship1() {
score=2; // set point value
}
Ship3 (housed in my Ship3 class) score value
public function Ship1() {
score=3; // set point value
}
I am just not sure if I would need to make a new function for combining the score value, and have my "score++;" pull from that, and how would I go about that?
I feel that this is a question that many fellow Objective-Oriented programmers would deem relevant, as combining a variable from multiple classes to a single counter is not as easy as it may seem. Also, this could be used in a wide range of other developer niches, apart from game developing -- creating a database of multiple models of computers in a network, and calculating a "total completed" field, after refreshing the workstations with a new OS or required software.
I really would appreciate anybody who could offer their expertise, opinion and/or words of encouragement.
Thank you very much,
Alex
Why not have a Singleton that each of the ships communicate with instead of doing it that way.
Whenever you increment the score:
ScoreManager.getInstance().incrementScore(ShipX.getScoreDelta())
Where getScoreDelta() would be reset to 0 after each collection.
Then when the game is done:
ScoreManager.getInstance().getCurrentScore();

Loop termination conditions

These for-loops are among the first basic examples of formal correctness proofs of algorithms. They have different but equivalent termination conditions:
1 for ( int i = 0; i != N; ++i )
2 for ( int i = 0; i < N; ++i )
The difference becomes clear in the postconditions:
The first one gives the strong guarantee that i == N after the loop terminates.
The second one only gives the weak guarantee that i >= N after the loop terminates, but you will be tempted to assume that i == N.
If for any reason the increment ++i is ever changed to something like i += 2, or if i gets modified inside the loop, or if N is negative, the program can fail:
The first one may get stuck in an infinite loop. It fails early, in the loop that has the error. Debugging is easy.
The second loop will terminate, and at some later time the program may fail because of your incorrect assumption of i == N. It can fail far away from the loop that caused the bug, making it hard to trace back. Or it can silently continue doing something unexpected, which is even worse.
Which termination condition do you prefer, and why? Are there other considerations? Why do many programmers who know this, refuse to apply it?
I tend to use the second form, simply because then I can be more sure that the loop will terminate. I.e. it's harder to introduce a non-termination bug by altering i inside the loop.
Of course, it also has the slightly lazy advantage of being one less character to type ;)
I would also argue, that in a language with sensible scope rules, as i is declared inside the loop construct, it shouldn't be available outside the loop. This would mitigate any reliance on i being equal to N at the end of the loop...
We shouldn't look at the counter in isolation - if for any reason someone changed the way the counter is incremented they would change the termination conditions and the resulting logic if it's required for i==N.
I would prefer the the second condition since it's more standard and will not result in endless loop.
In C++, using the != test is preferred for generality. Iterators in C++ have various concepts, like input iterator, forward iterator, bidirectional iterator, random access iterator, each of which extends the previous one with new capabilities. For < to work, random access iterator is required, whereas != merely requires input iterator.
If you trust your code, you can do either.
If you want your code to be readable and easily understood (and thus more tolerant to change from someone who you've got to assume to be a klutz), I'd use something like;
for ( int i = 0 ; i >= 0 && i < N ; ++i)
I always use #2 as then you can be sure the loop will terminate... Relying on it being equal to N afterwards is relying on a side effect... Wouldn't you just be better using the variable N itself?
[edit] Sorry...I meant #2
I think most programmers use the 2nd one, because it helps figure out what goes on inside the loop. I can look at it, and "know" that i will start as 0, and will definitely be less than N.
The 1st variant doesn't have this quality. I can look at it, and all I know is that i will start as 0 and that it won't ever be equal to N. Not quite as helpful.
Irrespective of how you terminate the loop, it is always good to be very wary of using a loop control variable outside the loop. In your examples you (correctly) declare i inside the loop, so it is not in scope outside the loop and the question of its value is moot...
Of course, the 2nd variant also has the advantage that it's what all of the C references I have seen use :-)
In general I would prefer
for ( int i = 0; i < N; ++i )
The punishment for a buggy program in production, seems a lot less severe, you will not have a thread stuck forever in a for loop, a situation that can be very risky and very hard to diagnose.
Also, in general I like to avoid these kind of loops in favour of the more readable foreach style loops.
I prefer to use #2, only because I try not to extend the meaning of i outside of the for loop. If I were tracking a variable like that, I would create an additional test. Some may say this is redundant or inefficient, but it reminds the reader of my intent: At this point, i must equal N
#timyates - I agree one shouldn't rely on side-effects
I think you stated very well the difference between the two. I do have the following comments, though:
This is not "language-agnostic", I can see your examples are in C++ but there
are languages where you are not allowed to modify the loop variable inside the
loop and others that don't guarantee that the value of the index is usable after
the loop (and some do both).
You have declared the i
index within the for so I would not bet on the value of i after the loop.
The examples are a little bit misleading as they implictly assume that for is
a definite loop. In reality it is just a more convenient way of writing:
// version 1
{ int i = 0;
while (i != N) {
...
++i;
}
}
Note how i is undefined after the block.
If a programmer knew all of the above would not make general assumption of the value of i and would be wise enough to choose i<N as the ending conditions, to ensure that the the exit condition will be eventually met.
Using either of the above in c# would cause a compiler error if you used i outside the loop
I prefer this sometimes:
for (int i = 0; (i <= (n-1)); i++) { ... }
This version shows directly the range of values that i can have. My take on checking lower and upper bound of the range is that if you really need this, your code has too many side effects and needs to be rewritten.
The other version:
for (int i = 1; (i <= n); i++) { ... }
helps you determine how often the loop body is called. This also has valid use cases.
For general programming work I prefer
for ( int i = 0; i < N; ++i )
to
for ( int i = 0; i != N; ++i )
Because it is less error prone, especially when code gets refactored. I have seen this kind of code turned into an infinite loop by accident.
That argument made that "you will be tempted to assume that i == N", I don't believe is true. I have never made that assumption or seen another programmer make it.
From my standpoint of formal verification and automatic termination analysis, I strongly prefer #2 (<). It is quite easy to track that some variable is increased (before var = x, after var = x+n for some non-negative number n). However, it is not that easy to see that i==N eventually holds. For this, one needs to infer that i is increased by exactly 1 in each step, which (in more complicated examples) might be lost due to abstraction.
If you think about the loop which increments by two (i = i + 2), this general idea becomes more understandable. To guarantee termination one now needs to know that i%2 == N%2, whereas this is irrelevant when using < as the condition.