Comparing indexes in arrays/vectors - c++

I just completed a project through Codecademy, and I couldn't for the life of me figure it out. I went and looked at the example solution and it contained code that I didn't even know you could do and I cannot figure out how it works.
There is a nested for loop, and the user takes advantage of adding the indexes together?? Or is comparing them?? I've just never seen it done, to be quite honest and I have looked for an explanation of what exactly is happening and I can't find one.
`
for (int i = 0; i < text.size(); ++i) {
int match = 0;
for (int j = 0; j < word.size(); ++j) {
if (text[i+j] == word[j]) {
++match;
}
}
`
The project was a C++ program where you had to bleep a word out of any phrase that was input into the program. I just don't understand what "text[i+j]" accomplishes? How do you add two indexes together in a for loop?? Does it add?? Does it compare?? But comparison doesn't make much sense to me either??
Here is a link to the github repository as well, so you can see the entire program: https://github.com/Codecademy/learn-cpp/tree/master/8-references-and-pointers/bleep

Since you're learning, the easiest way to figure this out is to write out exactly what is happening. Take text=="Hello, World and word=="World", and work out on paper how this code runs. For what values of i and j will match be incremented?

Related

Merge Sort With String Vectors C++

Hello all I am a noob to recursion and I'm feeling like banging my head against the wall. I watched some videos, read the chapter and have been trying to figure out the answer to this problem for over 6 hours now with no luck. My professor gave us the following code and we have to mod it from there. Note: We are reading 52k words from a file and then sorting them using this algorithm. Not sure if that matters but thought I would add the info just in case.
include
using namespace std;
vector<int> MergeUsingArrayIndices(const vector<int> & LHS,
const vector<int> & RHS)
{
vector<int> ToReturn;
int i = 0; // LHS index
int j = 0; // RHS index
while ((i < LHS.size()) && (j < RHS.size()))
{
if (LHS[i] < RHS[j])
{
ToReturn.push_back(LHS[i]);
++i;
}
else
{
ToReturn.push_back(RHS[j]);
++j;
}
}
while (i < LHS.size())
{
ToReturn.push_back(LHS[i]);
++i;
}
while (j < RHS.size())
{
ToReturn.push_back(RHS[j]);
++j;
}
return ToReturn;
}
Except now we have to make this work from just a single vector. This is what I have so far.
vector<string> MergeUsingArrayIndices(vector<string> & LHS,
int START, int MID, int MIDPLUSONE, int END)
{
vector<string> ToReturn;
int i = 0; // LHS index
int j = MIDPLUSONE; // RHS index
while ((i <= MID) && (j <= END))
{
if (LHS[i] < LHS[j])
{
ToReturn.push_back(LHS[i]);
++i;
}
else
{
ToReturn.push_back(LHS[j]);
++j;
}
}
while (i <= MID)
{
ToReturn.push_back(LHS[i]);
++i;
}
while (j <= END)
{
ToReturn.push_back(LHS[j]);
++j;
}
for (int k = 0; k < ToReturn.size(); ++k)
{
LHS[k] = ToReturn[k];
}
return ToReturn;
}
Plus this is the call prior to the function.
void MergeSort(vector<string> & VECTOR, int START, int END)
{
if (END > START)
{
int MID = (START + END) / 2;
MergeSort(VECTOR, START, MID);
MergeSort(VECTOR, MID + 1, END);
MergeUsingArrayIndices(VECTOR, START, MID, (MID+1), END);
}
}
void Merge(std::vector<string> & VECTOR)
{
MergeSort(VECTOR, 0, VECTOR.size()-1);
}
Console Screen Shot
Basically it is sorting but not very well since not everything is in alphabetical order. That was just a small sample of words from the list.
Thank you and best regards,
DON'T GET MARRIED.
UPDATE FOR: PNKFELIX
It tried the following;
vector<string> ToReturn;
int i = START; // LHS index
int j = MIDPLUSONE; // RHS index
while (i <= MID && j <= END)
{
if (LHS[i] <= LHS[j])
{
ToReturn[START] = LHS[i];
//ToReturn.push_back(LHS[i]);
++START;
++i;
}
and so on but this made the code worse so I am sure that is not what you were referring to. I have been up for days trying to figure this out and I cannot sleep......
The one thing you pointed to that is bothering me because I see why it's not happening but cannot fix is the call
I'm guessing that is why you used the apple, pear, orange, banana example. (very clever by the way). You can lead a horse to water but cannot make it drink. However, I still do not see how to fix this? I tried replacing my i = 0; with i = START as I now see this is probably the culprit when comparing the right side since it should start at that position but it actually made my code worse? What else am I missing here?
I have so much going on and cannot stand it when professors do stuff like this (my community college isn't great for CIS and my professor has never taught this class before). I cannot rest until I figure it out but the textbook is so far above my head (the professor even apologized for the textbook at the beginning of the semester saying it was too advanced for us but it is what they gave him) and uses a totally different approach (two separate arrays instead of one vector). What am I supposed to do with START? I have spent so much time on this and am dying to know the answer. Maybe that makes me lazy but there is a point where you can only think about something so much. I love to learn but this is not learning as I've hit my limit. I am missing something and don't know how to begin desk checking what it is. I am assuming the right hand side of each vector comparison is not sorted but how do I fix that? Is it because start is not always zero (example: for the right hand side )? I am not good at sorting algorithms (because I am not very bright (although I study allot)) as it is, and this is a new twist. It's like handing someone a bubble sort that is broken and asking them to desk check it, fix whats wrong with it, and make it more efficient yet they've never seen one working before.
The nice thing about a problem like this is that there's nothing specific to C++ here. One can take the proposed code and port it to pretty much any other reasonable language (e.g. JavaScript) and then debug it there to determine what is going wrong.
A good practice in any program is to document the assumptions and invariants of the code. If these invariants are simple enough, you can even check that they hold within the code itself, via assert statements.
So, lets see: from looking at how MergeUsingArrayIndices is invoked by MergeSort, it seems like your approach is a recursive divide-and-conquer: You first divide the input in two at a midpoint element, sort each side of the divided input, and then merge the two parts.
From that high-level description, we can identify a couple of invariants that must hold on entry to MergeUsingArrayIndices: the left half of LHS must be sorted, and the right half of LHS must also be sorted. We can check that these two conditions hold as we merge the vector, which may help us identify the spot where things are going wrong.
I took the original code and ported it as faithfully as I could to Rust (my preferred programming language), then added some assertions, and some print statements so that we can see where the assertions fail.
(There was one other change I forgot to mention above: I also got rid of the unused return value from MergeUsingArrayIndices. The array you're building up is solely used as temporary storage that is later copied into LHS; you never use the return value and therefore we can just remove that from the function's type entirely.)
Here is that code in a running playpen:
https://play.rust-lang.org/?gist=bd61b9572ea45b7139bf081cb51dc491&version=stable&backtrace=0
Some leading questions:
What indices is the assertion comparing when it reports that LHS[i] is in fact not less than LHS[i+1]?
The printouts report when the vector should be sorted at certain subranges: 0...0, 1...1, 0...1, et cetera. The indices you found above (assuming they are the same as the ones I found) are not within one of these subranges; so we in fact do not have a justification for trying to claim that LHS[i] is less than LHS[i+1]! So what happened, why does the code think that they should fall into a sorted subrange of the vector?
Strong hint number one: I left on a warning that the compiler issues about the code.
Strong hint number two: Try doing the exercise I left in the comment above the MergeUsingArrayIndices function.
Use strcmp(LHS[i],LHS[j])<0 in if condition

LeetCode Word Break, fail on Online Judge but pass Online test

I met a problem when I was doing leetcode 139, word break.
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. (each dictionary word can be used multiple times.)
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
I use basic dynamic programming algorithm, but may implement it in a different way from the popular one on the internet.
Here is the code:
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
int strlen = s.length();
if(0 == strlen) return true;
vector<bool> sepable(false, strlen);
for(int i = 0; i < strlen; ++i) {
if(wordDict.count(s.substr(0,i+1)) > 0) {
sepable[i] = true;
continue;
}
for(int j = 0; j < i; ++j) {
if(sepable[j] && wordDict.count(s.substr(j+1,i-j)) > 0) {
sepable[i] = true;
break;
}
}
}
return sepable[strlen-1];
}
};
When I ran online judge, it fails at the test:" "aaaaaaa" ["aaaa","aa"]", my code output true, the expected answer is false. However, if I run it on online test, it gives the right output. Also, it works fine on my own virtual machine with clang++.
The difference between online judge and online test is that each online test is only one test. Online judge contains many tests and will fail if anyone of the tests fails. So the problem of my code may lay like this: at some test other than the "aaaaaaa", it gives the right output but cause some potential problem. And that is why my code will fail on "aaaaaaa". However, if I just run this single test, it is fine.
The leetcode website says it may because my code has some undefined behaviors. The previous test case may influence the latter one. I don't know what are all the previous test case and didn't expect anyone here know about it. But I think as long as there are problems in my code, someone can find it.
I think the question is pretty clear this time.
this line parameters are of wrong order vector<bool> sepable(false, strlen); it should be vector<bool> sepable(strlen,false);the length of the vector comes first then the default value and false is implicitly converted to int so the length is set to 0 that gave the undefined behavior

