How to use the hasNext multiple times - java.util.scanner

So I am working on a program that will use Scanner to read through a text file and count the number of words, sentences, etc. I have code that works, but only to some degree and it is confusing me greatly. I have these two classes,
public void sentences()
{
while(text.hasNext())
{
// code to check for and count sentence ends
}
}
public void words()
{
while(text.hasNext())
{
// code to count for words
}
}
The confusing (to me) part is when I run both of these methods they work. However, (the order doesn't matter) the second one will not work. So if I were to write
w.words();
w.sentences();
the sentences method will do nothing and give me a value of 0. I have done some testing with system.out.println() and the sentences method will get called, but it will skip over the loop. So I feel like there something to do with the hasNext() method. Any thoughts?

The loop in words finishes when hasNext returns false. Unless you do something before the call to sentences it will still return false there, and never enter the loop.

Related

What is the equivalent of 'pass' from Python?

I want to check if the result from a request is having any issue. I categorize it into two: i) server error, ii) something else that is not a success. The third category is, result actually being a success. However, in the third category, I don't want to do anything.
So, my desirable code is:
if res.status().is_server_error() {
panic!("server error!");
} else if !(res.status.is_success()){
panic!("Something else happened. Status: {:?}", res.status());
} else{
pass;
}
I am aware of other ways to achieve this result: using match, ifs instead of if else if. But I wanted to learn what is the corresponding keyword of pass, like we have in Python. My aim is: if result is successful, just move along, if not, there are two ways to handle that panic.
Behold!
if predicate {
do_things();
} else {
// pass
}
Or even better
if predicate {
do_things();
} // pass
Or as I’ve recently taken to calling it the implicit + pass system
if predicate {
do_things();
}
In all seriousness there is no pass and no need for a pass in rust. As for why it exists in python, check out this answer
Python needs pass because it uses indentation-based blocks, so it requires some syntax to "do nothing". For example, this would be a syntax error in a Python program:
# syntax error - function definition cannot be empty
def ignore(_doc):
# do nothing
count = process_docs(docs, ignore) # just count the docs
The ignore function has to contain a block, which in turn must contain at least one statement. We could insert a dummy statement like None, but Python provides pass which compiles to nothing and signals the intention (to do nothing) to the human reader.
This is not needed in Rust because Rust uses braces for blocks, so one can always create an empty block simply using {}:
// no error - empty blocks are fine
fn ignore(_doc: &Document) {
// do nothing
}
let count = process_docs(docs, ignore); // just count the docs
Of course, in both idiomatic Python and Rust, one would use a closure for something as simple as the above ignore function, but there are still situations where pass and empty blocks are genuinely useful.

Ternary operator - exercise. I didn't get it, how the counting mechanics works - detailed explanation needed

Thank you in advance for your time and help.
Exercise:
Write the code for sumDigitsInNumber(int number). The method takes a three-digit whole number. You need to calculate the sum of the digits of this number, and then return the result.
Consider this example:
The sumDigitsInNumber method is called with argument 546.
Example output:
15
CODE:
public class Solution {
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
return number ==0? 0:number%10+sumDigitsInNumber(number/10);
}
}
This is a solution and the task has been passed. The problem is the solution had been implemented by someone (not by me) therefore I can't understand How this function does its job.
I tried to test the function parts separately, just to see what would happen, and here is the result:
number%10 = 546%10;
546/10 = 54;
output:
6+sumDigitsInNumber(546/10) - which is totally wrong.
I don't understand HOW sumDigitsInNumber is treated by the ternary operator in there and how this short line of code:
return number ==0? 0:number%10+sumDigitsInNumber(number/10);
makes such a complicated calculation?
Can anyone explain it to me in a way it would have explained to a Java-child?
TYVM in advance.
So, using the example number of 546, let's step through the code.
In the first run, it does indeed return 6+sumDigitsInNumber(546/10), that is all correct.
Because sumDigitsInNumber's parameter (number) is int, the decimal portion of the division is truncated, resulting in essentially a floor operation (forced round down). And we recursively call sumDigitsInNumber's, so we just keep "looping" that section of code. So for the second run, it is equivalent to sumDigitsInNumber(54), plus the additional 6 from the first run (6+sumDigitsInNumber(54)).
The second call returns 4+sumDigitsInNumber(54/10) by following the same logic as the first call. This is equivalent to 4+sumDigitsInNumber(5).
Then we run the whole process again, which returns 5+sumDigitsInNumber(5/10), equivalent to 5+sumDigitsInNumber(0).
The final call, sumDigitsInNumber(0), will return 0 because of the ternary operator in the return statement.
To expand this all out:
sumDigitsInNumber(546)
= 6+sumDigitsInNumber(546/10) = 6+sumDigitsInNumber(54)
= 6+(4+sumDigitsInNumber(54/10)) = 6+(4+sumDigitsInNumber(5))
= 6+(4+(5+sumDigitsInNumber(5/10))) = 6+(4+(5+sumDigitsInNumber(0)))
= 6+(4+(5+0))
= 6+(4+(5))
= 6+(9)
= 15

List iterator not incrementable assertion

