I have been trying to get this prototype for finding mode of an array to work but it is not returning the right thing, could someone please tell me what I am doing wrong.
int mode(int array[], int size)
{
int x;
int mode = 0;
int largest = 0;
for (x = 0; x < size; x++)
{
if (array[x] > largest)
{
largest = array[x];
mode = x;
}
}
return mode;
}
First of all if that's c++ Arrays are numbered from 0, so x should be 0 in the for. also x should be checked against < size. Other then that the code is good.
In the question you've mentioned that " prototype for finding mode of an array " ,but this program is intended to find the position of the largest number in an array, because
mode = x; // x is the value of i which in-turn is the position of element in the array
and the value of mode is returned. So the position of the largest element counting from the zero'th element's position is shown.
If you want a program to find the mode (element/number that occurs most often) in an array, here it is
#include <stdio.h>
int mode(int array[], int size);
int main()
{
int Num[100],size,ret_Val,i;
clrscr();
printf("Enter the size of the array\n");
scanf("%d",&size);
printf("%d ",size);
for(i=0;i<size;i++)
{
scanf("%d",&Num[i]);
}
ret_Val=mode(Num,size);
printf("Mode of the array is %d",ret_Val);
getch();
return 0;
}
int mode(int array[], int size)
{
int cntMde = 1;
int i;
int cnt = 1;
int num = array[0];
int mode = num;
for ( i=1; i<size; i++)
{
if (array[i] == num)
{
cnt++;
}
else
{
if (cnt > cntMde)
{
cntMde = cnt;
mode = num;
}
cnt = 1;
num = array[i];
}
}
return mode;
}
And the output is
Mode of the array is 44
I have analyzed four ways to calculate mode of the array:
If range of numbers in the array is small then use counting sort - O(N) time, (N) space but very efficient
Index elements in the array in hash table - O(N) time, O(N) space
Sort the array and then count successive equal elements - O(NlogN) time, O(1) space
Partially sort the array but skip partitions smaller than current candidate - O(NlogN) time, O(1) space but much more efficient than fully sorting the array because many partitions will be skipped
You can find source code for all four methods and performance comparison in this article: Finding Mode of an Array
Related
i got a problem which i can't solve
I want to know all prime numbers below a given limit x. Allowing me to enter x and calculate the prime numbers using the method of Erastosthenes. Displaying the result on the screen and saving it to a text file.
Calculating the primenumbers below the x, printing them and saving them to a text file worked, the only problem i have is that x can't exceed 500000
could you guys help me?
#include <stdio.h>
#include <math.h>
void sieve(long x, int primes[]);
main()
{
long i;
long x=500000;
int v[x];
printf("give a x\n");
scanf("%d",&x);
FILE *fp;
fp = fopen("primes.txt", "w");
sieve(x, v);
for (i=0;i<x;i++)
{
if (v[i] == 1)
{
printf("\n%d",i);
fprintf(fp, "%d\n",i);
}
}
fclose(fp);
}
void sieve(long x, int primes[])
{
int i;
int j;
for (i=0;i<x;i++)
{
primes[i]=1; // we initialize the sieve list to all 1's (True)
primes[0]=0,primes[1]=0; // Set the first two numbers (0 and 1) to 0 (False)
}
for (i=2;i<sqrt(x);i++) // loop through all the numbers up to the sqrt(n)
{
for (j=i*i;j<x;j+=i) // mark off each factor of i by setting it to 0 (False)
{
primes[j] = 0;
}
}
}
You will be able to handle four times as many values by declaring char v [500000] instead of int v [100000].
You can handle eight times more values by declaring unsigned char v [500000] and using only a single bit for each prime number. This makes the code a bit more complicated.
You can handle twice as many values by having a sieve for odd numbers only. Since 2 is the only even prime number, there is no point keeping them in the sieve.
Since memory for local variables in a function is often quite limited, you can handle many more values by using a static array.
Allocating v as an array of int is wasteful, and making it a local array is risky, stack space being limited. If the array becomes large enough to exceed available stack space, the program will invoke undefined behaviour and likely crash.
While there are ways to improve the efficiency of the sieve by changing the sieve array to an array of bits containing only odd numbers or fewer numbers (6n-1 and 6n+1 is a good trick), you can still improve the efficiency of your simplistic approach by a factor of 10 with easy changes:
fix primes[0] and primes[1] outside the loop,
clear even offsets of prime except the first and only scan odd numbers,
use integer arithmetic for the outer loop limit,
ignore numbers that are already known to be composite,
only check off odd multiples of i.
Here is an improved version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sieve(long x, unsigned char primes[]) {
long i, j;
for (i = 0; i < x; i++) {
primes[i] = i & 1;
}
primes[1] = 0;
primes[2] = 1;
/* loop through all odd numbers up to the sqrt(x) */
for (i = 3; (j = i * i) < x; i += 2) {
/* skip composite numbers */
if (primes[i] == 0)
continue;
/* mark each odd multiple of i as composite */
for (; j < x; j += i + i) {
primes[j] = 0;
}
}
}
int main(int argc, char *argv[]) {
long i, x, count;
int do_count = 0;
unsigned char *v;
if (argc > 1) {
x = strtol(argv[1], NULL, 0);
} else {
printf("enter x: ");
if (scanf("%ld", &x) != 1)
return 1;
}
if (x < 0) {
x = -x;
do_count = 1;
}
v = malloc(x);
if (v == NULL) {
printf("Not enough memory\n");
return 1;
}
sieve(x, v);
if (do_count) {
for (count = i = 0; i < x; i++) {
count += v[i];
}
printf("%ld\n", count);
} else {
for (i = 0; i < x; i++) {
if (v[i] == 1) {
printf("%ld\n", i);
}
}
}
free(v);
return 0;
}
I believe the problem you are having is allocating an array of int if more than 500000 elements on the stack. This is not an efficient way, to use an array where the element is the number and the value indicates whether it is prime or not. If you want to do this, at least use bool, not int as this should only be 1 byte, not 4.
Also notice this
for (i=0;i<x;i++)
{
primes[i]=1; // we initialize the sieve list to all 1's (True)
primes[0]=0,primes[1]=0; // Set the first two numbers (0 and 1) to 0 (False)
}
You are reassigning the first two elements in each loop. Take it out of the loop.
You are initializing x to be 500000, then creating an array with x elements, thus it will have 500000 elements. You are then reading in x. The array will not change size when the value of x changes - it is fixed at 500000 elements, the value of x when you created the array. You want something like this:
long x=500000;
printf("give a x\n");
scanf("%d",&x);
int *v = new int[x];
This fixes your fixed size array issue, and also gets it off the stack and into the heap which will allow you to allocate more space. It should work up to the limit of the memory you have available.
I have been attempting to code for a program that stores input into an array and then allows me to print it out. It also lets me know which number is the largest. What I am trying to figure out is how can I get my program to tell me the amount of times (occurrences) the largest number in array is input. Here is my code so far. As of now, this code outputs the numbers I enter to the array, the largest element in the array, and the occurrence of every number I input( The occurrences of the numbers are incorrect). In all the the amount of occurrences for every number turns out to be 0. Which is obviously incorrect. Again, I need my program to display the largest number (which it does) and the occurrences of ONLY the largest number. All advice, tips, or thoughts are welcome. Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
int main()
{
int arrayNum[15];
int a;
int max=0;
int location;
for( a=0; a < 15; a++)
{
printf("Enter element %d:", a);
scanf("%d",&arrayNum[a]);
}
for(a=0; a < 15; a++)
{
printf("%d\n", arrayNum[a]);
}
for (a = 1; a < 15; a++)
{
if (arrayNum[a] > max)
{
max = arrayNum[a];
location = a+1;
}
}
printf("Max element in the array in the location %d and its value %d\n", location, max);
for(a=0; a<15; a++)
{
if(arrayNum[a+1] == arrayNum[a])
continue;
else
printf("Number %d: %d occurences\n", arrayNum[a]);
}
return 0;
}
I spot some problems in your code. First, the third for loop starts at 1, but it does not update the max as the value of arrayNum[0].
Then, for the problem at hand, I would have two variables:
int max; // The maximum value
int max_count; // The count of the maximum value
Then, the logic to find the greatest, and the count, is the following:
For each element, compare it with the maximum seen. If it is equal, increment max_count. If it is bigger, update max with the value, and set the max_count to 1. If it is smaller, ignore it. Something like:
max = arrayNum[0];
max_count = 1;
for (int a = 1; a < 15; ++a)
{
if (arrayNum[a] == max)
max_count++;
else if (arrayNum[a] > max)
{
max_count = 1;
max = arrayNum[a];
}
}
All you need to do is introduce a new variable to keep track of the number of occurrences of max. When a new value of max is found, set that count to zero. When a subsequent value is found equal to the max, increment the counter.
Incidentally, your code doesn't properly find the maximum in its current form. Try one test case where your array elements are all negative. Try another test case in which all the values are positive, and the first value entered (arrayNum[0]) is the maximum. You will find, in both cases, that your function will not actually find the maximum.
Just before you begin the below loop max is still 0 make
max = a[0];
for (a = 1; a < 15; a++)
{
if (arrayNum[a] > max)
{
max = arrayNum[a];
location = a+1;
}
}
Later
int n=0;
for(i=0;i<15;i++)
{
if(max == a[i])
n++;
}
printf("Number of times max appears in the array is %d\n",n);
Replace last for loop with below code
NoOfOccurances = 0;
for(a=0; a<15; a++)
{
if(max == arrayNum[a])
{
NoOfOccurances++;
}
}
printf("Number %d: %d occurences\n", max,NoOfOccurances);
For your third for-loop, the one where you find out the largest number in your array, I would suggest to set max to arrayNum[0], that way it will work even with negative numbers.
Then, to know how many occurrence of the highest number there is, you need a count variable that you increment (count++) each time a number of the array is equal to max. To do that you need another for-loop.
Good luck.
You can do what you want in just one loop iteration:
int count = 1;
int position = 0;
int max = arrayNum[0];
int N = 15;
int p;
for (p = 1; p < N; ++p)
{
if (arrayNum[p] > max) // Find a bigger number
{
max = arrayNum[p];
pos = p;
count = 1;
}
else if ( arrayNum[p] == max) // Another occurrences of the same number
count++;
}
A simple solution with time complexity of O(n)
int maxoccurence(int a[],int ar_size)
{
int max=a[0],count=0,i;
for(i=0;i<ar_size;i++)
{
if(a[i]==max)//counting the occurrence of maximum element
count++;
if(a[i]>max)//finding maximum number
{
max=a[i];
count=1;
}
}
printf("Maximum element in the array is %d\n",max);
return count;
}
Given an array of integers , you can modify any of a number of arbitrary positive integer , and ultimately makes the entire array is strictly increasing and are positive integers , and asked at least need to change a few numbers
input: 5 1 2 2 3 4
output: 3
and there is what i have tried ,Each number in order to reduce more a ( first number minus one , then the second number minus two ,the third number minus three)
#include <stdio.h>
int Modify_the_array(int B[],int n);
int max(int a,int b);
int main(int argc,char *argv) {
int before_array[]={1,2,3,4,1,2,3,4,5};
int len=sizeof(before_array[0])/sizeof(before_array);
int b;
b=Modify_the_array(before_array,len);
printf("%d\n",b);
return 0;
}
int max(int a,int b){
return a>b?a:b;
}
int Modify_the_array(int B[],int len) {
int i,b=0,n=1;
int maxsofar,tmp,j;
for (i=0;i<len;i++){
B[i]=B[i]-n;
n++;
}
maxsofar=0;
tmp=0;
for(i=0;i<len;i++) {
for (j=i+1;j<len;j++) {
if (B[j]==B[i]&&B[i]>1) {
maxsofar=max(maxsofar,++tmp);
b=len-maxsofar;
}
}
}
return b;
}
somebody recommend there is another solution for this question,more efficently ,can anyone give me some advice,thank in advance
I came across the same problem recently. To make clear:
Problem Statement
You are given a sequence of integers a1,a2,a3.....an. You are free to replace any integer with any other positive integer. How many integers must be replaced to make the resulting sequence strictly increasing?
Input Format
The first line of the test case contains an integer N - the number of entries in the sequence.
The next line contains N space separated integers where the ith integer is ai.
Output Format
Output the minimal number of integers that should be replaced to make the sequence strictly increasing.
Given your input, len = 5, arr = [1 2 2 3 4], after minus index+1, get [0 0 -1 -1 -1].
Ignoring negative elements(these must be changed), compute Longest Increasing Subsequence(nondecreasing for this problem), which is a classic Dynamic Programming problem.
Denote the length of LIS = n(these elements will not be changed). So the final answer(the part doesn't belong to the increasing subsequence and the ignored negative part) is len-n(5-2=3).
We can compute LIS in O(nlogn) time with O(n) space.
int solve(vector<int> &arr) {
int len = arr.size();
for(int i = 0; i < len; i++) {
arr[i] -= i+1;
}
vector<int> lis(len,0);
int n = 0;
for(int i = 0; i < len; i++) {
if(arr[i] >= 0) {
int pos = binarysearchPos(lis,n,arr[i]);
lis[pos] = arr[i];
if(n == pos)
n++;
}
}
return len-n;
}
int binarysearchPos(vector<int> &arr, int n, int target) {
if(n == 0)
return 0;
if(arr[n-1] <= target)
return n;
int low = 0, high = n-1;
while(low < high) {
int mid = (low+high)/2;
if(arr[mid] > target) {
high = mid;
} else {
low = mid+1;
}
}
return low;
}
I'm having issues with a sort method I wrote. It is supposed to find the max value, and replace the last value in the array with the max (and move that value to where the last value was).
I've ran gdb, and it looks like the if statement always executes, and for some reason max = values[0] always sets max to 0. Granted I am very new to C so I might be wrong about what is going on.
/**
* Sorts array of n values.
*/
void sort(int values[], int n)
{
// TODO: implement an O(n^2) sorting algorithm
int max; //hold the max value through the iteration
int replaced; //to hold the value at the end of the array
int replacedhash; //to hold the location of the max value
do
{
replaced = values[n];
max = values[0]; //reset max to 0 for new iteration
for(int i = 0; i<n ; i++)
{
//check if the next value is larger,
//then update max and replacedhash if it is
if (max < values[i])
{
max = values[i];
replacedhash = i;
}
}
values[replacedhash] = replaced; //next three lines swap the values
n--;
values[n] = max;
} while (n!=0);
}
And I would use this by running:
int main() {
int test[] = {3,5,2,5,6,100,4,46};
sort(test, 8);
printarray(test, 8);
}
Error 1: replaced = values[n-1];
Your example in the problem statement is:
int test[] = {3,5,2,5,6,100,4,46};
sort(test, 8);
So you'll then look at test[8], which is undefined behavior
Error 2: replacedhash
replacedhash will be uninitialized if the first element of the array is the max. And it will probably have an incorrect value on later loops when the first element is the max.
My thoughts:
It appears to me that you've overcomplicating the code. You probably should just find the index in the array that has the maximum value, and then do the swap. It'll be simpler.
void sort(int values[], int n) {
do {
// Find index of maximum value
int max = 0;
for(int i=0; i<n; i++)
if (values[max] < values[i])
max = i;
// Swap
int temp = values[max];
values[max] = values[n-1];
values[n-1] = temp;
n--;
} while (n != 0);
}
Is the fastest algorithm for searching an unsorted array for an element linear search? I mean I guess a combination of merge sort + binary search would be slower. Are there any other options? (in terms of algorithms not involving multithreading)?
Yes, if the array is unsorted and that's all you know about its structure then the fastest way to search for an element is to consider every one which takes linear time O(n).
If you are going to be searching the array a lot then you may want to consider an initial sort and then insert elements into their correct sorted index (using binary search). This means that you have your initial sort as O(n log n) but each insert and search takes O(log n). It's all about tradeoffs and whether that is better than O(1) insert and O(n) search.
You said no multithreading but that is an easy way to boost performance, have multiple threads look at different chunks in the list.
I have created a method for searching an element in an unsorted array.
#include <iostream>
#include <vector> // for 2D vector
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<vector<int>> vect{ {0},{0},{0},{0},{0},{0},{0},{0},{0},{0} };
int count[10];
int min = INT_MAX;
int max = INT_MIN;
for (int i = 0; i < 10; i++)
{
count[i] = 0;
}
for (int i = 0; i < 7; i++)
{
//input 7 integers
int ip,
rem;
cin >> ip;
rem = ip % 10;
if (ip > max)
max = ip;
if (min > ip)
min = ip;
if (vect[rem][0] == 0 && count[rem] == 0)
{
vect[rem][0] = ip;
count[rem]++;
}
else
{
vect[rem].push_back(ip);
count[rem]++;
}
}
int find;
int flag = 0;
cin >> find;
int rem = find % 10;
if (find>max || find<min || count[rem] == 0)
cout<<"not present in the array";
else
{
for (int i = 0; i < vect[rem].size(); i++)
{
if (vect[rem][i] == find)
{
cout << "found";flag = 1;
break;
}
}
if(flag == 0)
cout<<"not present in the array";
}
return 0;
}
I see that this can be faster.
Basically I'm storing the elements in a 2D vector once I receive it.
I'm taking the remainder of the number (number % 10) as the index for the vector and pushing those elements.
Now to search the element, I'm traversing only the elements present in that specific index of the vector.
In this way, the number of comparisons are less.