Trying to find the most popular element of array - arrays

This is my last try. I tried to find the most popular element in a string, for do this i've taken the string and converted single character in number and after this i sorted them in int array.
the problem is: when i use the 2d array for keep the frequency of each number: x[1][y]. and which number: x[0][y]. for some reason they are trash number
can someone help me?
(my english is rusty, sry).
#include<stdio.h>
#include<time.h>
#include<math.h>
#include<string.h>
#include<conio.h>
#include<ctype.h>
#include<stdlib.h>
#include<malloc.h>
void bubble(int a[],int x);
void frequenza(int A[], int n);
int main(){
size_t counter;
char a[] = "asrfujefwaa";
int b[20];
int x;
x = strlen(a);
for(counter = 0; counter != strlen(a); counter ++)
{
b[counter] = a[counter];
}
bubble(b,x);
for(counter = 0; counter != x; counter ++)
{
printf("%d ",b[counter]);
}
puts("\n");
system("pause");
puts("\n");
frequenza(b,x);
return 0;
}
void bubble(int a[],int x)
{
size_t i;
int ord;
int scambio;
scambio = 0;
if(ord == 1)
{
return;
}
else
{
ord = 1;
for(i = 0; i < x - 1; i++)
{
if(a[i] > a[i + 1])
{
scambio = a[i];
a[i] = a[i + 1];
a[i + 1] = scambio;
ord = 0;
}
}
bubble(a,x);
}
}
void frequenza(int A[], int n)
{
int x[2][n];
int z = 0;
int y = 0;
size_t q;
x[0][0] = A[0];
x[1][0] = 1;
for(z = 0; z != n; z++)
{
if(x[0][y] == A[z + 1])
{
x[1][y] += 1;
}
if(x[0][y] != A[z + 1])
{
y++;
x[0][y] = A[z + 1];
}
}
for(z = 0; z != 2; z++)
{
puts("\n");
for(q = 0; q != y;q++)
{
printf("%d ",x[z][q]);
}
}
}

If you want to find the most common character in a string, you don't need to sort it or anything fancy. Just iterate through the characters, recording how many times each one has been seen, and get the maximum such count. You can do it all with a single pass through the string if you keep track of the maximum to date as you go:
#include <limits.h>
#include <stdio.h>
int main(void)
{
char a[] = "asrfujefwaa";
int freqs[UCHAR_MAX + 1] = { 0 }; // Initialize frequency table to all 0's
int most_common = 0;
for (unsigned char *c = (unsigned char *)a; *c; c++) {
if (++freqs[*c] > freqs[most_common]) {
most_common = *c;
}
}
printf("Most common character is %c, with %d occurrences.\n",
most_common, freqs[most_common]);
return 0;
}

Related

iterative permute function in C

