File not loading properly in C - c

I'm trying to compare a string using a pointer to the array and the destination as defined.
string destination;
int flightcompare(Flights FDA[], String destination)
{
int j=0;
Flights founddestination[10];
for (int i=0;i<MAXARRAYSIZE;i++)
{
(strcmp(Flight *FDA[i]->destination,destination)==0);
founddestination[j]= FDA[i];
j++;
}
return 1;
}

I am not sure about the programming language but I am assuming it is one with stringas a data type.
In your code, there's a Semicolon at the end of
strcmp(Flight *FDA[i]->destination,destination)==0);
which makes use of strcmpredundant.
Remove that Semicolon.
Plus You don't need to pass Flight*to strcmp
So, With these modifications, Function should look like:
int flightcompare(Flights FDA[], String destination)
{
int j=0;
Flights founddestination[10];
for (int i=0;i<MAXARRAYSIZE;i++)
{
if(strcmp(FDA[i]->destination,destination)==0)
{
founddestination[j]= FDA[i];
j++;
if(j >= 10)
{
break; // Stop Looping as Array is full
}
}
}
return j; // Return Count of the Flights found.
}

your strcmp line doesn't make any sense, cause you're not checking the boolean value which is the result of your comparison.
In general, it should be put in an if statement.
There's another problem though since there's no need to compare string objects with strcmp.
You can just compare them with operator ==.
if (FDA[i].destination == destination) {
// they're equal -> do something
} else {
// they're not equal -> do something else
}
That's assuming Flights type has a 'destination' public member.
Moreover, why put them in the founddestination array if you're not using it? and what is the purpose of returning an int?
If you want to know if there's any mismatching destination you can return a boolean.
If you want to return the number of equal destinations / non equal destinations you can just count them in an int.
Assuming you aim for the boolean solution i'd write:
bool flightcompare(Flights FDA[], String destination) {
for (int i = 0; i < MAXARRAYSIZE; ++i) {
if (FDA[i].destination != destination) {
return false;
}
}
return true;
}
If you want to return the amount of matching flights i'd write:
int flightcompare(Flights FDA[], String destination) {
int count = 0;
for (int i = 0; i < MAXARRAYSIZE; ++i) {
if (FDA[i].destination == destination) {
++count;
}
}
return count;
}

Related

Knuth Morris Pratt Algorithm, keep getting error "control reaches end of non-void function"

