I have this homework assignment where the user would enter 10 numbers and would find the mode of those 10 numbers. I got one mode working, my question is I dont know how to start finding multiple modes in the array. EX. 1 1 2 2 3 4 5 6 7 8 The mode of the array is 1,2
Here's the code for the mode
void displayMode(int numArray[])
{
int countArray[MAX];
int modeCount = 0;
int modeNumber;
int i = 0;
int j = 0;
for(i=0; i < MAX; i++)
{
countArray[i] = 0;
}
for(i=0; i < MAX; i++)
{
for (j = 0; j < MAX; j++)
{
if (numArray[i] == numArray[j])
countArray[i]++;
}
}
for (i=0; i < MAX; i++)
{
if (countArray[i] > modeCount)
{
modeCount = countArray[i];
modeNumber = numArray[i];
}
}
if (modeCount > 1)
printf("\nThe mode of the array is: %d",modeNumber);
else
printf("\nThe mode of the array is: None");
}
You need to use a container with size. This is easily achievable with std::vector in C++, but anyway, this is a rough (not memory efficient) implementation in C.
Use modeNumbers instead of one, and create a variable for size:
int modeNumbers[MAX];
size_t modeSize = 0;
Then, append with size:
if (countArray[i] > modeCount)
{
modeCount = countArray[i];
modeNumbers[0] = numArray[i];
modeSize = 1;
} else if (countArray[i] == modeCount) {
modeNumbers[modeSize++] = numArray[i];
}
Finally, use a for loop to output it:
if (modeCount > 1) {
printf("\nThe mode of the array is: ");
for (size_t i = 0; i < modeSize; ++i) { printf("%s%d", i == 0?"":", ", modeNumbers[i]; }
} else {
printf("\nThe mode of the array is: None");
}
Related
I have written a program with a function that looks at a two dimensional array ir_data[60][768].
The While loop should call the "Hotspotberechnung" function only when there is a value that equals or is over 30 in a given row.
"Hotspotberechnung" should store the given row in an array[24][32] and then print the array.
The problem is that the program prints an array without any values equal or over 30.
Unfortunately, I cannot find the mistake on my own.
The While Loop:
int8_t Temperatur[768] = {0};
while (get_ir_data( &Temperatur[0], sizeof(Temperatur)/sizeof(Temperatur[0])) == 0)
{
for(int k=0; k<768; k++)
{
if(Temperatur[k] >= 30)
{
Hotspotberechnung(Temperatur,bild);
}
}
}
The function :
bool Hotspotberechnung(int8_t tabelle1[768],int8_t tabelle2[24][32])
{
int i=0, j=0, x=0, y=0;
for(j=0; j<24; j++) //Tabellen werden gefüllt
{
for(i=0; i<32; i++)
{
tabelle2[j][i] = tabelle1[(j*24)+i];
}
}
for(j=0; j<24; j++)
{
for(i=0; i<32; i++)
{
printf("%d.%d=%d\n",j,i,tabelle2[j][i]);
}
}
get_ir_data :
int8_t get_ir_data(int8_t* data, int n)
{
static uint8_t idx = 0;
if (n != 24 * 32) {
printf("Invalid size of array data!\n");
return -1;
}
memcpy(data, ir_data[idx], n);
idx++;
if (idx >= sizeof(ir_data) / sizeof(*ir_data))
return -2;
return 0;
}
tabelle1[(j*24)+i]
This index calculation is wrong. You need
tabelle1[(j*32)+i]
To verify, calculate the maximal value of (j*24)+i, given the ranges of j (0 to 23) and j (0 to 31). Is it 767?
Im a beginner programmer and i needed some help with making the result of the following exercise look a bit better.
As i said in the title i want to make the exercise look nicer by removing the 0-s from the array and leaving just the numbers.
The exercise goes like this:
We enter an array of integers and we copy into the 2nd array the integers that are positive and negative and multiples of 3 and in the 3rd array the negative elements that are odd and not multiples of 3. This is the code that I did:
#include <stdio.h>
#include <stdlib.h>
#define N 5
int main()
{
int v[N];
int v2[N] = {0, };
int v3[N] = {0, };
int i;
printf("Please enter the elements of the 1st array: ");
for (i = 0; i < N; i++)
{
scanf("%d", &v[i]);
}
printf("\nThe elements of the 2nd array are: ");
for (i = 0; i < N; i++)
{
if ((v[i] >= 0 || v[i] <= 0) && v[i] % 3 == 0)
{
v2[i] = v[i];
}
}
for (i = 0; i < N; i++)
{
printf("%d ", v2[i]);
}
printf("\nThe value of the 3rd array are : ");
for (i = 0; i < N; i++)
{
if (v[i] <= 0 && v[i] % 2 != 0 && v[i] % 3 != 0)
{
v3[i] = v[i];
}
}
for (i = 0; i < N; i++)
{
printf("%d ", v3[i]);
}
return 0;
}
For future use if possible how to do I post a code copied for code blocks directly into here without using space 4 times on every line?
Thanks in advance
Another option is to insert a condition in the output loop:
for (i = 0; i < N; i++)
{
if (v2[i] != 0)
{
printf("%d ",v2[i]);
}
}
I had a task and the program is working, for the most part, however, it crashes if I put SPLIT value between 4 and 7 (crashes at different values, if I change SIZE, but for sake of simplicity, let's keep it at 10).
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
#define SIZE 10
#define SPLIT 4
#define LOW 0
#define HIGH 10
void generateArray(int data[],int size,int low, int high){
srand(time(NULL));
for(int i=0;i<size;++i){
data[i]=rand()%(high-low+1)+low;
}
}
int splitData(int arraySize, int startArray[], int splitPoint, int **firstNewArray, int **secondNewArray){
if(arraySize < 1){
return -1;
}
if(splitPoint < 1 || (splitPoint >= arraySize)){
return -1;
}
if(*firstNewArray != NULL || *secondNewArray != NULL){
return -1;
}
*firstNewArray = malloc(splitPoint * sizeof(int));
*secondNewArray = malloc((arraySize - splitPoint) * sizeof(int));
for(int i = 0; i < arraySize; ++i){
if(i < splitPoint){
(*firstNewArray)[i] = startArray[i];
printf("%d\n",startArray[i]);
}else{
(*secondNewArray)[i] = startArray[i];
printf("%d\n",startArray[i]);
}
}
return 0;
}
int main(){
int arraySize = SIZE ;
int *startArray = malloc(arraySize * sizeof(int));
generateArray(startArray,arraySize,LOW,HIGH);
int splitPoint = SPLIT;
int *firstNewArray = NULL;
int *secondNewArray = NULL;
int result;
result = splitData(arraySize, startArray, splitPoint, &firstNewArray, &secondNewArray);
if(result == 0){
for(int i = 0; i < arraySize; ++i){
if(i < splitPoint){
printf("First array number %d is %d\n",i+1,firstNewArray[i]);
}else{
printf("Second array number %d is %d\n",i,secondNewArray[i]);
}
}
free(firstNewArray);
free(secondNewArray);
}
free(startArray);
return 0;
}
What could be the cause of this behavior and how could I fix it? The task is to split startArray by the value SPLIT into 2 new dynamic arrays, that would be created in a function splitData and both of them could be used outside the function.
You have two issues with your code
first when you display the results:
for(int i = 0; i < arraySize; ++i){
if(i < splitPoint){
printf("First array number %d is %d\n",i+1,firstNewArray[i]);
}else{
printf("Second array number %d is %d\n",i,secondNewArray[i]);
}
}
This will not work specialy if array size is too higth or too low, example splitPoint is 9, this means secondNewArray Size is 1 but in this loop you are accessing secondNewArray[9] where it should be 0, you need to change the loop into something like this
for(int i = 0; i < splitPoint; ++i){
printf("First array number %d is %d\n",i+1,firstNewArray[i]);
}
for(int i = 0; i < SIZE - splitPoint; ++i){
printf("Second array number %d is %d\n",i+splitPoint+1 ,secondNewArray[i]);
}
You have the same isssue in your split function:
for(int i = 0; i < arraySize; ++i){
if(i < splitPoint){
(*firstNewArray)[i] = startArray[i];
printf("%d\n",startArray[i]);
}else{
(*secondNewArray)[i] = startArray[i];
printf("%d\n",startArray[i]);
}
}
In this case also you are accessing regions outside the size of your array, let say split is 9 you will be accessing secondNewArray[9] = startArray[9] where it should be secondNewArray[0] = startArray[9], to fix this you need to do the same thing here where you use different index for each array, the code should look like this:
int j = 0;
int k = 0;
for(int i = 0; i < arraySize; ++i){
if(i < splitPoint) {
(*firstNewArray)[j] = startArray[i];
printf("%d\n",startArray[i]);
j++;
}
else {
(*secondNewArray)[k] = startArray[i];
printf("%d\n",startArray[i]);
k++;
}
}
Take a hard look at the marked line below
for(int i = 0; i < arraySize; ++i){
if(i < splitPoint){
(*firstNewArray)[i] = startArray[i];
printf("%d\n",startArray[i]);
}else{
(*secondNewArray)[i] = startArray[i]; // LOOK HERE
printf("%d\n",startArray[i]);
}
Assuming an array size of 10 and a split point of 4, then *secondNewArray is indexed from 0 to 5; however, you’re trying to assign elements 4 through 9, which is outside the bounds of the array, leading to undefined behavior. You need to adjust the value of i in order to map properly:
(*secondNewArray)[i - splitPoint] = startArray[i];
I have a homework problem. It requires us to make a matrix based on user's input. For example : if user input 4 so the matrix will be 4 X 4. After that, the program will check if the matrix has the same value in a row or column. and it will give yes or no output.
For example :
input :
2
1 2
2 1
Output :
Yes
(because that matrix doesnt has a same value in a row or a column.)
Input 2 :
3
4 5 6
7 8 9
7 3 3
Output :
No
(Because that matrix have same values in a row or column (3 & 3 and 7 & 7)
Input 3:
2
1 2
3 2
Output :
No
(because that matrix have same value on column 1.)
Input 4
2
1 1
3 4
Output :
No
(because that matrix has same value in first row(1 1)
I have tried to do that, but some 'cases' still doesnt work. For example, i tried to include a count in my code but some of the count is not true.
example :
input :
4
3 4 5 6
2 3 4 5
6 5 6 3
5 4 6 3
OUTPUT :
No
count : 2
(it supposed to be 3 because it has the same value which are 6 (on row 3), 6 on column 3, and 3 on column 4.)
#include "stdio.h"
int main()
{
int matrix[500][500];
int testcase;
int count = 0;
scanf("%d",&testcase); getchar();
for(unsigned i = 0; i < testcase; i++) {
for(unsigned j = 0; j < testcase; j++) {
scanf("%d",&matrix[i][j]); getchar();
}
}
// printf("[0,0] = %c",matrix[0][0]);
// printf("\n[0,1] = %c",matrix[0][1]);
// printf("\n[1,0] = %c",matrix[1][0]);
// printf("\n[1,1] = %c",matrix[1][1]);
for(unsigned i = 0; i < testcase; i++) {
for(unsigned j = 0; j < testcase; j++) {
if(matrix[i][j] == matrix[i][j+1]) {
count = count + 1;
}
else if(matrix[i][j] == matrix[i+1][j]) {
count = count + 1;
}
}
}
if(count > 0) {
printf("No\n");
} else{
printf("Yes\n");
}
printf("Count : %d\n",count );
getchar();
return 0;
}
As I see you check if 2 numbers of the same value differ only one column or one row here:
if(matrix[i][j] == matrix[i][j+1]) {
count = count + 1;
}
else if(matrix[i][j] == matrix[i+1][j]) {
count = count + 1;
}
I think that you might need a temp variable so that you can scan each line and then each column separately , for example:
temp = matrix[i][j];
if(checkRow(temp, i, j, matrix, testcase) == true) count++;
if(checkColumn(temp, i, j, matrix, testcase) == true) count++;
and the checkRow would be something like this:
bool checkRow(int temp, int row, int col, int matrix[][500], int size)
{
for(int i=col; i < size;)
{
if(temp == matrix[row][i]) return true;
}
return false;
}
and respectively you will build the checkColumn function.
EDIT:
Since you told me you haven't learned how to use functions yet, this would be your final program. It works and I might suggest that the final test case should output "count = 4" since there is a case that you might missed.
Here is the code:
#include "stdio.h"
int main()
{
int matrix[500][500];
int testcase;
int count = 0;
scanf("%d",&testcase); getchar();
int temp;
for(unsigned i = 0; i < testcase; i++) {
for(unsigned j = 0; j < testcase; j++) {
scanf("%d",&matrix[i][j]); getchar();
}
}
// printf("[0,0] = %c",matrix[0][0]);
// printf("\n[0,1] = %c",matrix[0][1]);
// printf("\n[1,0] = %c",matrix[1][0]);
// printf("\n[1,1] = %c",matrix[1][1]);
for(unsigned i = 0; i < testcase; i++) {
for(unsigned j = 0; j < testcase; j++) {
temp = matrix[i][j];
//Scan current row
for(unsigned k = j+1; k < testcase; k++)
{
if(temp == matrix[i][k])
{
count++;
break;
}
}
//Scan current column
for(unsigned k = i+1; k < testcase; k++)
{
if(temp == matrix[k][j])
{
count ++;
break;
}
}
}
}
if(count > 0) {
printf("No\n");
} else{
printf("Yes\n");
}
printf("Count : %d\n",count );
getchar();
return 0;
}
May I suggest that before you copy the code you must understand the algorithm that lies behind it. It's simple and brute force thinking.
I am trying to read list of numbers from txt file and then sort them with Bucket sort.
so here is my code:
void bucketSort(int array[],int *n)
{
int i, j;
int count[*n];
for (i = 0; i < *n; i++)
count[i] = 0;
for (i = 0; i < *n; i++)
(count[array[i]])++;
for (i = 0, j = 0; i < *n; i++)
for(; count[i] > 0; (count[i])--)
array[j++] = i;
}
int main(int brArg,char *arg[])
{
FILE *ulaz;
ulaz = fopen(arg[1], "r");
int array[100];
int i=0,j,k,n;
while(fscanf(ulaz, "%d", &array[i])!=EOF)i++;
fclose(ulaz);
n=i;
for (j = 0; j<i; j++)
{
printf("Broj: %d\n", array[j]);
}
BucketSort(array,&n);
for (k = 0; k<i; k++)
printf("%d \n", array[i]);
return 0;
}
There are no errors in code,but when i call my function instead of sorted array i get array length random numbers(example: 2 3 5 4,after sorting i get 124520 124520 124520 124520 or some other random number) since i am a beginner,could someone help me with my code and what i did wrong? (sorry for bad english)
As Cool Guy correctly pointed out you have issues with memory access but on top of it the code does not sort anything. First you should read how Bucket Sort actually works.
In general:
You divide the input data among buckets by some criteria that guarantees that the buckets will not mess up the input order
Sort each bucket either using some other sorting method or recursively with bucket sort
Concatenate the sorted data (this is why the first point has the restriction of not messing up the input order)
Here is an example of your original code, I tried to adjust it as little as possible you it is easier for you to understand. This code divides a predefined input array among 3 buckets by range:
[-infinity][-1] -> first bucket
[0;10] -> second bucket
[11;infinity] -> third bucket
then performs Quicksort on each bucket and concatenates the result. I hope this helps to understand how this algorithm works.
#include <stdio.h>
#include <stdlib.h>
struct bucket
{
int count;
int* values;
};
int compareIntegers(const void* first, const void* second)
{
int a = *((int*)first), b = *((int*)second);
if (a == b)
{
return 0;
}
else if (a < b)
{
return -1;
}
else
{
return 1;
}
}
void bucketSort(int array[],int n)
{
struct bucket buckets[3];
int i, j, k;
for (i = 0; i < 3; i++)
{
buckets[i].count = 0;
buckets[i].values = (int*)malloc(sizeof(int) * n);
}
// Divide the unsorted elements among 3 buckets
// < 0 : first
// 0 - 10 : second
// > 10 : third
for (i = 0; i < n; i++)
{
if (array[i] < 0)
{
buckets[0].values[buckets[0].count++] = array[i];
}
else if (array[i] > 10)
{
buckets[2].values[buckets[2].count++] = array[i];
}
else
{
buckets[1].values[buckets[1].count++] = array[i];
}
}
for (k = 0, i = 0; i < 3; i++)
{
// Use Quicksort to sort each bucket individually
qsort(buckets[i].values, buckets[i].count, sizeof(int), &compareIntegers);
for (j = 0; j < buckets[i].count; j++)
{
array[k + j] = buckets[i].values[j];
}
k += buckets[i].count;
free(buckets[i].values);
}
}
int main(int brArg,char *arg[]) {
int array[100] = { -5, -9, 1000, 1, -10, 0, 2, 3, 5, 4, 1234, 7 };
int i = 12,j,k,n;
n=i;
for (j = 0; j<i; j++)
{
printf("Broj: %d\n", array[j]);
}
bucketSort(array, n);
for (k = 0; k<i; k++)
printf("%d \n", array[k]);
return 0;
}
Your code exhibits Undefined Behavior as you try to write into memory location which are not owned by your program.
for (i = 0; i < *n; i++)
(count[array[i]])++;
The above loop is causing the problem. You say that i is 4 which means that *n is also 4 and array contains 2 3 5 4. In the above code,count is an array of *n elements(in this case 4 elements) and the valid indices for the array are count[0],count[1],count[2] and count[3]. Doing
count[array[i]]
when i is zero is okay as it is same as count[2]. This is the same when i is 1 as it would be count[3] . After that ,when i is 4 and 5,count[4] and count[5] are wrong as you try to write to a invalid memory location.
Also,your code dosen't sort the values.