I'm trying to write an iterative function that computes all the permutations of an array of numbers given in input.
Here is the code I've written so far.
void permute(int *a, int size){
int j=0, i, h=0, m;
bool flag=true;
int f = factorial(size);
int *arr, *res;
int counter=0;
arr = malloc(f*sizeof(int));
for(i=0; i<f; i++)
arr[i] = 0;
while (j < f) {
if(arr[j]<j)
{
if(j%2 == 0)
{
swap(a[0],a[j]);
} else {
swap(a[arr[j]], a[j]);
}
arr[j]++;
j=0;
} else{
arr[j] = 0;
j++;
}
printf("%d\n",a[j] );
}
}
The code doesn't compute well all the permutations and goes into a long loop. Can someone help me, please? Thanks to everyone.
Your code is close but includes some problems. For instance, the while loop
while (j < f) will assign j to a value out of bound of the array a.
Instead would you please try:
#include <stdio.h>
#include <stdlib.h>
int factorial(int x)
{
int i;
int y = 1;
for (i = 1; i <= x; i++) {
y *= i;
}
return y;
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(int *a, int size)
{
int i, j = 0;
int f = factorial(size);
int *arr;
arr = calloc(f, sizeof(int)); // the members are initialized to 0
// print the original array
for (i = 0; i < size; i++) {
printf("%d%s", a[i], i == size - 1 ? "\n" : " ");
}
while (j < size) {
if (arr[j] < j) {
if (j % 2 == 0) {
swap(a + 0, a + j);
} else {
swap(a + arr[j], a + j);
}
// print the rearranged array
for (i = 0; i < size; i++) {
printf("%d%s", a[i], i == size - 1 ? "\n" : " ");
}
arr[j]++;
j = 0;
} else {
arr[j] = 0;
j++;
}
}
free(arr);
}
int main()
{
int a[] = {1, 2, 3}; // example
permute(a, sizeof a / sizeof a[0]); // the 2nd argument is the array length
return 0;
}
Output of the example:
1 2 3
2 1 3
3 1 2
1 3 2
2 3 1
3 2 1

C.Heapsort .Count the number of swaps and comparisons

The sorting seems to be working correctly. At least it sorts correctly :) It remains only to count the number of comparisons and swaps. How to calculate and output it?Somehow stalled at this point.. I will be very grateful for your help.If you demonstrate it with the updated code , I will be doubly grateful.
#include <stdio.h>
#include <stdlib.h>
void keyDown(int* arr, int n, int head)
{
int j;
if(2*head + 2 < n && arr[2*head + 1] < arr[2*head + 2])
{
j = 2*head + 2;
}
else j = 2*head + 1;
while(arr[head] < arr[j] && head < n / 2)
{
int tmp = arr[head];
arr[head] = arr[j];
arr[j] = tmp;
head = j;
if(2*head + 2 < n && arr[2*head + 1] < arr[2*head + 2])
{
j = 2*head + 2;
}
else j = 2*head + 1;
}
}
void heapSort(int* arr, int n)
{
int i;
for(i = n/2 - 1; i >= 0; i--)
{
keyDown(arr,n,i);
}
int l = n;
while(l > 1)
{
l--;
int tmp = arr[l];
arr[l] = arr[0];
arr[0] = tmp;
keyDown(arr,l,0);
}
}
int main(int argc, char *argv[]) {
int n=10;
int start, end,i;
int *arr;
arr=(int *)malloc(n*sizeof(int));
time_t invocation_time = time(NULL);
srand(invocation_time);
int s;
for (s=0;s<n;s++)
{
arr[s] = rand() % 50;
printf ("%d \n", arr[s]);
}
printf ("\n");
heapSort(arr, n);
for (i=0;i<n;i++){
printf ("%d \n", arr[i]);
}
return 0;
}
count the number of comparisons and swaps
make functions
//global counters
unsigned comparisons = 0, swaps = 0;
int lessthan(int a, int b) {
comparisons++;
return (a < b);
}
void swap(int *a, int *b) {
swaps++;
int tmp = *a; *a = *b; *b = tmp;
}
and then replace comparisons and swaps in your existing code with the specific function you need.
int main(int argc, char **argc) {
//...
if (lessthan(a[i], a[j])) swap(a+i, a+j);
//...
printf("comparisons: %u; swaps: %u\n", comparisons, swaps);
}

Count number of elements in array after placing them in ascending order

