Varying arguments for if () statement - c

I have a problem as stated below:
i have an array(say) a[]={10,24,56,33,22,11,21}
i have something like this
for(i=0;i<100;i++){
if(a[i]==10)
// do something
}
next when i=1
if(a[i]==10 && a[i+1]==24)
so on so at each iteration the arguments / conditions within if should be varying
now this will be a very big sequence i cant explicitly write
if(a[i]==10 && a[i+1]==24 && a[i+2]==56 ...... a[i+100]=2322)
how can i achieve this varying conditions?

You have to have a cumulative "boolean" variable that checks a[i] at the i-th iteration and update that variable:
int a[] = {...}; /* array with some values to verify */
int v[] = {...}; /* these are the actual desired values in a[] */
/* the verifying loop */
int i;
int cond = 1;
for (i = 0; i < 100; i++)
{
cond = cond && (a[i] == v[i]);
if (cond)
{
/* do something */
}
}

I think that you should introduce a boolean value.
bool valid = true;
for(i=0;i<100;i++){
if(a[i]==10 && valid)
// do something
else
{
valid = false;
break;
}
}
For every iteration, you need to change the value to which you are comparing a[i]

Have a loop within a loop:
for (i = 0; i != 100; ++i)
{
int condition = 1;
for (j = 0; i + j != 100 && condition; ++j)
{
condition = condition && (a[i + j] == /* your number */ );
}
if (condition) { /* ... */ }
}

In this case, you can use function pointers or blocks.
You can find a good example here here

Seeing your examples, I think that the variations you are talking about is only in the length of array 'a' whose presence you want to check in some array x. If indeed it is so, memcmp can be of use to you.
Let me modify your example a bit to clarify what I am saying.
int a[7]={10,24,56,33,22,11,21} is the required values you want to check in some array 'x', with different lengths of 'a' each time, with 'x' declared as
int x[1000];
In that case, you could use memcmp as follow :-
for ( len = 1 ; len <= 7 ; ++len )
{ for ( i = 0 ; i <= 1000-len ; ++i )
{ if ( ! memcmp( a, x+i, len * sizeof(int) ) )
{ // do something
}
}
}

Related

Inconsistent output given by same code on different C compilers

