I have a doubt with the solution of this question which is stated below -
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Strings["aa", "ab"] should return false and strings["aa", "aab"] should return true according to question.
Here is the code which I have attempted in the first place and I'm not getting a required output as mentioned above.
unordered_map<char,int>umap;
for(char m:magazine)
{
umap[m]++;
}
for(char r:ransomNote)
{
if(umap.count(r)<=1)
{
return false;
}
else{
umap[r]--;
}
}
return true;
}
In the above code, I have used umap.count(r)<=1 to return false if there is no key present.
For the strings ["aa","aab"], it is returning true but for strings ["aa","ab"], it is also returning true but it should return false.
Then I used another way to solve this problem by using just umap[r]<=0 in the place of umap.count(r)<=1 and it is working just fine and else all code is same.
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char,int>umap;
for(char m:magazine)
{
umap[m]++;
}
for(char r:ransomNote)
{
if(umap[r]<=0)
{
return false;
}
else{
umap[r]--;
}
}
return true;
}
I'm not able to get what i'm missing in the if condition of first code. Can anyone help me to state what I'm doing wrong in first code. Any help is appreciated.
unordered_map::count returns the number of items with specified key.
As you don't use multi_map version, you only have 0 or 1.
Associated value doesn't change presence of key in map.
To use count, you should remove key when value reaches 0:
for (char r : ransomNote) {
if (umap.count(r) == 0) {
return false;
} else {
if (--umap[r] == 0) {
umap.erase(r);
}
}
}
return true;
Related
I'm working on a game and I'm trying to add collectables. I'm trying to remove the object from the list after the player has collided with it, but it ends up crashing and says:
Unhandled exception thrown: read access violation.
__that was 0xDDDDDDE9.
It says this on the for loop statement, but I think it has to do with the remove_if() function.
Here is my code:
for (sf::RectangleShape rect : world1.level1.brainFrag) {
collides = milo.sprite.getGlobalBounds().intersects(rect.getGlobalBounds());
if (collides == true) {
world1.level1.brainFrag.remove_if([rect](const sf::RectangleShape val) {
if (rect.getPosition() == val.getPosition()) {
return true;
}
else {
return false ;
}
});
brainFrag -= 1;
collides = false;
}
}
if (brainFrag == 0) {
milo.x = oldPos.x;
milo.y = oldPos.y;
brainFrag = -1;
}
I don't understand your approach, you loop the rects, then when you find the one you want to remove, you search for it again through list<T>::remove_if.
I think that you forgot about the fact that you can use iterators in addition to a range-based loop:
for (auto it = brainFrag.begin(); it != brainFrag.end(); /* do nothing */)
{
bool collides = ...;
if (collides)
it = world1.level1.brainFrag.erase(it);
else
++it;
}
This allows you to remove the elements while iterating the collection because erase will take care of returning a valid iterator to the element next to the one you removed.
Or even better you could move everything up directly:
brainFrag.remove_if([&milo] (const auto& rect) {
return milo.sprite.getGlobalBounds().intersects(rect.getGlobalBounds())
}
A side note: there's no need to use an if statement to return a boolean condition, so you don't need
if (a.getPosition() == b.getPosition()
return true;
else
return false;
You can simply
return a.getPosition() == b.getPosition();
After watching carefully the following code I can't see why the compiler is warning me with "warning: control reaches end of non-void function".
bool Foam::solidMagnetostaticModel::read()
{
if (regIOobject::read())
{
if (permeabilityModelPtr_->read(subDict("permeability")) && magnetizationModelPtr_->read(subDict("magnetization")))
{
return true;
}
}
else
{
return false;
}
}
I can't see where is the problem, the else statement should care for returning false in every case which the first if is not true.
Trace the code path when regIOobject::read() is true, but either of permeabilityModelPtr_->read(subDict("permeability")) or magnetizationModelPtr_->read(subDict("magnetization")) is false. In that case, you enter the top if block (excluding the possibility of entering its attached else block), but then fail to enter the nested if block:
bool Foam::solidMagnetostaticModel::read()
{
if (regIOobject::read())
{
// Cool, read() was true, now check next if...
if (permeabilityModelPtr_->read(subDict("permeability")) && magnetizationModelPtr_->read(subDict("magnetization")))
{
return true;
}
// Oh no, it was false, now we're here...
}
else
{
// First if was true, so we don't go here...
return false;
}
// End of function reached, where is the return???
}
The minimalist fix is to just remove the else { } wrapping, so any fallthrough ends up at return false;:
bool Foam::solidMagnetostaticModel::read()
{
if (regIOobject::read())
{
// Cool, read() was true, now check next if...
if (permeabilityModelPtr_->read(subDict("permeability")) && magnetizationModelPtr_->read(subDict("magnetization")))
{
return true;
}
// Oh no, it was false, now we're here...
}
// Oh, but we hit return false; so we're fine
return false;
}
Alternatively, avoid specifically mentioning true or false at all, since your function is logically just a result of anding three conditions together:
bool Foam::solidMagnetostaticModel::read()
{
// No need to use ifs or explicit references to true/false at all
return regIOobject::read() &&
permeabilityModelPtr_->read(subDict("permeability")) &&
magnetizationModelPtr_->read(subDict("magnetization"));
}
The nested if is the problem.
When that branch is not taken, there is no other paths to take
the else statement should care for returning false in every case which the first if is not true.
Correct, but what if the first if condition is true, but the second if condition is not?
That is: What if regIOobject::read() returns true, but permeabilityModelPtr_->read(subDict("permeability")) returns false?
Then the flow of control enters the first if block, does not return, but does not enter the else block (because the first condition was true), so it just falls off the end of the function without hitting a return statement.
If you want the else { return false; } part to apply to either condition, you could just naively copy/paste it:
if (COND1) {
if (COND2) {
return true;
} else {
return false;
}
} else {
return false;
}
But that's quite a bit of code duplication. A better solution is to replace the nested if by a single condition:
if (COND1 && COND2) {
return true;
} else {
return false;
}
There's still some duplication: Both branches consist of a return statement followed by some expression.
We can factor out the common parts (return) and push the condition into the expression:
return COND1 && COND2 ? true : false;
But ? true : false is redundant: If the condition is true, evaluate to true, else evaluate to false? Well, that's just what the condition itself does:
return COND1 && COND2;
Or with your concrete expressions:
return regIOobject::read()
&& permeabilityModelPtr_->read(subDict("permeability"))
&& magnetizationModelPtr_->read(subDict("magnetization"));
This might be a non-sense question, but i'm kind of stuck so I was wondering if someone can help. I have the following code:
bool while_condition=false;
do{
if(/*condition*/){
//code
}
else if(/*condition*/){
//code
}
else if(/*condition*/){
//code
}
...//some more else if
else{
//code
}
check_for_do_while_loop(while_condition, /*other parameters*/);
}while(while_condition);
the various if and else if exclude with each other but each have other if inside; if a certain condition is met (which can't be specified in a single if statement), then the code return a value and the do while loop is ended. But if, after entering a single else if, the conditions inside aren't met the code exit without actually doing nothing, and the while loop restart the whole.
I want the program to remember where he entered and avoid that part of the code, i.e. to avoid that specific else if he entered without any result, so he can try entering another else if. I thought about associating a boolean to the statements but I'm not quite sure on how to do it. Is there a way which allows me not to modify the code structure too much?
To give an idea of one way of approaching this that avoid loads of variables, here is an outline of how you might data-drive a solution.
class TestItem
{
public:
typedef bool (*TestFuncDef)(const state_type& state_to_test, std::shared_ptr<result_type>& result_ptr);
TestItem(TestFuncDef test_fn_parm)
{
test_fn = test_fn_parm;
already_invoked = false;
}
bool Invoke(const state_type& state_to_test, std::shared_ptr<result_type>& result_ptr)
{
already_invoked = true;
return test_fn(state_to_test, result_ptr);
}
bool AlreadyInvoked() const {return already_invoked; }
private:
TestFuncDef test_fn;
bool already_invoked;
};
std::shared_ptr<result_type> RunTest(std::list<TestItem>& test_item_list, state_type& state_to_test)
{
for(;;) {
bool made_a_test = false;
for (TestItem& item : test_item_list) {
std::shared_ptr<result_type> result_ptr;
if (!item.AlreadyInvoked()) {
made_a_test = true;
if (item.Invoke(state_to_test, result_ptr)) {
return result_ptr;
}
else
continue;
}
}
if (!made_a_test)
throw appropriate_exception("No conditions were matched");
}
}
This is not supposed to be a full solution to your problem but suggests another way of approaching it.
The important step not documented here is to build up the std::list of TestItems to be passed to RunTest. Code to do so might look like this
std::list<TestItem> test_item_list;
test_item_list.push_back(TestItem(ConditionFn1));
test_item_list.push_back(TestItem(ConditionFn2));
The definition of ConditionFn1 might look something like
bool ConditionFn1(const state_type& state_to_test, std::shared_ptr<result_type>& result_ptr)
{
// Do some work
if (....)
return false;
else {
result_ptr.reset(new result_type(some_args));
return true;
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Sorry if this question is not suited for SO.
I have a C++ function that approximately looks like MyFun() given below.
From this function I am calling some(say around 30) other functions that returns a boolean variable (true means success and false means failure). If any of these functions returns false, I have to return false from MyFun() too. Also, I am not supposed to exit immediately (without calling the remaining functions) if an intermediate function call fails.
Currently I am doing this as given below, but feel like there could be a more neat/concise way to handle this. Any suggestion is appreciated.
Many Thanks.
bool MyFun() // fn that returns false on failure
{
bool Result = true;
if (false == AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (false == AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
// Repeat this a number of times.
.
.
.
if (false == Result)
{
cout << "Some function call failed";
}
return Result;
}
I would replace each if statement with a more coincise bitwise AND assignment:
bool MyFun() // fn that returns false on failure
{
bool Result = true;
Result &= AnotherFn1(); // Another fn that returns false on failure
Result &= AnotherFn2(); // Another fn that returns false on failure
// Repeat this a number of times.
.
.
.
if (false == Result)
{
cout << "Some function call failed";
}
return Result;
}
Use something like a std::vector of std::function. It is a lot more maintenable.
Example: http://ideone.com/0voxRl
// List all the function you want to evaluate
std::vector<std::function<bool()>> functions = {
my_func1,
my_func2,
my_func3,
my_func4
};
// Evaluate all the function returning the number of function that did fail.
unsigned long failure =
std::count_if(functions.begin(), functions.end(),
[](const std::function<bool()>& function) { return !function(); });
If you want to stop when a function fail, you just have to use std::all_of instead of std::count_if. You dissociate the control flow from the function list and that is, in my opinion, a good thing.
You can improve this by using a map of function with name as key that will allows you to output which function failed:
std::map<std::string, std::function<bool()>> function_map;
bool MyFun() // fn that returns false on failure
{
bool Result = true;
// if need to call every function, despite of the Result of the previous
Result = AnotherFn1() && Result;
Result = AnotherFn2() && Result;
// if need to avoid calling any other function after some failure
Result = Result && AnotherFn1();
Result = Result && AnotherFn2();
return Result;
}
Instead of
if (false == AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (false == AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
if (false == AnotherFn3()) // Another fn that returns false on failure
{
Result = false;
}
begin to use booleans as what they are, truth values:
if (!AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (!AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
if (!AnotherFn3()) // Another fn that returns false on failure
{
Result = false;
}
Then, all those conditions have the same code; they are basically part of one big condition:
if ( !AnotherFn1()
| !AnotherFn2()
| !AnotherFn3())
{
Result = false;
}
For your specific problem, where you want all functions be called, even if you know early you'll return false, it is important to not use the short circuiting operators && and ||. Using the eager bitwise operators | and & is really a hack, because they are bitwise and not boolean (and thus hide intent), but work in your situation iff AnotherFn? return strict bools.
You can negate what you do inside; less negations yield better code:
Result = false;
if ( AnotherFn1()
& AnotherFn2()
& AnotherFn3())
{
Result = true;
}
and then you can rid these assignments and instead return straightly:
if ( AnotherFn1()
& AnotherFn2()
& AnotherFn3())
{
return true;
}
cout << "something bad happened";
return false;
Summary
Old:
bool MyFun() // fn that returns false on failure
{
bool Result = true;
if (false == AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (false == AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
// Repeat this a number of times.
.
.
.
if (false == Result)
{
cout << "Some function call failed";
}
return Result;
}
New:
bool MyFun() // fn that returns false on failure
{
if (AnotherFn1() &
AnotherFn2() &
AnotherFn3())
{
return true;
}
cout << "Some function call failed";
return false;
}
There are more possible improvements, e.g. using exceptions instead of error codes, but don't be tempted to handle "expections" instead.
! can be used as a cleaner alternative to false
Like this:
bool MyFun() // fn that returns false on failure
{
bool Result = true;
if (!AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (!AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
// Repeat this a number of times.
.
.
.
if (!Result)
{
cout << "Some function call failed";
}
return Result;
}
how about using exceptions to handle failure:a neat exemple
the main question is, are the function call interdependant or not? can some be skipped if a previous one failed? ...
i have problems with the array function.. -
i put my mac on fist line and then says me approved , but if is on 2st line rejected. my real one is B6 on end. /address down are not real../
in heder file settings >
#define CLIENTSNUMBER 2
BOOL Checking2(LPCSTR MacID);
cpp >
char ClientMacs[CLIENTSNUMBER*1][18] = {
"5A-77-77-97-87-B7",
"5A-77-77-97-87-B6"
};
BOOL Checking2(LPCSTR MacID)
{
for(int x=0;x<CLIENTSNUMBER;x++)
{
if(!strcmp(MacID,ClientMacs[x]))
{
MessageBoxA(NULL,MacID,"APPROVED!",MB_OK);
return false;
} else {
MessageBoxA(NULL,MacID,"REJECTED!",MB_OK);
return false;
}
}
return false;
}
Because you return from your function (breaking out of your loop) when something matches or doesn't match. It will never actually loop.
Edit because it's a slow morning:
You need to go through the entire array and look at every element for a match before declaring it's rejected:
BOOL Checking2(LPCSTR MacID)
{
for(int x=0;x<CLIENTSNUMBER;x++)
{
if(strcmp(MacID,ClientMacs[x]) == 0)
{
MessageBoxA(NULL,MacID,"APPROVED!",MB_OK);
return false;
}
}
MessageBoxA(NULL,MacID,"REJECTED!",MB_OK);
return false;
}
Also, do you really mean to return false in both cases? I would assume if you find a match it should return true