I'm creating a program that reads input from an array and orders it in an ascending order. However, I also wanted to count the number of times each element appears in the array, but I'm struggling to to this. This is the code I have so far:
#include <stdlib.h>
#include <locale.h>
typedef enum _ordem {
Crescente=1
} ordem;
void troca(int *x, int *y){
int wk;
wk=*x;*x=*y;*y=wk;
}
int trocar(int x, int y, ordem dir){
if(dir == Crescente)
return x > y;
return 0;
}
void bubbleSort(int *array, int top, int fim, ordem dir){
int i, j, trocado;
for(i = top; i < fim; ++i){
trocado = 0;
for(j = top + 1; j <= fim - i; ++j)
if(trocar(array[j-1], array[j], dir)){
troca(&array[j-1], &array[j]);
trocado = 1;
}
if(trocado == 0)break;
}
}
int main(){
int vetor[100], index, ordem=1;
index=0;
setlocale(LC_ALL,"Portuguese");
printf("Introduza os nĂºmeros. Escreva -00 para parar. \n");
do{
scanf("%d", &vetor[index++]);
}while(vetor[index-1] != -00 && index < 100);
--index;
bubbleSort(vetor, 0, index-1, ordem);
{
int i;
for(i=0;i<index;++i)
printf("%d ", vetor[i]);
printf("\n");
}
return 0;
}
After the numbers have been sorted, equal numbers will be next to each other in the array. This makes it easy to count the number of times each number occurs using a single loop that iterates through the sorted array, with an extra variable that is incremented when the next element has the same number as the current element, or is reset when the next element has a different number.
The following block of code will do that:
{
int i, c;
c = 1;
for (i = 0; i < index; ++i) {
if (i < index - 1 && vetor[i] == vetor[i + 1]) {
c++;
} else {
printf("%d(x%d) ", vetor[i], c);
c = 1;
}
}
printf("\n");
}
You could create another array to store a table of the unique values with their frequency of occurrance:
struct freq {
int val;
int freq;
};
struct freq freq[100];
int nfreq = 0;
Fill the table using a loop similar to the earlier code:
{
int i, c;
c = 1;
for (i = 0; i < index; ++i) {
if (i < index - 1 && vetor[i] == vetor[i + 1]) {
c++;
} else {
freq[nfreq].val = vetor[i];
freq[nfreq].freq = c;
nfreq++;
c = 1;
}
}
}
Print the out the table with another simple loop:
{
int i;
for (i = 0; i < nfreq; i++) {
printf("%d(x%d) ", freq[i].val, freq[i].freq);
}
printf("\n");
}

sort function won't print sorted array?

