i want to create a function that take the inputs of an array and its number of values. The function should look through the array and as soon as it sees a ''3 in a row''(e.g { 1 2 3 4 5 5 5 6 7 8}), in this case 5. The function should print the index of the first 5. Im new to coding so im finding it difficult how to begin. Ive made an attempt but dont know how to proceed.
int NewFunction(int array, int numValues){
int i;
int j;
for(i=0;i<numValues;i++){
for(j=i+1;j<numValues;j++){
if(
First of all, you might want to go with a more descriptive name than NewFunction. Also, the array shouldn't be of type int, you're probably looking for a pointer to an int.
Furthermore, you don't need a nested loop like that:
for(i=0;i<numValues;i++){
for(j=i+1;j<numValues;j++){
Imagine doing this by hand, getting a list of about 1000 numbers, trying to find three in a row. How often would you pass through the list? A maximum of once, right? You wouldn't go through the list a thousand times, so neither should your algorithm, therefore you don't need a nested loop here.
What you're looking for is something like this:
int threeInARow(int* array, int numValues) {
int count = 1; // how many numbers in a row were found
int current = array[0]; // the number that we're looking for
int i = 1;
for (; i < numValues; i++) {
if (array[i] == current) {
if (++count == 3) return i - 2;
}
else { // a different number is found: start over
count = 1;
current = array[i];
}
}
return -1; // return a value indicating that no result was found
}
Start with a variable: where have you first seen the last value you saw. Let's call it last, and initialise it at 0. Then iterate index from 1 to the length of the array. If the difference between index and last is 3, return last as the index of the repeating value. If not, check whether index is at length. If so, the search failed. Otherwise, if the value at the current index is different from the value at last, set last to the current index.
Another approach.
#include <stdio.h>
#define ELEMENT 14
int three_in_a_row(int arr[], int n) {
int i, index, count = 0, max = 0;
i = -1;
do {
i = i + 1;
if (arr[i] == arr[i + 1]) {
index = i-1; //because we want the first occurrence
count++;
if (count > max) max = count; // 3 elements in a row means that max must be 3-1
} else
count = 0;
} while (i < n - 2 && max != 3 - 1);
return (max == 2 ? index : -1);// -1 indicates no result
}
int main(void) {
int array[] = {1,10,1,4,4,8,8,8,7,8,8,9,9,2}, index3;
index3 = three_in_a_row(array, ELEMENT);
printf("%d\n", index3);
return (0);
}
Related
I share with my solution of the algorithm to find the second maximum in a given unsorted array, is there a better way to do it? (I found complexity O(2n))
int PositionDuSecondMax(int *T, int n) {
// this function look for the index of the second maximum ( the number just under the maximum ) in a given array
// exemple : T[] = {10,100,14,49] ---> this function returns 3
// we have T a dynamic array and n the number of elements in T
// the given array in unsorted
int iMax = 0; // we suppose iMax == 0
int iSecMax;
// we go through the array and compare T[iMax] with the current element in the current index
// so we can find the index of the max in the array
for (int i = 0; i < n; i++) {
if (T[iMax] < T[i]) {
iMax = i;
}
}
// this if statement is to max sure that iMax is different from iSecMax
if (iMax == 0) {
iSecMax = 1;
} else {
iSecMax = iMax - 1;
}
// we loop through the array and compare each element with T[iSecMax] , we must specify that T[iSecMax] != T[iMax]
for (int i = 0; i < n; i++) {
if (T[iSecMax] < T[i] && T[iSecMax] == T[iMax]) {
iSecMax = i;
}
}
return iSecMax;
}
Your approach has multiple problems:
if the max is at offset 0 with a duplicate at offset 1 or if the max is at offset iMax - 1, the initial value of iSecMax is that of the maximum so you will not find the second max.
the test T[iSecMax] == T[iMax] to avoid select a duplicate of the max value is incorrect, it should be T[i] != T[iMax].
Here is a modified version:
int PositionDuSecondMax(const int *T, int n) {
// this function returns the index of the second maximum (the number just under the maximum) in a given array
// example: T[] = {10,100,14,49} --> this function returns 3
// arguments: T points to an unsorted array of int,
// n is the number of elements in T.
int iMax = 0;
int iSecMax = -1;
// we go through the array and compare T[iMax] with the
// element in the current index so we can find the index
// of the max in the array
for (int i = 1; i < n; i++) {
if (T[iMax] < T[i]) {
iMax = i;
}
}
// we loop through the array, ignoring occurrences of T[iMax] and
// compare each element with T[iSecMax]
for (int i = 0; i < n; i++) {
if (T[i] != T[iMax] && (iSecMax < 0 || T[iSecMax] < T[i])) {
iSecMax = i;
}
}
return iSecMax;
}
Notes:
the above function will return -1 if the array is empty or has all entries with the same value, ie: no second max value.
the complexity is O(n). O(2n) and O(n) are the same thing: O(n) means asymptotically proportional to n.
You could modify the code to perform a single scan with a more complicated test, and it would still be O(n).
If the array is unsorted, all elements must be tested so O(n) is the best one can achieve.
If the array was sorted, finding the second max would be O(1) on average (if the second to last element differs from the last), with a worst case of O(log n) (using binary search when the max has duplicates).
If you want to find second largest element in one traverse, you can follow below approach.
if (arrSize < 2)
{
printf(" Invalid Input ");
return;
}
first = second = INT_MIN;
for (i = 0; i < arrSize; i++)
{
/* If current element is greater than first
then update both first and second */
if (arr[i] > first)
{
second = first;
first = arr[i];
}
/* If arr[i] is in between first and
second then update second */
else if (arr[i] > second && arr[i] != first)
second = arr[i];
}
if (second == INT_MIN) printf("There is no second largest element\n");
else printf("The second largest element is %d\n", second);
The best approach is to visit each element of an array to find the second highest number in array with duplicates. The time complexity of this approach is O(n).
Algorithm :
i) Declare two variables max and second max and initialize them with integer minimum possible value.
ii) Traverse an array and compare each element of an array with the value assigned to max variable. If current element is greater than the value assigned at max variable. Then do two things –
a) In second max variable, assign the value present at max variable.
b) In max variable, assign the current index value.
iii) We have to do one more comparison that if current index value is less than max and greater than the value assigned at second max. Then, assign current index value at second max variable.
After complete iteration print the second max element of an array.
#include<stdio.h>
int secondLargest(int arr[], int len) {
//Initialize
int max = 0;
int second_max = 0;
for(int i = 0; i < len; i++) {
if(arr[i] > max) {
second_max = max;
max = arr[i];
}
if(max > arr[i] && arr[i] > second_max) {
second_max=arr[i];
}
}
return second_max;
}
int main(void) {
int arr[] = {70, 4, 8, 10, 14, 9, 7, 6, 5, 3, 2};
int len = 11;
printf("Second highest element is %d\n",secondLargest(arr,len));
return 0;
}
Consider we have to choose a Leader from n people. For this purpose, we create an
array of size n. We assign every candidate a number (1, 2, 3, 4, 5,….,n) and store it in array in
ascending order. We apply dancing chair (People struggle to get the chair!!! After stopping the
music, in each iteration one chair and one man is eliminated. The Final remaining one is the
winner) method. Suppose we start from index 0 then we have to skip 3 indexes and we will reach
at index 3. Set its value to zero and start again from index 4 and skip 3 indexes and we will reach at index 7. Repeat the same step and so on.
(1) When we reach at last index we will proceed to index 0 again (for example the last index is 19, we start the count from index 18 and skip 3 indexes then we will reach at 1 and set it to zero).
(2) If the reached element value is already 0 than set the next element to zero. Do the same process till only one element remaining?
We implement it by using array and function. Write a function SelectLeader () which takes array
as input and return the Leader.
#include <stdio.h>
int SelectLeader() {
int n, i;
int leader = 0;
printf("Enter total number of people to choose a Leader from: ");
scanf("%d", &n);
int array[n];
for (i = 0; i < n; i++) {
array[i] = i + 1;
}
for (i = 0; i <= n; i = (i + 3) % n) {
if (array[i] == 0) {
array[(i + 1) % n] = 0;
} else
array[i] = 0;
}
for (i = 0; i < n; i++) {
if (array[i] != 0) {
leader = i;
}
}
return leader;
}
int main() {
int L;
L = SelectLeader();
printf("Leader is the candidate with the index number %d\n", L);
}
You can use the following pesudo code
Suppose n= 10 , for easy understanding
I am creating a boolean flag array to check whether number is selected or not.
jump = 3
i = 0
for (int cnt=0;cnt<10;) {
if(flag[i%10] === false) {
flag[i%10]=true;
cnt+=1;
i+=jump;
}
else {
i+=1;
}
}
The index element remaining with flag false is ans.
However this approach is both space and time expensive.
I have got an assignment and i'll be glad if you can help me with one question
in this assignment, i have a question that goes like this:
write a function that receives an array and it's length.
the purpose of the function is to check if the array has all numbers from 0 to length-1, if it does the function will return 1 or 0 otherwise.The function can go through the array only one.
you cant sort the array or use a counting array in the function
i wrote the function that calculate the sum and the product of the array's values and indexes
int All_Num_Check(int *arr, int n)
{
int i, index_sum = 0, arr_sum = 0, index_multi = 1, arr_multi = 1;
for (i = 0; i < n; i++)
{
if (i != 0)
index_multi *= i;
if (arr[i] != 0)
arr_multi *= arr[i];
index_sum += i;
arr_sum += arr[i];
}
if ((index_sum == arr_sum) && (index_multi == arr_multi))
return 1;
return 0;
}
i.e: length = 5, arr={0,3,4,2,1} - that's a proper array
length = 5 , arr={0,3,3,4,2} - that's not proper array
unfortunately, this function doesnt work properly in all different cases of number variations.
i.e: length = 5 , {1,2,2,2,3}
thank you your help.
Checking the sum and product is not enough, as your counter-example demonstrates.
A simple solution would be to just sort the array and then check that at every position i, a[i] == i.
Edit: The original question was edited such that sorting is also prohibited. Assuming all the numbers are positive, the following solution "marks" numbers in the required range by negating the corresponding index.
If any array cell already contains a marked number, it means we have a duplicate.
int All_Num_Check(int *arr, int n) {
int i, j;
for (i = 0; i < n; i++) {
j = abs(arr[i]);
if ((j >= n) || (arr[j] < 0)) return 0;
arr[j] = -arr[j];
}
return 1;
}
I thought for a while, and then i realized that it is a highly contrained problem.
Things that are not allowed:
Use of counting array.
Use of sorting.
Use of more than one pass to the original array.
Hence, i came up with this approach of using XOR operation to determine the results.
a ^ a = 0
a^b^c = a^c^b.
Try this:
int main(int argc, char const *argv[])
{
int arr[5], i, n , temp = 0;
for(i=0;i<n; i++){
if( i == 0){
temp = arr[i]^i;
}
else{
temp = temp^(i^arr[i]);
}
}
if(temp == 0){
return 1;
}
else{
return 0;
}
}
To satisfy the condition mentioned in the problem, every number has to occour excatly once.
Now, as the number lies in the range [0,.. n-1], the looping variable will also have the same possible range.
Variable temp , is originally set to 0.
Now, if all the numbers appear in this way, then each number will appear excatly twice.
And XORing the same number twice results in 0.
So, if in the end, when the whole array is traversed and a zero is obtained, this means that the array contains all the numbers excatly once.
Otherwise, multiple copies of a number is present, hence, this won't evaluate to 0.
I keep receiving a Segmentation Fault 11 for the following code. I believe it has something to do with recursion but I'm not entirely sure how. The method should take in an array, skip the odd values, and keep repeating until it has an array with only value left and returns that value.
Thanks!
#include <stdio.h>
int callTable(int table[], int size)
{
int i = 0;
int j = 0;
int cHeight = size / 2;
int cTable[cHeight];
while (i < size)
{
if (table[i] % 2 == 0)
{
cTable[j] = table[i];
j++;
}
i++;
}
if (size > 1)
return callTable(cTable, cHeight);
else
return cTable[0];
}
int main()
{
int tPass[100];
int i, answer;
for (i = 0; i < 100; i++)
tPass[i] = i + 1;
answer = callTable(tPass, sizeof(tPass) / sizeof(tPass[0]));
printf("%d\n", answer);
}
Do you want to skip the odd values or the odd indexes? You are currently skipping the odd values, so after you call callTable once, there are only even values left. Then, on the second call, you try to use an array of half the size to store the even values (which are all of them), so you try to store the entire array on another with half the size.
If you intended to skip the odd indexes, then change this line:
if (table[i]%2==0)
for this one:
if (i%2==0)
That runs fine and returns 1 (which is the number with index 0).
I have an array of integers and I'm trying to find which one is the highest and set a new integer to the highest ones value. I'm very new to C, I literally just started learning it.
There is probably some kind of logical problem with what I'm doing but I haven't been able to spot it yet. so...
int my_array[4];
int highest_int = 0;
int i;
for (i = 0; i < 4; i++) {
if (my_array[i] > my_array[i++]) {
if (my_array[i] > highest_int) {
highest_int = my_array[i];
}
}
else {
if (my_array[i++] > highest_int) {
highest_int = my_array[i++]
}
}
}
So I loop through my array 4 times (4 elements) and I look at the iteration value and the next one and if the iteration value is highest I check it's also higher than the current value of the current 'highest integer' and if it is I set the current highest integer to the new highest value. If the value after the iteration value is higher I do the same thing but with that value instead.
That's what went through my head when I wrote this but when I enter 4 values it always comes out with the 3rd value in the array. No matter what I set those values to.
Can anyone tell me why?
Thanks a lot.
Why you are incrementing i inside the loop? Why do you need the else part?
Here's a simple way:
int my_array[4];
int highest_int = my_array[0];
int i;
for (i = 1; i < 4; i++) {
if (my_array[i] > highest_int) {
highest_int = my_array[i];
}
}
You're making this way more complicated than it really is :) Furthermore, you're writing i++ in too many places; each time i++ gets executed you're skipping over an array entry, which is probably not what you want.
Also, there's no need to compare to the previous value. Just compare to the highest one you've seen so far.
Here's a fixed version, just by deleting code, nothing changed or added:
int my_array[4];
int highest_int = 0;
int i;
for (i = 0; i < 4; i++) {
if (my_array[i] > highest_int) {
highest_int = my_array[i];
}
}
Note that this incorrectly reports 0 if all numbers in the array are negative. Start off highest_int = INT_MIN in case you need to handle those correctly, or use unsigned int.
If you are trying to find the highest number, here is the code:
int my_array[4];
int highest_int = my_array[0];
//Before entering the loop, assuming the first number to highest
int i;
for (i = 1; i < 4; i++) {
if (my_array[i] > highest_int) { //Compare every number with highest number
highest_int = my_array[i];
}
}
//Now we have the highest number
printf("Highest Number: %d",highest_int);