I want to write a code to find a char array in another one and print out place(element) of first occur of first array. I wrote my own code and it works. But it "seems" kind of messy. Does anyone have better idea to rewrite this code?
"only strlen() is allowed. I need to write it by designing loops."
Here's the code
#include <iostream>
#include <string.h>
using namespace std;
const int len = 100;
int main() {
int i, j, k, l;
char a[len]="leonardo" , b[len]="nar";
bool es1 = false, es2=false;
i = 0;
while(i < len && !es1)
{
j = 0;
if(a[i] == b[j])
{
k = i+1;
l = j;
while (k < i+strlen(b) && !es2)
{
j = j+1;
if (a[k] == b[j]) k = k+1;
else es2 = true;
}
if (a[i+strlen(b)-1]==b[l+2] && !es2) es1 = true;
else i = i+1;
}
else i= i+1;
}
cout << endl << "element: " << i;
return 0;
}
By the way this not a real homework. I just make myself ready for a programming exam.
I just find out that the code doesn't work fine if array b[] is shorter than 3 elements. So it seems the code needs major review!
The easy way to do it would be to use std::search:
auto it = std::search(a, a + 8, b, b + 3));
Here, it points to the beginning of the found sequence in a, or to std::end(a) if not found.
This looks like substring search algorithm. You can use any of the recognized algorithms like KMP.
Can you use a string instead of a char array? If so, you can use string::find.
http://www.cplusplus.com/reference/string/string/find/
bool bFound = strA.find(strB)
Related
How do i make this?
image of my homework
note: Batasan means limitaion and Contoh means example
So, my professor wants me to do make output the same size horizontal and vertically in pattern shown in the image
I dont know what to do, but the best i can make is this:
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
const char * array1[4];
const char * array2[4];
array1[0] = "O", array1[1] = ">", array1[2] = "X", array1[3] = "<";
array2[0] = "v", array2[1] = "/", array2[2] = "^", array2[3] = "\\";
cin>>n;
for(int i = 1; i <= n; i++){
if (i%2 != 0){
for(int j = 0; j <=n; j++){
cout << array1[j];
}
cout<<"\n";
} else if (i%2 != 0) {
for(int j = 0; j <=n; j++){
cout << array2[j];
}
cout<<"\n";
}
return 0;
}
}
I dont know if array is necessary or not.
If you guys have any suggestion about my program feel free to give me some.
This is my first time asking in this web and im sorry if my post and english are terrible
Thanks in advance:)
We are here to help.
I will first show you the problems in your code and then make a proposal on how to make it better.
So, let us first check your code:
#include<bits/stdc++.h> is a non C++ compliant compiler extension. It should never be used. On my machine, it does not compile.
using namespace std; should not be used. It is better to always use full qualified names. This will avoid name clashes from different scopes or namespaces
Variables should have meaningful names. One character variables are in most cases not that good
All variables should be initialized during definition
C-Style arrays should not be used in C++. Always use a specialized STL container like std::vector or std::array
In C++ we use std::string for strings and not char[] or char *
Array indices in C/C++ start with 0. If you use <= in the end condition of a for loop, you will access an element one past the end. This is a severe out of bound error. You do that in you for loop with the 'j'
There is anyway a severe out of bound bug here. You access array[j] and j might be 4 or bigger. That is a bug and must be corrected. You can simply do a modulo devision % by 4. Then you do never exceed the 4. it will then always be 0,1,2,3,0,1,2,3,0,1,2,3 . . .
You should write as much as possible comments
If we correct all this findings, then we could come up with:
#include <array>
#include <iostream>
constexpr size_t NumberOfLinePatterns = 2;
constexpr size_t NumberOfElementsPerLinePattern = 4;
using Pattern = std::array<std::array<char, NumberOfElementsPerLinePattern>, NumberOfLinePatterns>;
// If you do not yet know the std::array. Then uncomment the following and
// remove on opening and closing curly brace in the initialization below
// using Pattern = char[NumberOfLinePatterns][NumberOfElementsPerLinePattern];
Pattern pattern{{
{'O','>','X','<'},
{'v','/','^','\\'}
}};
int main() {
// Get number of rows and columns to print
unsigned int numberOfElements{}; std::cin >> numberOfElements;
// Now, for all rows and columns
for (unsigned int row{}; row < numberOfElements; ++row) {
for (unsigned int column{}; column < numberOfElements; ++column) {
// Print the selected character
std::cout << pattern[row % NumberOfLinePatterns][column % NumberOfElementsPerLinePattern];
}
std::cout << '\n';
}
return 0;
}
I am trying to understand this recursion using the debugger and trying to understand it step by step the main.The debugger shows the smallAns returns the size of the array I can't understand how this smallAns is returning the size of the array input[].can anyone explain this
#include<iostream>
using namespace std;
int subsequences(char input[], int startIndex,char output[][50]){
if(input[startIndex] == '\0'){
output[0][0] = '\0';
return 1;
}
int smallAns = subsequences(input, startIndex+1, output);
for(int i = smallAns; i < 2*smallAns; i++){
int row = i - smallAns;
output[i][0] = input[startIndex];
int j = 0;
for(; output[row][j] != '\0'; j++){
output[i][j + 1] = output[row][j];
}
output[i][j + 1] = '\0';
}
return 2*smallAns;
}
int main(){
char input[] = "abc";
char output[100][50];
int ans = subsequences(input, 0, output);
for(int i = 0; i < ans; i++){
for(int j = 0; output[i][j] != '\0'; j++){
cout << output[i][j];
}
cout << endl;
}
}
Here's what the algorithm is doing:
Start at the end, with the empty subsequence (or "\0"). You have 1 subsequence.
Look at the last character not yet considered. For all the subsequences you have found, you can either add this last character, or don't. Therefore you have doubled the number of subsequences.
Repeat.
Therefore, 2 * smallAns means "Take the number of subsequences found in the lower recursive call, and double it." And this makes sense after you know how it was implemented. Thus the importance of comments and documentation in code. :)
The thing i want to do is compare two arrays, A and B, and post numbers from array B that doesn't appear in array A.
http://pastebin.com/u44DKsWf My full code.
Problem starts at line 42 i think.
int writingPosition = 1;
for (int c = 1; c<=firstArrayLength; c++)
{
for(int z = 1; z>secondArrayLength; z++)
{
if (firstArray[c] != secondArray[z])
{
thirdArray[writingPosition] = secondArray[z];
writingPosition++;
}
if (firstArray[c] == secondArray[z])
{
thirdArray[c] == '0'; // NEED FIXING I GUESS
}
}
}
The idea is that i mark numbers that dont fit my task as '0', so later on i can print array while ignoring 0.
Thank you!
You could use binary_search from algorithm module from C++ Standard Library.
Note this works with std::vector aswell.
Live demo
#include <array>
#include <iostream>
#include <algorithm>
int main()
{
std::array<int, 3> firstArray { 1, 3, 5 }; // stack based array like int[3]
std::array<int, 3> secondArray { 2, 3, 4 };
// Sort first array to be able to perform binary_search on it
std::sort(firstArray.begin(), firstArray.end());
for (const auto secondArrayItem : secondArray)
{
// Binary search is a very efficient way of searching an element in a sorted container of values
if (std::binary_search(firstArray.begin(), firstArray.end(), secondArrayItem) == false)
{
std::cout << "Item " << secondArrayItem << " does not exist in firstArray" << std::endl;
}
}
return 0;
}
Correction to your code should be somewhat like :
int writingPosition = 1;
for (int c = 1; c<=firstArrayLength; c++)
{
for(int z = 1; z<=secondArrayLength; z++)
{
if (firstArray[c] != secondArray[z])
{
thirdArray[writingPosition] = secondArray[z];
writingPosition++;
}
if (firstArray[c] == secondArray[z])
continue;
}
}
On a side note : Prefer using 0 as the base index for arrays.
There are many things wrong with your code.
Arrays of size s always range from 0 to s-1, so in your case you should use
for(int g = 0; g<50; g++)
i.s.o.
for(int g = 0; g<=50; g++)
and similar for the other arrays
Secondly, you fill the third array with char elements, and then compare them to int
thirdArray[c] == '0';
and later
if(thirdArray[g] != 0)
Either use '0' or 0 both times, but don't mix them up.
But the general algorithm doesn't make much sense either, you're overriding third array both based on index c as index z.
Also the range on z makes little sense.
(I assume this is homework or at least you're trying to study, so won't simply give a solution)
why don't you store the numbers that doesn't exist in a string and then you print the string from cout? this is how you can do this:
string output = "";
bool isFound = false;
for (int c = 1; c<=secondArrayLength; c++)
{
isFound = false;
for(int z = 1; z>firstArrayLength; z++)
{
if (secondArray[c] == firstArray[z])
{
isFound = true;
}
}
if(!isFound)
output+=(secondArray[c].str()+" ");
}
cout<<output;
try this it must work fine
This code works for me when I run it on my IDE, but it doesn't work on the website that has the exercise. I get a segmentation fault. So is this code correct? Did I make a mistake?
#include <iostream>
#include <string>
using namespace std;
string FirstReverse(string str) {
for (int i = 0, back = str.size()-1; i != back; ++i, --back)
{
char c = str[back];
str[back] = str[i];
str[i] = c;
}
return str;
}
int main() {
cout << FirstReverse("hello");
return 0;
}
Also, what's the best way to do this?
Your index only needs to reach half of the length, and that way we ensure that the swap between a pair only happens once:
for (int i = 0; i < str.size() / 2 ; i ++)
{
char c = str[str.size() - 1 - i];
str[str.size() - 1 - i] = str[i];
str[i] = c;
}
If you change the loop condition to "i <= back" then it won't cause segmentation fault. It is because when size-1 is even , i & back will never become equal. Thus loop will keep on going without breaking & attempt to access string member outside the string.
Just change your condition from != to <= and it will be solved.
I've done a program for string comparison with one mismatch at a programming website. It gives me wrong answer. I've working on it extensively but, I couldn't find testcases where my code fails. Can somebody provide me test cases where my code fails. I've done the comparison using Boyer Moore Horspool k-mismatches algorithm as it's the fastest searching algorithm
The code is as such
int BMSearch_k(string text, string pattern, int tlen, int mlen,int pos)
{
int i, j=0,ready[256],skip2[256][mlen-1],neq;
for(i=0; i<256; ++i) ready[i] = mlen;
for(int a=0; a<256;a++) {
for(i = mlen;i>mlen-k;i--)
skip2[i][a] = mlen;
}
for(i = mlen-2;i>=1;i--) {
for(j=ready[pattern[i]]-1;j>=max(i,mlen-k);j--)
skip2[j][pattern[i]] = j-i;
ready[pattern[i]] = max(i,mlen-k);
}
j = mlen-1+pos;
//cout<<"\n--jafffa--\n"<<pos<<"+"<<mlen<<"="<<j<<endl;
while(j<tlen+k) {
//cout<<"\t--"<<j<<endl;
int h = j;
i=mlen-1;
int neq=0,shift = mlen-k;
while(i>=0&&neq<=k) {
//cout<<"\t--"<<i<<endl;
if(i>=mlen-k)
shift = min(shift,skip2[i][text[h]]);
if(text[h]!= pattern[i])
neq++;
i--;
h--;
}
if(neq<=k)
return j-1;
j += shift;
}
return -1;
}
You aren't initialising your arrays correctly,
int i, j=0,ready[256],skip2[256][mlen-1],neq;
for(i=0; i<256; ++i) ready[i] = mlen;
for(int a=0; a<256;a++) {
for(i = mlen;i>mlen-k;i--)
skip2[i][a] = mlen;
}
On the one hand, you declare skip2 as a 256×(mlen-1) array, on the other hand, you fill it as a (mlen+1)×256 array.
In the next loop,
for(i = mlen-2;i>=1;i--) {
for(j=ready[pattern[i]]-1;j>=max(i,mlen-k);j--)
skip2[j][pattern[i]] = j-i;
ready[pattern[i]] = max(i,mlen-k);
}
you use ready[pattern[i]] before it has been set. I don't know if those mistakes are what's causing the failing testcase, but it's easily imaginable that they do.
If Daniel's suggestions do not solve the problem, here are a couple more things that look odd:
return j-1; // I would expect "return j;" here
This seems odd as if you have k=0,mlen=1, then the highest value that j can take is tlen+k-1, and so the highest return value is tlen-2. In other words matching a pattern 'a' against a string 'a' will not return a match at position 0.
Another oddity is the loop:
for(i = mlen-2;i>=1;i--) // I would expect "for(i = mlen-2;i>=0;i--)" here
it seems odd that in the preprocessing you will never access the first character in your pattern (i.e. pattern[0] is not read).