My sort function won't print the sorted array?
I'm trying to write a program that gathers array elements, sorts the array, then prints the factorial of each element. I don't want to get ahead of myself and write the recursive function if the array isn't being sorted correctly. The sort seems fine to me; people have criticized me using while loop but I don't know another way yet. Any input is appreciated.
#include <stdio.h>
int sorter(int numbList[]);
int getData(int numList[]);
//int recursive(int numList[]);
int main(void) {
int x;
int numberList[x];
getData(&numberList[x]);
sorter(&numberList[x]);
//recursive(&numberList[x]);
return 0;
}
//gets user input-data
int getData(int numbList[]) {
int i;
int x;
printf("Enter number of Elements:\n");
scanf("%d", &x);
printf("Enter the values for each element starting from first
element:\n");
for (i = 0; i < x; i++) {
scanf("%d", &numbList[i]);
}
printf("\nYou have filled the array list with\n");
for (i = 0; i < x; i++) {
printf("%d\n", numbList[i]);
}
return numbList[x];
}
//sorter function
int sorter(int numbList[]) {
int x;
int temp;
int swapped;
while (1) {
swapped = 0;
for (int i = 0; i < x; i++) {
if (i > numbList[i + 1]) {
temp = numbList[x];
numbList[x] = numbList[x + 1];
numbList[x + 1] = numbList[x];
swapped = 1;
}
if (swapped == 0) {
break;
}
}
printf("Array as sorted:\n");
for (int i = 0; i < x; i++) {
printf("%d\t", numbList[x]);
}
return(numbList[x]);
}
}
//recursive factorial function
/* int recursive(int numbList[]) {
int b = 0;
numbList[b] *= numbList[b - 1];
return 0;
} */
Some hints as comments in your code:
It still won't do the job, but get you in better shape...
int main(void)
{
//uninitialized x!
int x;
//Even if you get a value for x, VLAs are depreciated
int numberList[x];
//Both calls get the adress of last value + 1 in numberList.
//So you a) go out of the array bounds, and b) why would you want
//the last element's address??
//Just use it like getData(numberList);
getData(&numberList[x]);
sorter(&numberList[x]);
return 0;
}
//gets user input-data
//What is the return value for?
int getData(int numbList[])
{
int i;
int x;
printf("Enter number of Elements:\n");
scanf("%d",&x);
printf("Enter the values for each element starting from first element:\n");
for(i=0;i<x;i++){
scanf("%d",&numbList[i]);
}
printf("\nYou have filled the array list with\n");
for(i=0;i<x;i++){
printf("%d\n",numbList[i]);
}
//see above
return numbList[x];
}
//sorter function
//Again, what and why return?
int sorter(int numbList[])
{
//uninitialized x!
int x;
int temp;
int swapped;
while(1)
{
swapped=0;
for(int i=0;i<x;i++)
{
//What do you compare here? Think.
if(i>numbList[i+1])
{
temp=numbList[x];
numbList[x]=numbList[x+1];
//What do you have temp for??
numbList[x+1]=numbList[x];
swapped=1;
}
//Pretty sure you want an else clause here
if(swapped==0)
{
break;
}
}
printf("Array as sorted:\n");
for(int i=0;i<x;i++)
{
printf("%d\t",numbList[x]);
}
return(numbList[x]);
}
}
There are multiple problems in your code:
the number of elements x is uninitialized when you define the array numbList[x]. This has undefined behavior. You should pass a pointer to the count to getData and this function should update this value, allocate the array, read the values and return a pointer to the array.
You should not break strings on multiple lines without a \
The swap code is broken: the test if (i > numbList[i + 1]) is incorrect, it should be
if (numbList[i] > numbList[i + 1])
the swap code should use i instead of x as an index and the last assignment in the swap code should store temp into numbList[i + 1].
the inner loop should stop at x - 1 to avoid reading past the end of the array.
you should let the inner loop run to the end and break from the outer loop if swapped == 0.
Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
int *getData(int *count);
void sorter(int numList[], int count);
int main(void) {
int x;
int *numberList;
numberList = getData(&x);
if (numberList != NULL) {
printf("Elements entered:");
for (int i = 0; i < x; i++) {
printf(" %d", numberList[i]);
}
printf("\n");
sorter(numberList, x);
printf("Sorted array:");
for (int i = 0; i < x; i++) {
printf(" %d", numberList[i]);
}
printf("\n");
free(numberList);
}
return 0;
}
//gets user input-data
int *getData(int *countp) {
int i, x;
int *numbList;
printf("Enter the number of elements: ");
if (scanf("%d", &x) != 1 || x <= 0) {
printf("Invalid size:");
return NULL;
}
numbList = calloc(sizeof *numbList, x);
if (numbList == NULL) {
printf("Memory allocation error:");
return NULL;
}
printf("Enter the element values: ");
for (i = 0; i < x; i++) {
if (scanf("%d", &numbList[i]) != 1) {
free(numbList);
return NULL;
}
}
*countp = x;
return numbList;
}
//sorter function
void sorter(int numbList[], int x) {
for (;;) {
int swapped = 0;
for (int i = 0; i < x - 1; i++) {
if (numbList[i] > numbList[i + 1]) {
int temp = numbList[i];
numbList[i] = numbList[i + 1];
numbList[i + 1] = temp;
swapped = 1;
}
}
if (swapped == 0) {
break;
}
}
}
You can use bubble sort algorithm technique which is fast sorting algorithm and it uses for loop instead of while loop
int bubbleSorter(int numbList[])
{
int temp;
int i, x;
bool swapped = false;
for (i = 0; i < x - 1; i++)
{
swapped = false;
for (j = 0; j < x - 1 - i; j++)
{
if (list[j] > list[j + 1])
{
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
swapped = true;
}
else {
swapped = false;
}
}
// if no number was swapped that means
// array is sorted now, break the loop.
if (!swapped) {
break;
}
printf("Array as sorted:\n");
for (int i = 0; i<x; i++)
{
printf("%d\t", numbList[x]);
}
return(numbList[x]);
}
}

How to take input of a number and display it in descending order?

I am fairly new to C programming .
If the user enters a number lets say 123.
How can i print out 321?
I tried using bubble and selection sort but i find them very hard to understand at this initial stage!
I was hoping somebody could help me understand it by breaking it out !
Please help
Thank You
Here you go!
#include <stdio.h>
#include <string.h>
int main()
{
int n ;
int m ;
int i, j, jMax, max=0, res = 0;
int len = 0;
printf("Input number\n");
scanf("%d", &n);
m = n;
do // compute length of array that contains our input number
{
n /= 10;
len++;
}
while (n > 0);
n = m; // copy back input number
int * arr = malloc(len*sizeof(int)); // allocate memory for the array
len = 0; // initialize len for loop use
do // fill the array of input number
{
arr[len] = n%10;
n/=10;
len++;
}
while (n > 0);
//sort
int * sort = malloc(len*sizeof(int));
for(i = 0; i< len; i++)
{
for(j = 0; j<len; j++)
{
if(arr[j] > max)
{max = arr[j]; jMax = j;}
}
arr[jMax] = 0;
sort[i] = max;
max = 0;
}
// convert back from array to an int
j = 1;
for (i=0; i< len; i++)
{
res += sort[len-i-1]*j;
j *= 10;
}
printf(" %d", res);
return 0
}
You can take the user input as string, and print the string in reverse order, using a loop or recursion, but since you are new to c , I would say, go with chux's solution.
The below code does both reversing the entered number as well as arranging the entered number in the descending order.
You can try the below code:
int main()
{
int n,m,len,i,j,max=0,x;
printf("Enter the number\n");
scanf("%d",&n);
m = n;
len = 0;
printf("Number in the reverse order\n");
while(n>0)
{
n=n/10;
printf("%d",(n%10));
len++;
}
printf("\n");
printf("Numbers in descending order\n");
int *num = malloc(len*sizeof(int));
i =0;
while(m>0)
{
num[i++] = m%10;
m= m/10;
}
/* Any sorting technique can be used to sort the array */
for(i=0;i<len;i++)
{
max = num[i];
x = i;
for(j=i+1;j<len;j++)
{
if(num[j] > max)
{
max = num[j];
x = j;
}
}
num[x] = num[i];
num[i]= max;
}
/* Priting the entered number in descending order */
for(i=0;i<len;i++)
printf("%d",num[i]);
printf("\n");
return 0;
}
#include <stdio.h>
static inline char *max_c(size_t size, const char array[size]){
const char *p = array;
for(int i=1;i<size;++i){
if((unsigned char)*p < array[i])
p = array + i;
}
return (char*)p;
}
static inline void swap(char *a, char *b){
char tmp = *a;
*a = *b;
*b = tmp;
}
int main(void) {
char digits[32];
int len;
printf("input nums : ");
scanf("%31[0-9]%n", digits, &len);
for(int i = 0; i<len-1 ; ++i){
//swaped with the first element to select an element of maximum
swap(max_c(len - i, digits + i), &digits[i]);
}
printf("%s\n", digits);
return 0;
}
Just converting the int to a string using sprintf then reversing the string would probably be the easiest.
#include <stdio.h>
#include <string.h>
int main(){
int num = 123;
char str[15];
char backwards[15];
int i, j = 0;
sprintf(str,"%d",num);
for(i = strlen(str) - 1; i >= 0; i--){
backwards[j++] = str[i];
}
backwards[j] = '\0';
printf("%s\n",backwards);
return 0;
}
Then if you need to turn it back into an int then using atoi would do the trick.
//Remember to include this if you use atoi
#include <stdlib.h>
//Then just use this after you have reversed the string to
//convert it back to type int
num = atoi(&backwards);

Resources