The DoCollision function is a callback function which is checking for collisions every frame by iterating over a collider list.
void Collision::DoCollisions(Game *game){
for (ColliderList::const_iterator colliderAIt = colliders_.begin();
colliderAIt != colliders_.end();
colliderAIt++)
{
ColliderList::const_iterator colliderBIt = colliderAIt;
for (++colliderBIt; colliderBIt != colliders_.end(); ++colliderBIt)
{
Collider *colliderA = *colliderAIt;
Collider *colliderB = *colliderBIt;
if (CollisionTest(colliderA, colliderB))
{
game->DoCollision(colliderA->entity, colliderB->entity);
}
}
}
if collision test passes for any two game entities, game entity(Base class for all game objects) class destructor invoke function DestroyCollider which removes the respective collider elements from the list.
void Collision::DestroyCollider(Collider *collider){
colliders_.remove_if(std::bind1st((std::equal_to<Collider *>()), collider));
delete collider }
You're removing the element of a list that the iterator points to. That invalidates the iterator, meaning you're not allowed to use it anymore.
A typical remove loop for a list or vector looks like this:
for (auto iterator = list.begin(); iterator != list.end(); ) {
if (should_remove(iterator)) {
iterator = list.erase(iterator);
} else {
++iterator;
}
}
Note how, if an element is to be removed, the iterator is not incremented, but instead replaced with the result of the erase call.
You will have to find a way to refactor your code to match this pattern. This is complicated because your condition is deep within the collision function, but you can do either that (which has the advantage of making your code more efficient by getting rid of the linear search, by the way), or you can, instead of immediately removing the elements, collect them in a separate list, and then remove them after you're done iterating over the main list.
Or you can turn colliders_ into an intrusive list (e.g. from Boost.Intrusive, or hand-written). Intrusive lists are very good for situations like yours.

Why is the time complexity of this algorithm exponential?

During an interview, I was asked the time complexity of the following algorithm:
static bool SetContainsString(string searchString, HashSet<string> setOfStrings)
{
for (int i = 0; i < searchString.Length; i++)
{
var segment = searchString.Substring(0, i + 1);
if (setOfStrings.Contains(segment))
{
var remainingSegment = searchString.Substring(segment.Length);
if (remainingSegment == "") return true;
return SetContainsString(remainingSegment, setOfStrings);
}
}
return false;
}
I answered "linear" because it appears to me to loop only through the length of searchString. Yes, it is recursive, but the recursive call is only on the portion of the string that has not yet been iterated over, so the end result number of iterations is the length of the string.
I was told by my interviewer that the time complexity in the worst case is exponential.
Can anyone help me clarify this? If I am wrong, I need to understand why.
I believe that your interviewer was incorrect here. Here’s how I’d argue why the time complexity isn’t exponential:
Each call to the function either makes zero or one recursive call.
Each recursive call reduces the length of the string by at least one.
This bounds the total number of recursive calls at O(n), where n is the length of the input string. Each individual recursive call does a polynomial amount of work, so the total work done is some polynomial.
I think the reason your interviewer was confused here is that the code given above - which I think is supposed to check if a string can be decomposed into one or more words - doesn’t work correctly in all cases. In particular, notice that the recursion works by always optimistically grabbing the first prefix it finds that’s a word and assuming that what it grabbed is the right way to split the word apart. But imagine you have a word like “applesauce.” If you pull off “a” and try to recursively form “pplesauce,” you’ll incorrectly report that the word isn’t a compound because theres no way to decompose “pplesauce.” To fix this, you’d need to change the recursive call to something like this:
if (SetContainsString(...)) return true;
This way, if you pick the wrong split, you’ll go on to check the other possible splits you can make. That variant on the code does take exponential time in the worst case because it can potentially revisit the same substrings multiple times, and I think that’s what the interviewer incorrectly thought you were doing.

Is good to call function in other function parameter?

I suppose this:
public static string abc()
{
return "abc";
}
Is better to call this function in this way:
string call = abc();
Console.writeline(call);
Than this?
console.writeline(abc());
is there any reason to prefer one to the other?
Both are valid. However, out of experience I have concluded that the first option is more suitable for readability and ease of maintenance. I can't count how many times I have changed from the "compact" style to the first one as a help for a debugging session.
For example, this style makes it easy to check the correctness intermediate of an intermediate result:
string call = abc();
assert(!call.empty()); // Just an example.
Console.writeline(call);
Also, it helps to make the code more robust later, adding a conditional check before the subsequent action that checks call's value, for example if the design does not guarantee that the condition of the previous assert holds but you still need to check it.
string call = abc();
if (!call.empty())
{
Console.writeline(call);
}
Note also that with this style you will be able to easily inspect the value of call in your debugger.
Given your exact example (one parameter, value not used elsewhere, no side effects), it's just a matter of style. However, it gets more interesting if there are multiple parameters and the methods have side effects. For example:
int counter;
int Inc() { counter += 1; return counter }
void Foo(int a, int b) { Console.WriteLine(a + " " + b); }
void Bar()
{
Foo(Inc(), Inc());
}
What would you expect Foo to print here? Depending on the language there might not even be a predictable result. In this situation, assigning the values to a variable first should cause the compiler (depending on language) to evaluate the calls in a predictable order.
Actually I don't see a difference if you don't have any error checking.
This would make a difference
string call = abc();
# if call is not empty
{
Console.writeline(call);
}
The above method could avoid empty string being written.

Resources