Output 4 set of 7 ascendant ordered and unique random numbers

I'm having some difficulty figuring out how to solve my issue here, and I thought why not go here and ask you professionals for some help.
The main thing is, I've only been studying C++ for a few weeks in School, and roughly what
I've been going through are if/else, for/while/do loops, arrays and obviously some more basic stuff, so my main problem while trying to solve this is whether or not my knowledge is enough?
Would this be easier solved if I read on about vectors etc?
Now, what I have been successful of doing is sorting the numbers which I solved like this:
Basically what I used is an bubble sort algorithm (I think?)
for(int i=0; i<6; i++)
{
for(int j=0; j<6; j++)
{
if(slump[j]>random[j+1])
{
temp = random[j];
slump[j] = random[j+1];
slump[j+1] = random;
}
}
}
However I can't for the life of me figure out how to prevent duplicates from appearing (there can be duplicates from row to row but not on the same row) when assigning each index from 0-6 a random number.
for(int j=0;j<7;j++)
{
random[j] = rand()%40+1;
}
I hope I've made myself somewhat clear, as English isn't my native language, please do tell me if I need to clarify anything. And I do hope I can find some help on how to solve this, with a not too complex solution here.
The sorting procedure will not help you to prevent duplicates, so it must be resolved before.
First you ensure that there are no duplicated numbers. When you get all the numbers you need.
To ensure that there are no random numbers, two options:
After each number is generated, check against the numbers already obtained. If it is repeated, discard it and get a new random number.
Since you want 7 numbers in a 40 wide range, just use it as an order. The first number is picked between 0-39, the second number between 0-38, and so on. Already used numbers are skipped (so, a random sequence of 3-5-2-4 means the number sequence 3-6-2-7)
Umm, it shouldn't be too hard to check for duplicates.
You could try the following for instance:
for (int i = 0; i < 7; i++)
{
random[i] = rand%40 + 1;
}
for (int i = 0; i < 7; i++)
{
for (int j = 1; j < 7; j++)
{
if(random[i] == random[j])
{
random[i] = rand%40 + 1;
i = i -1;
break;
}
}
}
I'm pretty sure that should be a profecceint check for whether or not a number has been repeated in random[]. Also, even though vectors are more fun and somewhat easier to use they will not make this operation easier.
Hope it helps. =)