Different compilers are giving different outputs for the same logic in my algorithm.
I wrote the following code for a C code exercise.
The code checks for the longest string in a string vector.
But the same logic gives two different outputs.
Here's what is happening. I have no idea what I did wrong.
First version - without a printf() inside the if condition
Here the if (j > longest) just attributes new values for int longest and int index.
#include <stdio.h>
int main(void) {
char *vs[] = {"jfd", "kj", "usjkfhcs", "nbxh", "yt", "muoi", "x", "rexhd"};
int longest, index = 0;
/* i is the index for elements in *vs[].
* "jfd" is 0, "kj" is 1... */
for (int i = 0; i < sizeof(*vs); i++) {
/* j if the index for string lengths in vs[].
* for "jfd", 'j' is 0, 'f' is 1... */
for (int j = 0; vs[i][j] != '\0'; j++) {
/* if j is longer than the previous longest value */
if (j > longest) {
longest = j;
index = i;
}
}
}
printf("Longest string = %s\n", vs[index]);
return 0;
}
I ran it on https://replit.com/. It gave the unexpected output for longest string of "jfd". https://replit.com/#Pedro-Augusto33/Whatafuck-without-printf?v=1
Second version - with a printf() inside the if condition
Now I just inserted a printf() inside the if (jf > longest) condition, as seen in the code block bellow.
It changed the output of my algorithm. I have no idea how or why.
#include <stdio.h>
int main(void) {
char *vs[] = {"jfd", "kj", "usjkfhcs", "nbxh", "yt", "muoi", "x", "rexhd"};
int longest, index = 0;
/* i is the index for elements in *vs[].
* "jfd" is 0, "kj" is 1... */
for (int i = 0; i < sizeof(*vs); i++) {
/* j if the index for string lengths in vs[].
* for "jfd", 'j' is 0, 'f' is 1... */
for (int j = 0; vs[i][j] != '\0'; j++) {
/* if j is longer than the previous longest value */
if (j > longest) {
printf("Whatafuck\n");
longest = j;
index = i;
}
}
}
printf("Longest string = %s\n", vs[index]);
return 0;
}
I also ran it on https://replit.com/. It gave the expected output for longest string of "usjkfhcs". https://replit.com/#Pedro-Augusto33/Whatafuck-with-printf?v=1
Trying new compilers
After replit.com giving two different outputs, I tried another compiler to check if it also behaved strangely. https://www.onlinegdb.com/online_c_compiler gives random outputs. Sometimes it's "jfd", sometimes it's "usjkfhcs". https://onlinegdb.com/iXoCDDena
Then I went to https://www.programiz.com/c-programming/online-compiler/ . It always gives the expected output of "usjkfhcs".
So, my question is: why are different compilers behaving so strangely with my algorithm? Where is the flaw of my algorithm that makes the compilers interpret it different?
The code does not make sense.
For starters the variable longest was not initialized
int longest, index = 0;
So using it for example in this statement
if (j > longest) {
invokes undefined behavior.
In this for loop
for (int i = 0; i < sizeof(*vs); i++) {
the expression sizeof( *vs ) is equivalent to expression sizeof( char * ) and yields either 4 or 8 depending on the used system. It just occurred such a way that the array was initialized with 8 initializers. But in any case the expression sizeof( *vs ) does not provide the number of elements in an array and its value does not depend on the actual number of elements.
Using the if statement within the for loop in each iteration of the loop
for (int j = 0; vs[i][j] != '\0'; j++) {
/* if j is longer than the previous longest value */
if (j > longest) {
longest = j;
index = i;
}
}
Also does not make sense. It does not calculate the exact length of a string that is equal to j after the last iteration of the loop. So in general such a loop shall not be used for calculating length of a string.
Consider a string for example like "A". Using this for loop you will get that its length is equal to 0 while its length is equal to 1..
It seems you are trying to find the longest string a pointer to which stored in the array.
You could just use standard C string function strlen declared in header <string.h>. If to use your approach with for loops then the code can look the following way
#include <stdio.h>
int main(void)
{
const char *vs[] = { "jfd", "kj", "usjkfhcs", "nbxh", "yt", "muoi", "x", "rexhd" };
const size_t N = sizeof( vs ) / sizeof( *vs );
size_t longest = 0, index = 0;
for ( size_t i = 0; i < N; i++ )
{
size_t j = 0;
while ( vs[i][j] != '\0' ) ++j;
if ( longest < j )
{
longest = j;
index = i;
}
}
printf( "Longest string = %s\n", vs[index] );
printf( "Its length = %zu\n", longest );
return 0;
}

Is this syntax array inside array?

Below code snippet from Leetcode. the given exercise is to find the longest substring without repeating characters. I am trying to understand the logic from someone has posted the solution
I have below question is
I have cnt and s are array. is this array inside array cnt[s[j]] and cnt[s[j]]++? how it works, please help to explain. I have tried to visualize the code execution using this
I have tried to understand below line . I tried to visualize the code execution using
#include <stdio.h>
int lengthOfLongestSubstring(char * s)
{
if (s[0] == '\0')
return 0;
if (s[1] == '\0')
return 1;
int i, j, len, max = 0;
int cnt[255] = {0}; // array of counter
//memset(cnt,0,sizeof(cnt));
for (i=0; s[i]!=0; i++)
{
len = 0;
for (j=i; s[j]!=0; j++)
{
if (cnt[s[j]] == 0) /* What does this mean since cnt and s both are array? is this called array inside array ? */
{
printf("iteration %d %c\n",j,s[j]);
cnt[s[j]]++;
len++;
}
else
{ /* if character are not equal */
break;
}
}
if (len > max)
max = len;
}
return max;
}
int main()
{
char string1[] = "abcabcbb";
printf("%d",lengthOfLongestSubstring(string1));
return 0;
}
The syntax a[b[i]] means the value in b[i] references the index from a to read.
So if you have int a[] = { 10, 100, 1000, 10000, 100000}; int b[] = { 3, 2, 1, 0}; then a[b[0]] resolves to a[3] which has the value 10000.
Note that this requires b to only have values that are valid indexes into a.
It's not an array inside an array, it's using one array to get the subscript into another array.
When you see a complex expression you don't understand, split it up into simpler expressions.
cnt[s[j]]++;
is roughly equivalent to
int charcode = s[j];
cnt[charcode]++;
s is a string, so s[j] contains a character code. So this increments the element of cnt corresponding to that character code, and the final result is frequency counts of each character.

Checking whether a string consists of two repetitions

I am writing a function that returns 1 if a string consists of two repetitions, 0 otherwise.
Example: If the string is "hellohello", the function will return 1 because the string consists of the same two words "hello" and "hello".
The first test I did was to use a nested for loop but after a bit of reasoning I thought that the idea is wrong and is not the right way to solve, here is the last function I wrote.
It is not correct, even if the string consists of two repetitions, it returns 0.
Also, I know this problem could be handled differently with a while loop following another algorithm, but I was wondering if it could be done with the for as well.
My idea would be to divide the string in half and check it character by character.
This is the last function I tried:
int doubleString(char *s){
int true=1;
char strNew[50];
for(int i=0;i<strlen(s)/2;i++){
strNew[i]=s[i];
}
for(int j=strlen(s)/2;j<strlen(s);j++){
if(!(strNew[j]==s[j])){
true=0;
}
}
return true;
}
The problem in your function is with the comparison in the second loop: you are using the j variable as an index for both the second half of the given string and for the index in the copied first half of that string. However, for that copied string, you need the indexes to start from zero – so you need to subtract the s_length/2 value from j when accessing its individual characters.
Also, it is better to use the size_t type when looping through strings and comparing to the results of functions like strlen (which return that type). You can also improve your code by saving the strlen(s)/2 value, so it isn't computed on each loop. You can also dispense with your local true variable, returning 0 as soon as you find a mismatch, or 1 if the second loop completes without finding such a mismatch:
int doubleString(char* s)
{
char strNew[50] = { 0, };
size_t full_len = strlen(s);
size_t half_len = full_len / 2;
for (size_t i = 0; i < half_len; i++) {
strNew[i] = s[i];
}
for (size_t j = half_len; j < full_len; j++) {
if (strNew[j - half_len] != s[j]) { // x != y is clearer than !(x == y)
return 0;
}
}
return 1;
}
In fact, once you have appreciated why you need to subtract that "half length" from the j index of strNew, you can remove the need for that temporary copy completely and just use the modified j as an index into the original string:
int doubleString(char* s)
{
size_t full_len = strlen(s);
size_t half_len = full_len / 2;
for (size_t j = half_len; j < full_len; j++) {
if (s[j - half_len] != s[j]) { // x != y is clearer than !(x == y)
return 0;
}
}
return 1;
}
This loop
for(int j=strlen(s)/2;j<strlen(s);j++){
if(!(strNew[j]==s[j])){
true=0;
}
}
is incorrect. The index in the array strNew shall start from 0 instead of the value of the expression strlen( s ) / 2.
But in any case your approach is incorrect because at least you are using an intermediate array with the magic number 50. The user can pass to the function a string of any length.
char strNew[50];
The function can look much simpler.
For example
int doubleString( const char *s )
{
int double_string = 0;
size_t n = 0;
if ( ( double_string = *s != '\0' && ( n = strlen( s ) ) % 2 == 0 ) )
{
double_string = memcmp( s, s + n / 2, n / 2 ) == 0;
}
return double_string;
}
That is the function at first checks that the passed string is not empty and its length is an even number. If so then the function compares two halves of the string.
Here is a demonstration program.
#include <stdio.h>
#include <string.h>
int doubleString( const char *s )
{
int double_string = 0;
size_t n = 0;
if (( double_string = *s != '\0' && ( n = strlen( s ) ) % 2 == 0 ))
{
double_string = memcmp( s, s + n / 2, n / 2 ) == 0;
}
return double_string;
}
int main( void )
{
printf( "doubleString( \"\" ) = %d\n", doubleString( "" ) );
printf( "doubleString( \"HelloHello\" ) = %d\n", doubleString( "HelloHello" ) );
printf( "doubleString( \"Hello Hello\" ) = %d\n", doubleString( "Hello Hello" ) );
}
The program output is
doubleString( "" ) = 0
doubleString( "HelloHello" ) = 1
doubleString( "Hello Hello" ) = 0
Pay attention to that the function parameter should have the qualifier const because the passed string is not changed within the function. And you will be able to call the function with constant arrays without the need to defined one more function for constant character arrays.
it's better to do it with a while loop since you don't always have to iterate through all the elements of the string but since you want the for loop version here it is (C++ version):
int doubleString(string s){
int s_length = s.length();
if(s_length%2 != 0) {
return 0;
}
for (int i = 0; i < s_length/2; i++) {
if (s[i] != s[s_length/2 + i]){
return 0;
}
}
return 1;
}

Cycle through an array in either direction based on a bool

I'm looking for a method of looping through some array in either direction based on some passed bool value, with the same functionality as:
void Transfer(bool *_payload, int _size, bool _isLSB)
{
if (_isLSB)
{
for (int i = _size - 1; i >= 0; i--)
{
digitalWrite(dataPin, _payload[i]);
}
}
else
{
for (int i = 0; i < _size; i++)
{
digitalWrite(dataPin, _payload[i]);
}
}
}
or
void Transfer(bool *_payload, int _size, bool _isLSB)
{
int _index = 0;
if (_isLSB) _index = _size - 1;
for (;;)
{
printf("%d",_payload[_index]);
if (_isLSB) _index--;
else _index++;
if (_isLSB && _index < 0) break;
if (!_isLSB && _index >= _size) break;
}
}
Other than creating a method that reverses the array, is there a nice simplification of this?
You can define the starting and ending point and the increment conditionally:
void Transfer(bool *_payload, int _size, bool _isLSB)
{
int increment = _isLSB ? -1 : 1;
int i = _isLSB ? _size : -1; // one before the area to scan
int end = _isLSB ? -1 : _size; // one past the area
while ((i += increment) != end) // incr/decr before testing
{
digitalWrite(dataPin, _payload[i]);
}
}
We do not know in advance which way the index will be changing (incrementing or decrementing), so we can't use less-than or greater-than in the loop condition. And after processing the last item the index will be modified once more, hence the stopping point is one past the area being processed.
Similarly we need the starting point one position before the scanned area, so that after incrementing (or decrementing) the index we process the valid, first item.
You can calculate the direction and the start/end position for the for loop depending on _isLSB
void Transfer(bool* _payload, int _size, bool _isLSB) {
int dir;
int start;
int end;
if(_isLSB) {
dir = -1;
start = _size-1;
end = -1;
}else {
dir = 1;
start = 0;
end = _size;
}
for(int i = start; i != end; i+=dir) {
digitalWrite(dataPin, _payload[i]);
}
}
What you could do for example, since in C true and false are expanded to integer values in reality, is to use said integer value for calculations.
In the following example I will extract the main problem from your question which is: Looping over a size in a direction depending on a boolean value
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
int main()
{
int size = 5;
bool condition = false;
// Option #1
printf("Option #1\n");
for (int i = (size - 1) * condition; (i >= 0 && condition) || (i < size && !condition); i += 1 * pow(-1, condition))
{
printf("%d", i);
}
// Option #2
printf("\nOption #2\n");
int i = (size - 1) * condition;
for (;;)
{
printf("%d", i);
i += 1 * pow(-1, condition);
if ((i < 0 && condition) || (i >= size && !condition))
break;
}
return 0;
}
With the main function giving the following output for condition = true
Option #1
01234
Option #2
01234
And the following output for condition = false
Option #1
43210
Option #2
43210

Searching through pointer array to count letter uses

Ok, so I am not looking for an a full answer please. I just don't know where to begin with this. I have a code that is declaring a pointer array full of names. The goal is to write a code to search the names and count each letter that is used.
/*
* Search through each character in s,
* which is array containing n strings,
* and update the global count array
* with the correct character counts.
* Note: check the examples to see
* if the counts should be case
* sensitive or case insensitive.
*/
void letterCount(char * s[], int n){
//Implement this function
int c = 0,x; // This is what I've done and I
char p = 'a', j = 'z'; // don't know where im messing up.
while (s[c] != '\0') { // I know I can't compare pointer
if (s[c] >= p && s[c] <= j ){ // and integer.
x = *s[c] - 'a';
count[x]++;
}
c++;
}
}
/*
* Initialize each value in the global
* count array to zero.
*/
void initializeCount(){
//Implement this function
int i;
for (i = 0; i < 26; i++){ // Also not sure if this is correct.
count[i] = 0;
}
}
The output should count the letter uses into an array called count[26].
Any suggestions please?
s[c] is not a character, it's a pointer, you are comparing pointer and character p which is not valid,
if (s[c] >= p && s[c] <= j ) // here you are comparing address & char, which you shouldn't
rotate one more loop for comparing each char of string.
Modify your code as
void letterCount(char * s[], int n){
//Implement this function
int c = 0,x,i; // This is what I've done and I
char p = 'a', j = 'z'; // don't know where im messing up.
// assuming n is no of string, rotate main loop from 0 to n
while (c<n) {
for(i=0;s[c][i]!='\0';i++) // I know I can't compare pointer
if (s[c][i] >= p && s[c][i] <= j ){ // and integer.
x = s[c][i] - 'a';
count[x]++;
}
c++;
}
}
I hope you got this.

Resources