Code keeps returning the error "control reaches end of non-void function".
The source of the error is probably: int lps[M] but I can't figure out how to fix it. I tried to assign value to it but the error is still there.
EDIT: sorry about the return -1; thing. Fixed that but the error I'm trying to fix is still there.
int knuth(char *string, char * pattern){
int M = strlen(string);
int N = strlen(pattern);
int lps[M];
if (string == NULL)
{
return -1;
}
else {
int i = 0;
int j = 0;
while (i < N) {
if (string[j] == pattern[i]) {
j++;
i++;
}
if (j == M) {
//printf("Found stringtern at index %d ", i - j);
j = lps[j - 1];
return i - j;
} else if (i < N && string[j] != pattern[i]) {
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
return i - j;
}
}
}
Ignoring all other potential problems in this function, the compiler is rightfully complaining that not all code paths return a value. You have declared the knuth function to return an int, yet it's possible for logic in your function to reach the end without returning a value. If you go down one of those paths, the function will return an indeterminate value, and if the caller uses that value, it will invoke undefined behavior. See the condensed version of your function below:
int knuth(char *string, char * pattern){
if (string == NULL)
{
return -1; // ok, here's a return, but it's conditional on string == NULL
}
else {
while (...) {
if (...) {
return i - j; // here's another return, also conditional
} else if (...) {
}
return i - j; // here's the final return in your function, which is
// conditional on entering the while loop
}
// what if you get here (ie, the condition of the while loop was false)?
// The function returns nothing, this is what the compiler is warning
// you about.
}
// Here is logically the same as at the end of the else block .. also no return
}
As I mentioned in my comment, there's no point to the while loop, since you unconditionally return from it at the end of the first iteration. That means the loop is guaranteed to only execute once, eliminating the need for a loop all together. Your logic can be simplified, at least with a method as below:
int knuth(char *string, char * pattern){
int i=0, j=0;
if (string == NULL)
{
return -1; // ok, here's a return, but it's conditional on string == NULL
}
else if (i < N) {
// if i < N, do whatever manipulations you want as before
if (...) {
// return i - j; // really no need to return i-j here, we'll do that
// at the end now
} else if (...) {
}
}
// now at the very end of the function, this will unconditionally return
return i - j;
}
However, I suspect you actually want to loop, in which case your logic should be something like
int knuth(char *string, char * pattern){
int i=0, j=0;
if (string == NULL)
{
return -1;
}
else
{
while (i < N)
{
// ... do your operations. Be _very_ careful to increment
// i appropriately (probably each time thru the loop), otherwise
// you'll get an infinite loop here. I see a conditional
// mutation of i in your OP, which makes me nervous.
}
// since this is the end of an else block, we can return here
//return i - j;
}
// but IMO it's clearer to return here. It's up to you, depending on
// where you want to scope i and j
return i - j;
}
Your code falls off the end of the function when string == NULL.
This writing style is old; typically we would not write
if(string != NULL)
{
/* Entire body logic */
}
but rather we would now write
if(string == NULL)
{
/* handle input error and return; or do we do string = ""; */
}
You will find this mistake more easily avoided by using the modern style. It has been pointed out to me that string can't be NULL here because of the strlen(string) call above. While such a platform does exist where strlen() checks for NULL, depending on that behavior is unwise, and the check should be moved before the strlen(string) call.
Nobody believes in single return anymore, which was the only real reason for the old style.

Check if Char Array contains special sequence without using string library on Unix in C

Let‘s assume we have a char array and a sequence. Next we would like to check if the char array contains the special sequence WITHOUT <string.h> LIBRARY: if yes -> return true; if no -> return false.
bool contains(char *Array, char *Sequence) {
// CONTAINS - Function
for (int i = 0; i < sizeof(Array); i++) {
for (int s = 0; s < sizeof(Sequence); s++) {
if (Array[i] == Sequence[i]) {
// How to check if Sequence is contained ?
}
}
}
return false;
}
// in Main Function
char *Arr = "ABCDEFG";
char *Seq = "AB";
bool contained = contains(Arr, Seq);
if (contained) {
printf("Contained\n");
} else {
printf("Not Contained\n");
}
Any ideas, suggestions, websites ... ?
Thanks in advance,
Regards, from ∆
The simplest way is the naive search function:
for (i = 0; i < lenS1; i++) {
for (j = 0; j < lenS2; j++) {
if (arr[i] != seq[j]) {
break; // seq is not present in arr at position i!
}
}
if (j == lenS2) {
return true;
}
}
Note that you cannot use sizeof because the value you seek is not known at run time. Sizeof will return the pointer size, so almost certainly always four or eight whatever the strings you use. You need to explicitly calculate the string lengths, which in C is done by knowing that the last character of the string is a zero:
lenS1 = 0;
while (string1[lenS1]) lenS1++;
lenS2 = 0;
while (string2[lenS2]) lenS2++;
An obvious and easy improvement is to limit i between 0 and lenS1 - lenS2, and if lenS1 < lenS2, immediately return false. Obviously if you haven't found "HELLO" in "WELCOME" by the time you've gotten to the 'L', there's no chance of five-character HELLO being ever contained in the four-character remainder COME:
if (lenS1 < lenS2) {
return false; // You will never find "PEACE" in "WAR".
}
lenS1minuslenS2 = lenS1 - lenS2;
for (i = 0; i < lenS1minuslenS2; i++)
Further improvements depend on your use case.
Looking for the same sequence among lots of arrays, looking for different sequences always in the same array, looking for lots of different sequences in lots of different arrays - all call for different optimizations.
The length and distribution of characters within both array and sequence also matter a lot, because if you know that there only are (say) three E's in a long string and you know where they are, and you need to search for HELLO, there's only three places where HELLO might fit. So you needn't scan the whole "WE WISH YOU A MERRY CHRISTMAS, WE WISH YOU A MERRY CHRISTMAS AND A HAPPY NEW YEAR" string. Actually you may notice there are no L's in the array and immediately return false.
A balanced option for an average use case (it does have pathological cases) might be supplied by the Boyer-Moore string matching algorithm (C source and explanation supplied at the link). This has a setup cost, so if you need to look for different short strings within very large texts, it is not a good choice (there is a parallel-search version which is good for some of those cases).
This is not the most efficient algorithm but I do not want to change your code too much.
size_t mystrlen(const char *str)
{
const char *end = str;
while(*end++);
return end - str - 1;
}
bool contains(char *Array, char *Sequence) {
// CONTAINS - Function
bool result = false;
size_t s, i;
size_t arrayLen = mystrlen(Array);
size_t sequenceLen = mystrlen(Sequence);
if(sequenceLen <= arrayLen)
{
for (i = 0; i < arrayLen; i++) {
for (s = 0; s < sequenceLen; s++)
{
if (Array[i + s] != Sequence[s])
{
break;
}
}
if(s == sequenceLen)
{
result = true;
break;
}
}
}
return result;
}
int main()
{
char *Arr = "ABCDEFG";
char *Seq = "AB";
bool contained = contains(Arr, Seq);
if (contained)
{
printf("Contained\n");
}
else
{
printf("Not Contained\n");
}
}
Basically this is strstr
const char* strstrn(const char* orig, const char* pat, int n)
{
const char* it = orig;
do
{
const char* tmp = it;
const char* tmp2 = pat;
if (*tmp == *tmp2) {
while (*tmp == *tmp2 && *tmp != '\0') {
tmp++;
tmp2++;
}
if (n-- == 0)
return it;
}
tmp = it;
tmp2 = pat;
} while (*it++ != '\0');
return NULL;
}
The above returns n matches of substring in a string.

Compare two arrays and return the index of the first appearence

I have a task to do, and I was thinking about it, but I dont come up with the right answer.
In a language of your choosing, write a function that gets a string named str and a string named set.
The function will return the index of the first appearance of any char from set in str.
For example:
str = "hellohellohellohelloistom!"
set = "t98765!"
The function will return 22 (index of '5' in str).
Make sure that time complexity is not larger than the length of both strings - O(m+n)
Assume that the string only contains ASCII characters.
I was thinking about it and I thought about doing it with divide and conquer. I have a base case that is always O(1) and the I divide the problem in smaller problems until I get the answer. The problem is that with that solution the complexity will be O(log n).
The other approax I thought was to make a Set. But I still don't really know how to approach this problem. Any ideas??
This program is written in Swift
let str = "hellohellohellohelloistom!"
let set = "t98765!"
func findFirstAppearance(str : String , set : String) -> Int? {
var index : Int?
mainLoop: for setCharacter in set.characters{
for (indexOfChar,strCharacter) in str.characters.enumerate(){
if strCharacter == setCharacter{
index = indexOfChar
break mainLoop
}
}
}
return index
}
print(findFirstAppearance(str, set: set))
print(findFirstAppearance("helloWorld", set: "546Wo"))
Or another solution with less time consuming
let str = "hellohellohellohelloistom!"
let set = "t98765!"
func findFirstAppearance(str : String , set : String) -> Int? {
var index : Int?
mainLoop: for setCharacter in set.characters{
if let range = str.rangeOfString(String(setCharacter)){
index = str.startIndex.distanceTo(range.startIndex)
break
}
}
return index
}
print(findFirstAppearance(str, set: set))
print(findFirstAppearance("helloWorld", set: "546Wo"))
Note :
if any character is not found then it will return nil
it's case sensitive comparison
Hope this will solve your problem.
Since all the strings involved contain only ASCII characters then using constant memory this can be solved in O(LengthOf(str) + LengthOf(set)).
Here is the code in "C" Language:
//ReturnValues:
//-1 : if no occurrence of any character of set is found in str
//value >=0 : index of character in str.
int FindFirstOccurenceOfAnyCharacterInSet(const char *str, const char *set, int *index_of_set)
{
char hash[256];
int i = 0;
while(i < 256)
{
hash[i] = -1;
++i;
}
i = 0;
while(set[i] != '\0')
{
hash[set[i]] = i;
++i;
}
i = 0;
while(str[i] != '\0')
{
if(hash[str[i]] != -1)
{
*index_of_set = hash[str[i]];
return i;
}
++i;
}
*index_of_set = -1;
return -1;
}
Logic works by recording the position/indexes (which are >=0) of all the characters of set in hash table and then parsing str and checking whether the current character of str is present in hash table.
index_of_set will also report the index of character in set which is found in str. If index_of_set = -1 then no occurrence was found.
Thanks for the help!!
Here is also the code in C#.
Cheers,
public static int FindFirstOccurenceOfAnyCharacterInSet(string str, string set)
{
var hash = new int[256];
int i = 0;
while (i < 256)
{
hash[i] = -1;
++i;
}
i = 0;
do
{
hash[set[i]] = i;
++i;
} while (set[i] != '\0' && i < set.Length - 1);
i = 0;
while (str[i] != '\0')
{
if (hash[str[i]] != -1)
{
return i;
}
++i;
}
return -1;
}

Bubble sorting an array with nulls in C

I'm trying to create a bubble sort with nulls in the middle in C.
The code works ok when the array is ordered in a way so the nulls are at the end of the array (hense the "continue" condition works).
My array looks like this: [John,David,NULL,Grace,NULL,NULL]
on which I run this function:
void SortContacts(char * people[]) {
int i,j;
char *tempswap;
for (i=0; i<storage-1; i++) {
for (j=0; j<storage-i-1; j++) {
if (people[j+1]==NULL) {
continue;
}
if (strcmp(people[j],people[j+1]) > 0) {
tempswap = people[j];
people[j] = people[j+1];
people[j+1] = tempswap;
}
}
}
}
When executing with the NULL in the middle of the array the exe crashes.
You cannot strcmp a NULL value. Although you are guarding against a strcmp of people[j+1] being NULL, you don't check people[j].
Try the following (untested), which simply provides a strcmp function which treats a NULL like "".
int
strcmpwithnull(const char *a, const char *b)
{
return strcmp(a?a:"", b?b:"");
}
void SortContacts(char * people[]) {
int i,j;
char *tempswap;
for (i=0; i<storage-1; i++) {
for (j=0; j<storage-i-1; j++) {
if (strcmpwithnull(people[j],people[j+1]) > 0) {
tempswap = people[j];
people[j] = people[j+1];
people[j+1] = tempswap;
}
}
}
}
If you want a NULL to be treated as greater than any other string, then try (again untested):
int
strcmpwithnull(const char *a, const char *b)
{
if (a == b)
return 0; /* handles 2 NULLs and two strings at the same location */
else if (!a)
return 1;
else if (!b)
return -1;
else
return strcmp(a, b);
}
If you want them to be less than any other string (including the empty string), swap the return 1 and return -1.
Here is the problem
if (people[j+1]==NULL)
{
continue;
}
You need to check both j and j+1
Also consider What if you have a NULL in the head of the array ? or you have 2 NULLs one after another
So you need also to check the j not only the j+1
you should also check thejisn't null
You want to end up with the nulls at the right of the array. This can be achieved by making nulls strictly greater than any string. You have to encode this into the comparison function.
int cmp(const char *x, const char *y)
{ if(x == 0) return 1;
if(y == 0) return -1;
return strcmp(x, y);
}

compare two int array in j2me?

In my app I have 2 images with same dimensions,that I would to give their RGB data and compare them.In j2me we can not use java.util.Arrays and so Arrays.equals(array1, array2) method. One way to compare them is using for loop and compare each element of two int array,but i'm looking for better way.When I search in web I found ArrayUtils class,here,that has some equals() methods,but it's method compare two arrays of objects and before compare int arrays convert them to Enumeration by arrayToEnumeration(Object array) that creates an enumeration from given object.
Finally this is my question:
Is there a better way to compare two int arrays in j2me?
Try something like this.. From the Util class
public static boolean equals(byte[] a, byte[] a2) {
if (a==a2)
return true;
if (a==null || a2==null)
return false;
int length = a.length;
if (a2.length != length)
return false;
for (int i=0; i<length; i++)
if (a[i] != a2[i])
return false;
return true;
}
private int compareArray(String[] _array1, String[] _array2){
Vector m_length1 = new Vector();
Vector m_length2 = new Vector();
if(_array1 && _array2!=null)
{
for(int i=0; i<_array1.length; i++){
if(m_length1[i]!=null){
m_length1.add(_array1[i]);
}
}
for(int j=0; j<_array2.length; j++){
if(m_length2[j]!=null){
m_length2.add(_array2[j]);
}
}
}
if(m_length1.size()==m_length2.size()){
return 0; /*matching*/
}else{
return -1; /*no matching*/
}
}
You can modify it as int array or you can compare byte of each value.
For instance;
byte sample[] = {0,0,0,0};
sample= yourValue.getBytes();
Convert byte array to String:
public boolean equals(byte[] b1, byte[] b2){
String strB1 = new String(b1);
String strB2 = new String(b2);
if(strB1.equals(strB2)){
return true;
}
else{
return false;
}
}

Resources