Issues of getting stuck into infinite loop while iterating through vectors

I want to search through a vector of pairs and in order to do so..i am doing the following:
vector<pair<double ,double> > vec_pairs;
for(vector<unsigned int>::size_type j = 0; j != vec_pairs.size(); j++ )
{
if(vec_pairs[j].first==12.6)
{
int z=7;
continue;
}
}
However my problem is...upon doing this...i am getting stuck in an infinite loop...
Can anyone help me in resolving the problem
First of all, the code that you posted works well 'as it is'.
The only reason for such type of a code to go into infinite loop is to modify j inside the loop.
If you increase j inside the loop, you will probably not get stuck because you will go out of bonds and might have your code crash.
for(vector<unsigned int>::size_type j = 0; j != vec_pairs.size(); j++ )
{
if(vec_pairs[j].first==12.6)
{
j++;//You will go out of vector bonds and might get an error here.
continue;
}
}
However, if you do something like this:
for(vector<unsigned int>::size_type j = 0; j != vec_pairs.size(); j++ )
{
if(vec_pairs[j].first==12.6)
{
j--;//j is decreased each time you get in here, so you will be stuck on one element,
continue;
}
}
Then you will get stuck inside, because when you go into the if statement (say, on element 7), j will decrease to 6, then you will continue the loop, j will increase back to 7, you will go inside the if again, and so on.
I have tested your code in codepad. Check it here! And it is working fine. Check the value of the variable j while debugging. As SingerOftheFall said, It might be getting decremented or reset somewhere. It can also go on an infinite loop if you are adding elements inside the loop which increase the value of vec_pairs.size() and the condition j != vec_pairs.size() will never be true in that case. Can't find anything wrong in the code you given.

Why am I getting this output?

Alright so I writing Conways Game of Life in C++, and so far I have only created the rule that allows users to create cells if it has 3 neighbors.
Here is the current code: http://tinypaste.com/f59b4463
When I launched the program I entered in the coordinates so that I would have the gameboard depicted in the photo below, and the output wasn't what I expected, it should have made it so that the cell 2,1 would be alive, but in the output it remained dead. I am not sure why it is not working. Any help?
Input & Output: http://i.imgur.com/1Mvhi.png
Several things to address, and while this is not an answer, it's too big for a comment. Please fix these then I will get back to you...
In gameboard() please arrange the code so that it consists of two for loops instead of all the couts. Example:
int i, j;
for (i = j = 0; i < 10; i++) {
for (; j < 10; j++) {
cout << world[i][j];
}
}
it's much more concise.
Second, in cells(), in the second for loop, you can use another nested for loop.
Third, I would avoid naming normal variables in ALL CAPS since that is generally reserved for preprocessor #defines.
K, enjoy cleaning up :)
Alright. It's an algorithmic issue. When you call calculate, it creates extra cells because it's not exactly one generation. It's a mix of two and three - it acts on cells you just created. Get what I'm saying? I explained this on GMail.