compiler is showing ArrayIndexOutOfBoundException...i guess my logic is wrong somewhere - search

static int binarySearch(int start, int end, int x, int[] arr) {
while (start <= end) {
int mid = (start + end) / 2;
if (x > arr[mid]) {
start = mid + 1;
} else if (x < arr[mid]) {
end = mid - 1;
} else {
return mid;
}
}
return -1;
}

Related

Hi, I wrote code in C++ fot linear search but it displays the index of searched elemet twice with second index value as random garbage value

Here is the code.what i did is implement linear search on some elements of the array and the push searched elements in stack,afterwards I print the popped elements from stack and print them.But in search function it displays two index values.
using namespace std;
int searched[10];
int stack[100], n=100, top=-1;
void push(int val) {
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
}
void pop() {
if(top<=-1)
cout<<"Stack Underflow"<<endl;
else {
cout<<"The popped element is "<< stack[top] <<endl;
top--;
}
}
void display() {
if(top>=0) {
cout<<"Stack elements are:";
for(int i=top; i>=0; i--)
cout<<stack[i]<<" ";
cout<<endl;
} else
cout<<"Stack is empty";
}
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
cout<<"The element is found at the index"<<i<<"\n\n";
return x;
}
int main(void)
{
int arr[15] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
int x = 0;
for(int i=0;i<8;i++)
{
x++;
int result = search(arr, n, x);
cout << "searched Element is " << result<<"\t\t";
push(result);
pop();
}
return 0;
}```
There are two issues that lead to this confusing result.
First, if I am not mistaken the search function, which was written like this:
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
cout<<"The element is found at the index"<<i<<"\n\n";
return x;
}
is parsed similarly to the following:
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++) {
if (arr[i] == x) {
cout<<"The element is found at the index"<<i<<"\n\n";
}
}
return x;
}
Presumably you meant this:
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++) {
if (arr[i] == x) {
cout<<"The element is found at the index"<<i<<"\n\n";
return x;
}
}
}
Second, since the global n starts at the value 100, the search loop runs off the end of the length 15 array, into other memory. This is probably undefined behavior.

C++ program to read a string and return the integer in it(negative ones and positive ones)

I am trying to write a c ++ program that read a string and print out all the integers that can be read in this string. For example if s="-1b34ggg--54-7-t--". the program should print : -1 34 -54 -7. Below is my code but it does not work. It just print out the positive integers.
#include<string>
using namespace std;
bool isNumber(string s)
{
for (int i = 0; i < s.length(); i++)
if (isdigit(s[i]) == false)
return false;
return true;
}
int main(void)
{
string s;
s="-1b34ggg--54-7-t--";
string temp="";
for(int i=0;i<s.length();i++)
{
if(isdigit(s[i]))
{
temp+=s[i];
}
else if(s[i]=='-')
{
if(isNumber(temp))
{
cout<<atoi(temp.c_str())<<" ";
temp="";
temp+=s[i];
}
else
{
temp="";
temp+=s[i];
}
}
else
{
if(isNumber(temp))
{
cout<<atoi(temp.c_str())<<" ";
}
temp="";
}
}
return 0;
}
s[0] can contain - or + sign. you did not check it.
bool isNumber(string s)
{
if (s.empty()) return false;
if ((s[0] == '-' || s[0] == '+') && s.length() == 1)
return false;
for (int i = 1; i < s.length(); i++)
if (isdigit(s[i]) == false)
return false;
return true;
}
Ok problem solved! Big thanks to Mushfiqur Rahman for helping. Code below.
#include<string>
using namespace std;
bool isNumber(string s)
{
if (s.empty()) return false;
if ((s[0] == '-' || s[0] == '+') && s.length() == 1)
return false;
for (int i = 1; i < s.length(); i++)
if (isdigit(s[i]) == false)
return false;
return true;
}
int main(void)
{
string s;
s="-1b34ggg--54-7-t--";
string temp="";
for(int i=0;i<s.length();i++)
{
if(isdigit(s[i]))
{
temp+=s[i];
}
else if(s[i]=='-')
{
if(isNumber(temp))
{
cout<<atoi(temp.c_str())<<" ";
temp="";
temp+=s[i];
}
else
{
temp="";
temp+=s[i];
}
}
else
{
if(isNumber(temp))
{
cout<<atoi(temp.c_str())<<" ";
}
temp="";
}
}
return 0;
}

my program does not continue compiling if I don't type any letter

I am solving the problem set1_ credit in cs50. the program woks fine, however after entering the credit card number, i need to enter any letter in the keyboard in order for the program to give me the answer.
here is my code
# include <cs50.h>
# include <stdio.h>
# include <math.h>
long credit(void);
int main(void)
{
long long num = credit();
long long num2 = num;
int c = log10(num), i, sum , sum1, sum2 = 0, digits[c], divid[c], remind[c], total[c], cards[c];
scanf("%d", &c);
for ( i = 0; i <= c ; i++)
{
digits[c-i] = num % 10;
num = num /10;
scanf("%d", &digits[c-i]);
}
if ( c % 2 != 0)
{
for ( i = 0 ; i <= c ; i++)
{
if ( i % 2 == 0 )
{
digits[i] = digits [i] * 2;
}
else
{
digits[i] = digits [i];
}
}
}
else
{
for ( i= 0 ; i <= c ; i++)
{
if ( i % 2 != 0)
{
digits [i] = digits[i] * 2;
}
else
{
digits[i] = digits[i];
}
}
}
for ( i = 0; i <= c; i++ )
{
remind[i] = digits[i] % 10;
}
//printf("\n");
for (i = 0; i <= c; i++)
{
divid[i] = digits[i] / 10;
}
for ( i = 0; i <= c; i++ )
{
total[i] = remind[i] + divid[i];
}
for ( i = 0; i <= c ; i++ )
{
sum = sum + total[i];
}
// recreate the card's number in a form of an array
for ( i = 0; i <= c ; i++)
{
cards[c-i] = num2 % 10;
num2 = num2 /10;
scanf("%d", &cards[c-i]);
}
// check the nature and the validity of a card
int cards1 = cards[1];
if (sum % 10 == 0 && cards[0] == 3)
{
if (c == 15 )
{
switch (cards [1])
{
case 4: printf("AMEX");
break;
case 7: printf("AMEX");
break;
}
}
//return 0;
printf("AMEX");
}
else if (cards[0] == 5 && sum % 10 == 0)
{
if (c == 16)
{
switch (cards [1])
{
case 1: printf("MASTERCARD");
break;
case 2: printf("MASTERCARD");
break;
case 3: printf("MASTERCARD");
break;
case 4: printf("MASTERCARD");
break;
case 5: printf("MASTERCARD");
break;
}
}
//return 0;
printf("MASTERCARD\n");
}
else if (cards[0] == 4 && sum % 10 == 0)
{
switch (c)
{
case 13: //printf("VISA\n");
break;
case 16: //printf("VISA\n");
break;
}
printf("VISA\n");
}
else
{
printf("INVALID\n");
}
printf("\n");
}
// get number of digits of an integer
long credit(void)
{
long long n;
do
{
n = get_long_long("Number: ");
}
while (log10(n) < 12 || log10(n) > 16);
return n;
}
I would be very grateful if anyone could help me solve this issue.
thanks in advance.
From man scanf:
The scanf() function reads input from the standard input stream stdin
The program is waiting for keyborad input (stdin) at one of the several scanf commands.
NB This question description is misleading because the program does compile, it (seemingly) stops running until keyboard input.

Find the word in the stream?

Given an infinite stream of characters and a list L of strings, create a function that calls an external API when a word in L is recognized during the processing of the stream.
Example:
L = ["ok","test","one","try","trying"]
stream = a,b,c,o,k,d,e,f,t,r,y,i,n,g.............
The call to external API will happen when 'k' is encountered, again when the 'y' is encountered, and again at 'g'.
My idea:
Create trie out of the list and navigate the nodes as you read from stream in linear time. But there would be a bug if you just do simple trie search.
Assume you have words "abxyz" and "xyw" and your input is "abxyw".In this case you can't recognize "xyw" with trie.
So search should be modified as below:
let's take above use case "abxyw". We start the search and we find we have all the element till 'x'. Moment you get 'x' you have two options:
Check if the current element is equal to the head of trie and if it is equal to head of trie then call recursive search.
Continue till the end of current word. In this case for your given input it will return false but for the recursive search we started in point 1, it will return true.
Below is my modified search but I think it has bugs and can be improved. Any suggestions?
#define SIZE 26
struct tri{
int complete;
struct tri *child[SIZE];
};
void insert(char *c, struct tri **t)
{
struct tri *current = *t;
while(*c != '\0')
{
int i;
int letter = *c - 'a';
if(current->child[letter] == NULL) {
current->child[letter] = malloc(sizeof(*current));
memset(current->child[letter], 0, sizeof(struct tri));
}
current = current->child[letter];
c++;
}
current->complete = 1;
}
struct tri *t;
int flag = 0;
int found(char *c, struct tri *tt)
{
struct tri *current = tt;
if (current == NULL)
return 0;
while(*c != '\0')
{
int i;
int letter = *c - 'a';
/* if this is the first char then recurse from begining*/
if (t->child[letter] != NULL)
flag = found(c+1, t->child[letter]);
if (flag == 1)
return 1;
if(!flag && current->child[letter] == NULL) {
return 0;
}
current = current->child[letter];
c++;
}
return current->complete;
}
int main()
{
int i;
t = malloc(sizeof(*t));
t->complete = 0;
memset(t, 0, sizeof(struct tri));
insert("weathez", &t);
insert("eather", &t);
insert("weather", &t);
(1 ==found("weather", t))?printf("found\n"):printf("not found\n");
return 0;
}
What you want to do is exactly what Aho-Corasick algorithm does.
You can take a look at my Aho-Corasick implementation. It's contest-oriented, so maybe not focused on readability but I think it's quite clear:
typedef vector<int> VI;
struct Node {
int size;
Node *fail, *output;
VI id;
map<char, Node*> next;
};
typedef pair<Node*, Node*> P;
typedef map<char, Node*> MCP;
Node* root;
inline void init() {
root = new Node;
root->size = 0;
root->output = root->fail = NULL;
}
Node* add(string& s, int u, int c = 0, Node* p = root) {
if (p == NULL) {
p = new Node;
p->size = c;
p->fail = p->output = NULL;
}
if (c == s.size()) p->id.push_back(u);
else {
if (not p->next.count(s[c])) p->next[s[c]] = NULL;
p->next[s[c]] = add(s, u, c + 1, p->next[s[c]]);
}
return p;
}
void fill_fail_output() {
queue<pair<char, P> > Q;
for (MCP::iterator it=root->next.begin();
it!=root->next.end();++it)
Q.push(pair<char, P> (it->first, P(root, it->second)));
while (not Q.empty()) {
Node *pare = Q.front().second.first;
Node *fill = Q.front().second.second;
char c = Q.front().first; Q.pop();
while (pare != root && !pare->fail->next.count(c))
pare=pare->fail;
if (pare == root) fill->fail = root;
else fill->fail = pare->fail->next[c];
if (fill->fail->id.size() != 0)
fill->output = fill->fail;
else fill->output = fill->fail->output;
for (MCP::iterator it=fill->next.begin();
it!=fill->next.end();++it)
Q.push(pair<char,P>(it->first,P(fill,it->second)));
}
}
void match(int c, VI& id) {
for (int i = 0; i < id.size(); ++i) {
cout << "Matching of pattern " << id[i];
cout << " ended at " << c << endl;
}
}
void search(string& s) {
int i = 0, j = 0;
Node *p = root, *q;
while (j < s.size()) {
while (p->next.count(s[j])) {
p = p->next[s[j++]];
if (p->id.size() != 0) match(j - 1, p->id);
q = p->output;
while (q != NULL) {
match(j - 1, q->id);
q = q->output;
}
}
if (p != root) {
p = p->fail;
i = j - p->size;
}
else i = ++j;
}
}
void erase(Node* p = root) {
for (MCP::iterator it = p->next.begin();
it != p->next.end(); ++it)
erase(it->second);
delete p;
}
int main() {
init();
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
string s;
cin >> s;
add(s, i);
}
fill_fail_output();
string text;
cin >> text;
search(text);
erase(root);
}

C, convert hex number to decimal number without functions

i'm trying to convert hexadecimal number to decimal number. What i've come up so far is:
#include <unistd.h>
#include <stdio.h>
long convert(char *input, short int *status){
int length = 0;
while(input[length])
{
length++;
}
if(length = 0)
{
*status = 0;
return 0;
}
else
{
int index;
int converter;
int result = 0;
int lastNumber = length-1;
int currentNumber;
for(index = 0; index < length; index++){
if(index == 0)
{
converter = 1;
}
else if(index == 1)
{
converter = 16;
}
else{
converter *= 16;
}
if(input[lastNumber] < 45 || input[lastNumber] > 57)
{
*status = 0;
return 0;
}
else if(input[lastNumber] > 45 && input[lastNumber] < 48)
{
*status = 0;
return 0;
}
else{
if(input[lastNumber] == 45)
{
*status = -1;
return result *= -1;
}
currentNumber = input[lastNumber] - 48;
result += currentNumber * converter;
lastNumber--;
}
}
*status = -1;
return result;
}
}
int main(int argc, char **argv)
{
char *input=0;
short int status=0;
long rezult=0;
if(argc!=2)
{
status=0;
}
else
{
input=argv[1];
rezult=convert(input,&status);
}
printf("result: %ld\n", rezult);
printf("status: %d\n", status);
return 0;
}
Somehow i always get resoult 0. Ia am also not allowed to use any other outher functions (except printf). What could be wrong with my code above?
This:
if(dolzina = 0)
{
*status = 0;
return 0;
}
is not merely testing dolzina, it's first setting it to 0. This causes the else clause to run, but with dolzina equal to 0 which is not the expected outcome.
You should just use == to compare, of course.

Resources