I'm trying to find the most repeated int number of my vector.
Here is my code:
for (i = 0; i < dim; i++){
temp = vet[i];
for (i = 0; i < dim; i++){
if(vet[i] == temp){
count++;
}
}
if (most < count){
most = count;
elem = vet[i];
}
}
return elem;
}
It's not correct. I hope you can help me. Thank you!
The most obvious problem is that your code uses i in both the inner and the outer loops. The most and count variables are uninitialized in the above code, and count needs to be reset before starting the inner loop each time.
The method used in this code of iterating over the entire array for each element to count appearances is not very efficient. The efficiency could be improved by starting the inner loop from i + 1, instead of from 0. By doing this, the first frequency count for each element will be correct, though the later counts will be low since the earlier indices will not be visited. But this does not matter, since the first count will have set the most variable if possible. The count variable can be set to 1 before the inner loop begins, since the ith element is the test value, and the inner loop will skip this index. This change will substantially reduce the number of array accesses.
Note that this function will return the value of the first element in the array that is also the most frequently appearing.
int get_most_common(int vet[], size_t dim)
{
size_t i, j, count;
size_t most = 0;
int temp, elem;
for(i = 0; i < dim; i++) {
temp = vet[i];
count = 1;
for(j = i + 1; j < dim; j++) {
if(vet[j] == temp) {
count++;
}
}
if (most < count) {
most = count;
elem = vet[i];
}
}
return elem;
}
You can always try the brute force method, count the frequency of each element, then find the maximum one.
To implement a full version of such function with efficiency, you will need special data structure such as hashtable or dictionary.
But the following codes work well if you just need to return the first item that match such condition.
#include <stdio.h>
// returns the first matched most frequent item of a list
// list items of same value must be grouped, for example, a sorted list
// only returns the first matched item
int max_frequent_item_of(int vet[], int dim)
{
int i = 0;
// element and its count of current sublist
int current = vet[0];
int current_count = 0;
// most frequent element and its count of the list so far
int most = vet[0];
int most_count = 0;
while (i < dim) {
// if i-th element still belong to current sublist, run the counter
if (vet[i] == current) {
current_count += 1;
i += 1;
}
// otherwise, the current sublist just ended
else {
// update the most frequent element
if (current_count > most_count) {
most = current;
most_count = current_count;
}
// reset current sublist
current = vet[i];
current_count = 1;
i += 1;
}
}
printf("most frequent item %d, count %d\n", most, most_count);
return most;
}
int main(void)
{
// vet must be in order, sort with `qsort` if necessary
int vet[] = {1, 1, 2, 3, 4, 4, 4, 8, 9, 9};
int size = 10;
int n;
printf("list: ");
for (n = 0 ; n < size; n++)
{
printf("%d ", vet[n]);
}
printf("\n");
max_frequent_item_of(vet, size);
return 0;
}
output
list: 1 1 2 3 4 4 4 8 9 9
most frequent item 4, count 3
I write This Code do what you need and extra if two numbers have the same repeating times, it returns the Bigger one.
int ReturnMostRepeated(int val[], size_t dim)
{
size_t i,j,count;
int temp=0, temp2;
for(i =0;i<dim;i++)
{
count = 1;
for(j=i+1;j<dim;j++)
{
if(val[j]==val[i])
{
count++;
}
}
if (count>temp)
{
temp = count;
temp2 = val[i];
}else if(count == temp) if (val[i]>temp2) temp2 = val[i];
}
return temp2;
}
Related
So I am trying to write this function where the input parameter array will be taken and copied into another array but in a sorted way. For example: an input parameter of 3, 1, 9, 8 will copy into the target array 1, 3, 8, 9.
This is what I have so far but it only copies the smallest element in every time. I'm looking for a way to "blacklist" smallest values that are discovered in each pass.
void sort_another_array(int *param, int *target, int size){
int i, j, lowest = param[0];
for(i = 0; i < size; i++){
for(j = 0; j < size; j++){
if(param[j] < lowest){
lowest = param[j]
}
}
target[i] = lowest;
}
}
Of course I could have another array of already found lowest values but that's more unnecessary looping and checking and adds to the already terrible n^2 complexity. Is there an easier way to do this?
I'm completely new to C, so please do restrict it to simple programming concepts of logic statements, using some flag variables etc..
The probably most straight-forward way to do this is to first copy the whole array and then sort the new array in-place using a standard sorting algorithm.
However, if you want to keep the current structure, the following would be an alternative when all elements are unique:
void sort_another_array(int *param, int *target, int size) {
int i, j, past_min = INT_MAX, current_min = INT_MAX;
for (i = 0; i < size; ++i) {
for (j = 0; j < size; ++j) {
if (i == 0 || param[j] > past_min) {
if (past_min == current_min || param[j] < current_min) {
current_min = param[j];
}
}
}
target[i] = current_min;
past_min = current_min;
}
}
What this does is keeping track of the previously lowest element found (past_min). The next element to find is lowest among all elements greater than past_min. I.e., we want both param[j] > past_min and param[j] < current_min to be true. However, the first element to add to target (i.e., when i == 0) will not have a lower element before it, so we add an exception for that. Similar, the first element satisfying param[j] > past_min in a pass will not have any element to compare with so we add another exception using past_min == current_min (this is true only for the first element found in a pass).
If you have duplicates in the array, this might work:
void sort_another_array(int *param, int *target, int size) {
int j, past_min, current_min, write = 0, round_write = 0;
while (round_write != size) {
for (j = 0; j < size; ++j) {
if (round_write == 0 || param[j] > past_min) {
if (write == round_write || param[j] < current_min) {
current_min = param[j];
write = round_write;
target[write] = current_min;
++write;
} else if (param[j] == current_min) {
target[write] = current_min;
++write;
}
}
}
round_write = write;
past_min = current_min;
}
}
Basically it's the same idea, but it writes all elements of the minimum value in the same pass.
You can use a modified insertion sort algorithm to solve this problem:
#include <stdio.h>
void sort_another_array(int *param, int *target, int size)
{
for ( int i = 0; i < size; i ++ ) // do for all elements in param
{
int j = i - 1;
while ( j >= 0 && target[j] > param[i] ) // find index of element in target which is samler or equal than param[i]
{
target[j+1] = target[j]; // shift forward element of target which is greater than param[i]
j --;
}
target[j+1] = param[i]; // insert param[i] into target
}
}
#define SIZE 10
int main( void )
{
int a[SIZE] = { 9, 8, 0, 2, 1, 3, 4, 5, 7, 6 };
int b[SIZE];
sort_another_array( a, b, SIZE );
for ( int i = 0; i < SIZE; i ++ )
printf( "%2d", b[i] );
return 0;
}
The solution I am providing, has a limitation that: If there are no duplicates in the array, then this will work:
void sort_another_array(int *param, int *target, int size)
{
int i, j, lowest;
for(i = 0; i < size; i++)
{
int k = 0;
if( i > 0) // for all except first iteration
{
while(param[k] <= target[i-1]) // find the one greater than the last one added
k++;
}
lowest = param[k];
for(j = 1; j < size; j++)
{
if( ( i==0 && param[j] < lowest ) || ( i > 0 && param[j] < lowest && param[j] > target[i-1])) // for all except first iteration the min found should be greater than the last one found
{
lowest = param[j];
}
}
target[i] = lowest;
}
}
I posted earlier about a runtime error in my C program but now I'm having another issue with the code. My program runs fine without any errors but it always prints 0 no matter what the input. I've spent the last 4 hours trying to figure out why my code is doing that but I've had no luck. I would really appreciate if someone could give me a hand.
My program takes in an input of a sequence of integers, using another program that works like scanf. Getint() reads an input of a sequence of integers and stops reading the input when it reaches EOF (-1). The number of integers in the sequence is 1000.
// ar_max(a[]) returns the max entry of a
int ar_max(int a[]) {
int max_so_far = a[0];
for (int i = 1; i < 1000; i++) {
if (a[i] > max_so_far) {
max_so_far = a[i];
}
}
return max_so_far;
}
int main() {
int inputnum = getint();
// array containing the distinct numbers seen
int a_num[1000] = {};
// array containing the frequencies of the distinct numbers seen
int a_freq[1000] = {};
int len_n = 0;
while (inputnum != EOF) {
int i = 0;
len_n = i + 1;
int len_f = len_n;
// update the frequency of inputnum if it's already been seen
for (i = 0; i < len_f; i++, len_n += 1) {
if (a_num[i] == inputnum) {
a_freq[i] = a_freq[i] + 1;
}
}
// add inputnum into the array if it hasn't already been seen
if (i == len_n) {
a_num[i+1] = inputnum;
a_freq[i+1] = 1;
}
inputnum = getint();
}
// print the first number with the highest frequency
for (int j = 0; j < len_n; j++) {
if (a_freq[j] == ar_max(a_freq)) {
printf("%d\n", a_num[j]);
break;
}
}
}
For example, an input of
10 20 30 20
should result in 20
The code has the right idea, but it still has some problems.
First, you have two arrays with related information. You keep two lengths for each of these arrays and try to keep the lengths the same. That's complicated. Instead, consider having just one length for both arrays.
When you loop thorugh the array in oder to check whether the given number is already contained in the array:
for (i = 0; i < len_f; i++, len_n += 1) {
if (a_num[i] == inputnum) {
a_freq[i] = a_freq[i] + 1;
}
}
you update then length of the number array with each iteration. You shouldn't, because you are not changing the length of anything while iterating though the loop.
Next, you check whether the number hasn't been found with:
if (i == len_n) ...
That doesn't work, because you update the frequency in the first loop, but don't terminate the loop; your condition will always be true. You can fix this by breaking out of the loop explicitly with break when you have found the number. (Better yet, make the look-up and frequency update a function whose return value indicates whether the element was found and add the elemen if it wasn't.)
When you append the new element:
if (i == len_n) {
a_num[i+1] = inputnum;
a_freq[i+1] = 1;
}
you should, of course, increment the length of the array you append to. In general, appending an item to an array looks like this:
array[len++] = item;
Recall that the first index is zero and that the actual length is one beyond the valid indices.
There are other points:
When you add an element, you should make sure that you don't overflow the array. The dimension of 1000 is generous, but not infinite.
In your function ar_max, you iterate over all 1000 elements of the array. You have initialised the arrays to zero, so the maximum will still be right, but it is better to pass the array size to the function, too, so that you can iterate over only the actual items.
If your function ar_max returned an index instead of a value, you could access both array with that index and you wouldn't need the last loop over j, because j is just that index.
If you have two parallel arrays, it is a good idea to create a struct that hold the item and frequency and always keeps them together. That simplifies the code, because you don't have to keep anything in sync. Such a data layout also lends itself to sorting and filtering other common operations.
Here's a version that implements the fixes described above. It also uses a function to look up an element by value and makes ar_max return an array index instead of a value.
#include <stdlib.h>
#include <stdio.h>
#define MAX 1000
int getint()
{
int x;
if (scanf("%d", &x) < 1) return EOF;
return x;
}
int ar_max(const int a[], int len)
{
if (len == 0) return -1;
int max_so_far = a[0];
int max_index = 0;
for (int i = 1; i < len; i++) {
if (a[i] > max_so_far) {
max_so_far = a[i];
max_index = i;
}
}
return max_index;
}
int ar_find(const int a[], int len, int which)
{
for (int i = 0; i < len; i++) {
if (a[i] == which) return i;
}
return -1;
}
int main()
{
int inputnum = getint();
int a_num[MAX] = { }; // distinct numbers seen
int a_freq[MAX] = { }; // frequencies of the distinct numbers
int len = 0; // actual length of both arrays
while (inputnum != EOF) {
int i = ar_find(a_num, len, inputnum);
if (i < 0) { // append new item
if (len >= MAX) {
fprintf(stderr, "Array size %d exceeded\n", MAX);
exit(1);
}
a_num[len] = inputnum;
a_freq[len] = 1;
len++;
} else { // increment existing item
a_freq[i]++;
}
inputnum = getint();
}
int imax = ar_max(a_freq, len);
if (imax >= 0) {
printf("%d (%d times)\n", a_num[imax], a_freq[imax]);
} else {
puts("Empty input.");
}
return 0;
}
int main()
{
// array containing the distinct numbers seen
int a_num[1000] = {0};
// array containing the frequencies of the distinct numbers seen
int a_freq[1000] = {0};
int len_n = 0;
int i = 0, j = 0;
// Read first entry
int inputnum = getint();
if (EOF == inputnum)
{
printf("No valid number input given\n");
return -1;
}
// Make first entry in a_num and a_freq
a_num[0] = inputnum;
a_freq[0] = 1;
// Update len_n to 1
len_n = 1;
// Get new entry from user and update number array and frequency array
inputnum = getint();
while (inputnum != EOF)
{
// update the frequency of inputnum if it's already been seen
for (i = 0; i < len_n; i++)
{
if (a_num[i] == inputnum)
{
a_freq[i] = a_freq[i] + 1;
break;
}
}
// add inputnum into the array if it hasn't already been seen
if (i == len_n)
{
a_num[i] = inputnum;
a_freq[i] = 1;
// Update len_n
len_n++;
}
// Check if we have already reached 1000
if (1000 == len_n)
{
printf("Reached 1000 entry read\n");
break;
}
// Next entry
inputnum = getint();
}
// print the number with the highest frequency
int max_freq = ar_max(a_freq);
for (j = 0; j < len_n; j++)
{
if (a_freq[j] == max_freq)
{
printf("%d\n", a_num[j]);
break;
}
}
}
NOTE:
1. #define MAX_SIZE 1000 can be used since hardcoded value 1000 is used repeatedly in code. This will help when you have use new size (say 1500) and you need to change only the #define MAX_SIZE 1500, other code remains unchanged.
2. ar_max() function can be modified to give array index where max occurs to avoid the for loop in main to find the array index. e.g.
int ar_max(int a[])
{
int index = 0;
int max_so_far = a[0];
for (int i = 1; i < 1000; i++) {
if (a[i] > max_so_far) {
max_so_far = a[i];
index = i;
}
}
return index;
}
In main():
printf("%d\n", a_num[ar_max(a_freq)]);
I am trying to find an efficient way to find count of all elemets to the right of current element whose value is less than current element in an array in C.
For example:
My array is, R = [2, 4 ,3 ,1]
Then for 2, elements on right of 2 are (4,3,1), among which less than 2 is 1. So the count is 1.
Then for 4, elements on right of 4 are (3,1), among which less than 4 is 3 and 1. So the count is 2.
Then for 3, elements on right of 3 are (1), among which less than 3 is 1. So the count is 1.
Then for 1, Nothing on right of 1 , so nothing is less so count is 0.
So the output array (Containing all the counts) is [ 1,2,1].
How to do it efficiently in C?
I wrote the following code snippet, which seems to be incorrect:
for( i = 0 ; i < size; i++ ) {
index = find_index(R,size,R[i]);
for( j = index+1 ; j < size; j++ ) {
values_to_right[j] = R[j];
}
print_array(values_to_right, size);
printf("\n****************\n");
}
Where as my find_index() and print_array() functions are as follows:
int find_index(int a[], int num_elements, int value)
{
int i;
for (i=0; i<num_elements; i++)
{
if (a[i] == value)
{
return(i); /* it was found */
}
}
return(-1); /* if it was not found */
}
void print_array(int a[], int num_elements)
{
int i;
for(i=0; i<num_elements; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
Any help will be much appreciated.
Check the code below:
#include <stdio.h>
int main(void) {
int a[4] = {2,4,3,1};
int b[4];
int i,sum,k=0,j;
for(i=0;i<4;i++)
{
sum =0;
for(j=i+1;j<4;j++)
{
if(a[j] < a[i])
sum ++;
}
b[k++] = sum;
}
for(i=0;i<k;i++)
printf("%d ",b[i]);
return 0;
}
int i = 0;
// Used as loop index
int currentValue = myArray[currentIndex];
// Holds value at current element
int count = 0;
// Will hold How many elements have smaller values (your question)
for(i = 0; i < currentIndex; i++){
if(myArray[i] < currentValue){
count++;
}
}
Will tell you how many array elements have a smaller value than your reference element. If you want a list of which elements (array indices) satisfy the condition, it gets more complicated...
EDIT: My solution is added to the end of the question. Thanks for the hint.
I'll just go with an example. Suppose I have an array with length n:
arr = { 1, 4, 8, 2, 5, ... }
If I want to traverse all combinations of TWO elements I would write:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// do something with arr[i] and arr[j]
}
}
I If I want to traverse all configurations of THREE elements I would simply add another layer of for iteration:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
// do something with arr[i] and arr[j]
}
}
}
What if the number of elements is given by user (say m), and we don't know exactly what it is? What should I write then?
(I couldn't figure out the best title for this question. And the tags are not accurate either. Help me with these too, if you want.)
Answer
The solution is this function:
void configurations(int depth, int* array, int length, int* indices, int curDepth) {
if (curDepth == 0) {
for (int i = 0; i < depth; i++) {
printf("%d ", indices[i]);
}
printf("\n");
return;
}
for (int i = 0; i < length; i++) {
indices[curDepth - 1] = i;
configurations(depth, array, length, indices, curDepth - 1);
}
}
The usage of the function above is shown below:
int a[] = {9, 8, 7, 6, 5, 4, 3, 2, 1};
int configSize = 3;
int* indices = new int[configSize];
configurations(configSize, a, 9, indices, configSize);
The console will show all configurations of the given size of the elements in the array:
0 0 0
1 0 0
2 0 0
3 0 0
4 0 0
...
5 8 8
6 8 8
7 8 8
8 8 8
You can simply use recursion.
Some pseudo-code:
void someFunction(int[] arr, int n, int depth)
{
if (depth == 0)
{
// do something with the stored elements
return;
}
for (int i = 0; i < n; i++)
{
// store arr[i]
someFunction(arr, n, depth-1);
}
}
There are a few ways to store arr[i]. One way could be to pass an array of size initialDepth down via the recursive call, along with the current index in that array. We increase the index on every recursive call, and put arr[i] at the current index. Then, when the depth == 0 if-statement triggers, we'll have an array containing a permutation, which we could do whatever with.
This, as your code, would repeat elements (i.e. one permutation will consist exclusively of the first element repeated a few times). If you wish to avoid this, you can instead swap the first element with each other element at the first step, then recurse, swapping the second element with each other element at the second step, and so on.
void someFunction(int[] arr, int n, int pos, int depth)
{
if (pos == depth)
{
// do something with the elements in arr from 0 to pos
return;
}
for (int i = pos; i < n; i++)
{
// swap arr[pos] and arr[i]
someFunction(arr, n, pos+1, depth);
// swap arr[pos] and arr[i] back
}
}
Call with someFunction(inputArray, n, 0, desiredDepth).
Use backtracking (depth-first search). The general idea will be something like this:
void Generate(int n) {
if ((0..n).count(i => used[i]) >= NUMBER_OF_ELEMENTS_DESIRED_FOR_A_PERMUTATION) {
print this permutation;
return;
}
used[n] = true;
foreach (int next in (0..n).where(i => !used[i]))
Generate(next);
used[n] = false;
}
You can be use recursion, Something like this:
public static void main(String[] args) {
char[] alphabet = new char[] {'a','f','j'};
possibleStrings(2, alphabet,"");
}
public static void possibleStrings(int maxLength, char[] alphabet, String curr) {
if(curr.length() == maxLength) {
System.out.println(curr);
} else {
for(int i = 0; i < alphabet.length; i++) {
String oldCurr = curr;
curr += alphabet[i];
possibleStrings(maxLength,alphabet,curr);
curr = oldCurr;
}
}
}
i have this function to print the histogram, I suppose to use this function calculate mode as well, I understand that to find mode you need to compare number of occurrences of each score, but I can't figured out how to implement this into the code. Is there anyway to implement this function to find mode?
this is my function
int calMode(RECORD list[], int count){
int tempMode = 0;
int i, k;
int current = 0;
while (current < count)
{
printf("%d:", list[current].score);
for(k=0; (i=current + k) < count ; ++k)
{
if(list[current].score == list[i].score)
printf("*");
else
break;
}
if(k > tempMode)
tempMode = k;
printf("\n");
current = current + k;
}
printf("%d\n", tempMode);
return tempMode;
}
int calMode(RECORD list[], int count){
int tempMode;
int i, k;
int current = 0;
int max = -1;
int update = 0;
while (current < count){
printf("%d:", list[current].score);
for(k=0; (i=current + k) < count ; ++k){
if(list[current].score == list[i].score)
printf("*");
else
break;
}
printf("\n");
if(k>max){
max = k;
tempMode = list[current].score;
update = 1;
} else if(k == max){
update = 0;
}
current = current + k;
}
if(update == 0)
tempMode = -1;//indeterminable
return tempMode;
}
Well, you'll need a different algorithm. You need to find the maximum .score member of your items, and store the corresponding index(es). Something like this might do:
int max = list[0].score;
RECORD *max_item[count] = { &list[0] };
size_t index = 1;
while (count-- > 1) {
// We're looking for any items that are greater than or equal to the
// current max, so when we find items that are less, we jump back to
// the condition evaluation using "continue".
if (list[count].score < max) { continue; }
// When we find a value that's greater than the current maximum, we
// need to discard all previously stored "maximum" items and update
// our current maximum.
if (list[count].score > max) {
index = 0;
max = list[count].score;
}
// At this point, the current item can't be less than the current max.
// This is because of the "continue;" earlier. Add this item to our
// list of "maximum" items.
max_item[index++] = &list[count];
}
max now stores the maximum score in your histogram, index stores the number of items that contain that maximum score and max_item stores pointers to RECORDs that contain that item.