I have a 2 dimensional array. I'm trying to add the digits of each element in the array and find the sum.
For example :
consider my array is: a[2][2] = { {15,11}, {13,21} }.
Now for the element 15 i need to add 1+5 and the result 6 placed in the same position.
and for element 11 1+1 and place the result 2 in the same position. And the same for all other elements.
Following is my code.
int main ()
{
int a[3][2] = { {19,11}, {13,21}, {12,14}};
int i, j;
int digit1,digit2,sum1=0,sum2=0,rem1,rem2;
for ( i = 0; i < 3; i++ )
{
for ( j = 0; j < 2; j++ )
{
digit1 = a[i];
rem1 = digit1%10;
sum1 = sum1 + rem1;
digit1 = digit1/10;
digit2 = a[j];
rem2 = digit2%10;
sum2 = sum2 + rem2;
digit2 = digit2/10;
printf("\nthe sum of i: ", sum1);
printf("\nthe sum of j: ", sum2);
}
}
return 0;
}
But from above code I'm not getting the sum.
I am kinda new to this and got stuck here. Here's the code in EDITOR.
Define a function to compute the sum of the digits of an integer.
int getSumOfDigits(int n)
{
int ret = 0;
while ( n > 0 )
{
ret += (n%10);
n /= 10;
}
return ret;
}
Use the function in the for loop.
for ( i = 0; i < 3; i++ )
{
for ( j = 0; j < 2; j++ )
{
a[i][j] = getSumOfDigits(a[i][j]);
}
}
Its simple. Do the following -
//Assuming the array is a[3][2]
for(int i=0;i<3;i++)
for(int j=0;j<2;j++)
{
int sum = 0;
while(a[i][j])
{
sum+=a[i][j]%10;
a[i][j]/=10;
}
a[i][j]=sum;
}
Inside for loop put this code instead of your code it will work
for ( j = 0; j < 2; j++ )
{
sum1=0;
while(a[i][j]){
sum1=sum1+(a[i][j]%10);
a[i][j]=a[i][j]/10;
}
a[i][j]=sum1;
printf("\nthe sum of [%d][%d]: %d", i,j,sum1);
}
Related
First I generate some random numbers and then i need to exchange them like I discribte in the following lines.
I tryed it iut with the for loobs.
I have to exchange the numbers of the array
Change number 1 and 2, 3 and 4,.....29 and 30
Change number 1 and 3, 4 and 7,.....27 and 30
Thank you for your Help
srand(time(NULL));
for ( i = 0; i < SIZE; i++ )
{
mainArray[i] = rand() % ( UPPERBOUND - LOWERBOUND + 1 ) + LOWERBOUND;
}
for ( i = 0; i < SIZE; i++)
{
if ( countDigitChange == 2 )
{
digitChanger1 = workArray2[i];
i++;
digitChanger2 = workArray2[i];
workArray2[i] = digitChanger1;
i--;
workArray2[i] = digitChanger2;
countDigitChange = 0;
}
countDigitChange++;
}
for ( i = 0; i < SIZE; i++)
{
if ( countDigitChange % 3 == 0 )
{
digitChanger1 = workArray3[i];
i += 2;
digitChanger2 = workArray3[i];
workArray3[i] = digitChanger1;
i += 2;
workArray3[i] = digitChanger2;
countDigitChange = 0;
}
countDigitChange++;
}
This seems much simpler:
Declare a helper function:
void swap_int(int* x, int *y)
{
int tmp = *x;
*x = *y;
*y = tmp;
}
Then in your code that needs to shuffle the array:
int i, j; // declare this up top with all your other variable declarations
// for each pair of elements swap them
for (i=0, j=1; j < SIZE; i+=2, j+=2)
{
swap_int(&mainArray[i], &mainArray[j]);
}
// swap array[0] with array[2], then swap array[3] with array[5], etc...
for (i=0, j=2; j < SIZE; i+=3, j+=3)
{
swap_int(&mainArray[i], &mainArray[j]);
}
I have this weird problem, When I run following code snippet, it gives me wrong answer. I am trying to find smallest positive number from 2D array.
I tried combining two if conditions in one if, placing brackets, interchanging if conditions. But while I debug I see, control never goes inside if greater than 0 condition.
float smallest(float b[3][4]);
int main()
{
float a[3][4],result;
int i, j;
printf("\nEnter 12 numbers into the array:\n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
{
scanf("%f", &a[i][j]);
}
printf("\n");
}
result=smallest(a);
printf("\nSamllest positive number is %.1f", result);
system("pause");
return 0;
}
float smallest(float b[3][4])
{
int i, j;
float min = b[0][0];
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
{
if (b[i][j]<min)
if (b[i][j]>0)
min = b[i][j];
}
}
return min;
}
Enter 12 numbers into the array:
-5
4
9
7
6
2
3
1
-7
5
4
7
Samllest positive number is -5.0
It is becuse you set min to b[0][0] which is -5 in your example, so the only number where if (b[i][j]<min) is true is -7. But your second if only true if the number is greater than 0. Which is false for -7, therefore min = b[i][j]; this code never executes.
Initialize min to FLT_MAX and it should be fine. (Although this could be problematic if the array only contains negative numbers.)
assign first positive value of array to your min and then use your code.
int check = 0;
int i, j;
float min=-2;//this is for case when all elements are negative
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
{
if (b[i][j] > 0)
{
min = b[i][j];
check = 1;
break;
}
}
if (check == 1)
break;
}
so your smallest function:
float smallest(float b[3][4])
{
int check = 0;
int i, j;
float min=-1;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
{
if (b[i][j] > 0)
{
min = b[i][j];
check = 1;
break;
}
}
if (check == 1)
break;
}
if(min<0)
printf("no positive number");
else
{
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
{
if (b[i][j]<min)
if (b[i][j]>0)
min = b[i][j];
}
}
}
return min;
}
you also should check if returned min is navigate or positive in main.
if it was negative no positive value were found.
The function initially is defined incorrectly.
For starters the function shall have a second parameter that specifies the number of "rows" in the array. This function declaration
float smallest(float b[3][4]);
is equivalent to the following function declaration
float smallest(float b[][4]);
and the both declarations declare the same one function the declaration of which is adjusted by the compiler to the fol;lowing
float smallest(float ( *b )[4]);
Secondly the array can have no positive element. SO in this case the function will return an incorrect value.
Th function should return either an index or a pointer to the minimum positive elements. And if the index or the pointer is outside the array then it means that the array does not have a positive element.
Here is a demonstrative program that shows how the function can be defined and how in the caller there can be determine whether the array has a minimum positive element.
#include <stdio.h>
#define N 4
size_t smallest( float a[][N], size_t size )
{
size_t i = 0;
float *p = ( float * )a;
while ( i < size * N && !( 0 < p[i]) ) ++i;
size_t min = i;
for ( ++i; i < size * N; i++ )
{
if ( 0 < p[i] && p[i] < p[min] ) min = i;
}
return min;
}
int main(void)
{
float a[][N] =
{
{ -5, 4, 9, 7 },
{ 6, 2, 3, 1 },
{ -7, 5, 4, 7 }
};
const size_t M = sizeof( a ) / sizeof( *a );
size_t min = smallest( a, M );
if ( min < M * N )
{
printf( "The smallest positive element is %.1f\n", a[min / N][min % N] );
}
else
{
puts( "There ia no minimal positive element in the array" );
}
return 0;
}
The program output is
The smallest positive element is 1.0
I'm trying to create a function that compares two four digit numbers and
returns the number of similar digits between the two. For example, with a generated number of 4311 and the user entered 1488,
the score should return 2 (4 and 1).
If it was 4311 and the other is 1147,
the score should return three (1, 1 and 4). I don't know why it isn't giving me the right outputs, hope you can help.
int getSameDigitScore(int playerGuess, int generatedNum) {
int score = 0;
int i;
int j;
int k;
int generatedNumArray[4];
int playerGuessArray[4];
// turns playerGuess into an array
while (playerGuess > 0 ) {
i = 0;
playerGuessArray[i] = playerGuess % 10;
i++;
playerGuess /= 10;
}
// turns generatedNum into an array
while (generatedNum > 0) {
i = 0;
generatedNumArray[i] = generatedNum % 10;
i++;
generatedNum /= 10;
}
// compares the two arrays
for (k = 3; k >= 0; k--) {
for (j = 3; j >= 0; j--) {
if (generatedNumArray[k] == playerGuessArray[j]) {
score++;
playerGuessArray[j] = 0;
j = -5;
}
}
}
return score;
}
You are assigning i = 0 inside the while loop while generating the playerGuessArray and generatedNumArray. Due to which the playerGuess and generatedNumArray array will have elements as first digit of your number 0 0 0 .
Move the initialization out of the loop.
int getSameDigitScore(int playerGuess, int generatedNum) {
int score = 0;
int i, j, k, n;
int generatedNumArray[4];
int playerGuessArray[4];
// turns playerGuess into an array
i = 0; // This has been out of while loop
while (playerGuess > 0 ) {
playerGuessArray[i] = playerGuess % 10;
i++;
playerGuess /= 10;
}
// turns generatedNum into an array
int n = 0; // This has been out of the while loop
while (generatedNum > 0) {
generatedNumArray[n] = generatedNum % 10;
n++;
generatedNum /= 10;
}
// compares the two arrays
for (k = 3; k >= 0; k--) {
for (j = 3; j >= 0; j--) {
if (generatedNumArray[k] == playerGuessArray[j]) {
score++;
playerGuessArray[j] = 0;
j = -5;
}
}
}
return score;
}
int main() {
int m;
n = getSameDigitScore(1231, 2342);
printf("Score is: %d\n", m);
}
You're re-initializing increment variable i on every iteration which should be moved out of the while loop. With that moved out the above code works fine.
There are the following issues with the code.
You are initializing the integer i inside the while loop. This needs to be done before the loop for each loop.
You need a separate array to get the output of equal digits. See AnswerArray in code below. Also it is a good design practice to pass this array to the function and clear this array inside the function.
In the last for loop, you should break from the inner loop after getting a match. This is to take care of cases where playerGuess == 1222 and generatedNum = 1111 In the code shown this will result in a score of 1.
See the final code below with some test cases.
int getSameDigitScore(int playerGuess, int generatedNum, int *AnswerArray) {
int score = 0;
int i;
int j;
int k;
int generatedNumArray[4] = {0};
int playerGuessArray[4] = {0};
memset(AnswerArray,0,4*sizeof(int));
// turns playerGuess into an array
i = 0;
while (playerGuess > 0 ) {
playerGuessArray[i] = playerGuess % 10;
i++;
playerGuess /= 10;
}
// turns generatedNum into an array
i = 0;
while (generatedNum > 0) {
generatedNumArray[i] = generatedNum % 10;
i++;
generatedNum /= 10;
}
// compares the two arrays
score=0;
for (k = 3; k >= 0; k--) {
for (j = 3; j >= 0; j--) {
if (generatedNumArray[k] == playerGuessArray[j]) {
AnswerArray[score++] = generatedNumArray[k];
playerGuessArray[j] = -1;
break;
}
}
}
return score;
}
int main(void)
{
int AnswerArray[4],score;
score = getSameDigitScore(4311,1488,AnswerArray);
printf ("\nScore = %d \n Answer Array = ",score);
for (int i=0; i<score; i++)
{
printf ("%d ",AnswerArray[i]);
}
score = getSameDigitScore(4311,1147,AnswerArray);
printf ("\nScore = %d \n Answer Array = ",score);
for (int i=0; i<score; i++)
{
printf ("%d ",AnswerArray[i]);
}
score = getSameDigitScore(1222,1111,AnswerArray);
printf ("\nScore = %d \n Answer Array = ",score);
for (int i=0; i<score; i++)
{
printf ("%d ",AnswerArray[i]);
}
score = getSameDigitScore(1111,1222,AnswerArray);
printf ("\nScore = %d \n Answer Array = ",score);
for (int i=0; i<score; i++)
{
printf ("%d ",AnswerArray[i]);
}
}
The initializing i=0 which you made inside the loop should be outside the loop.
while (playerGuess > 0 ) {
i = 0;
playerGuessArray[i] = playerGuess % 10;
i++;
playerGuess /= 10;
}
If the initialization is inside the looop then,
Everytime playerGuessArray[0] value will be updated.
FYI:
If playerGuess can contain 0 aat the begin of four digit like 0123
For example, playerGuessValue is 0123, Then by using
while (playerGuess > 0 ) {
i = 0;
playerGuessArray[i] = playerGuess % 10;
i++;
playerGuess /= 10;
}
playerGuessArray will contain only [1,2,3] instead of [0,1,2,3].
So, the better solution would be taking two temporary variables and checking last digit one by one.
Like this:
int temp1=playerGuess, temp2=GeneratedNum;
int i=0;
bool flag = true;
while(flag && i < 4){
if(temp1%10 != temp2%10){
flag = false;
}
temp1 /= 10;
temp2 /= 10;
i++;
}
if(flag){
score++;
}
FYI:
Debugging will help you in finding out these little mistakes.So, try to debug your code with multiple inputs and verify your answer.
Here are few reference on how to debug:
https://blog.hartleybrody.com/debugging-code-beginner/
https://www.codementor.io/mattgoldspink/how-to-debug-code-efficiently-and-effectively-du107u9jh%60
Thanks.
#include <stdio.h>
void main()
{
int maj, count, n = 6;
int arr[] = {1, 2, 2, 2, 2, 3, 4};
for (int i = 0; i < n; i++) {
maj = arr[i];
count = 0;
for (int j = 9; j < n; j++) {
if (arr[j] == maj) count++;
}
if (count > n / 2) {
break; /* I think some problem is here ,if majority element not found then it takes last element as the majority element */
}
}
printf("%d", maj);
}
It is giving correct output if majority ellement is there but incorrect output if no majority element is there for example if array is {1,2,3,4} it is giving output as 4. please help!!
#include <stdio.h>
int main() {
int maj, count, n = 7; //n is size of arr
int arr[] = {1, 2, 2, 2, 2, 3, 4};
int isFound = 0; //0 -> false, 1 -> true
for (int i = 0; i < n; i++) {
maj = arr[i];
count = 1; //first elements is itself
isFound = 0; //by default we assume that no major elements is found
for (int j = i+1; j < n; j++) { //iterate from next elements onwards to right in array
if (arr[j] == maj) count++;
}
if (count > n / 2) {
isFound = 1;
break; //major elements found; no need to iterator further; just break the loop now
}
}
if(isFound) printf("%d ", maj);
else printf("no major element");
return 0;
}
For starters according to the C Standard function main without parameters shall be declared like
int main( void )
Try not to use magic numbers. Usually as in your program they are a reason for program bugs. For example you declared the array arr as having 7 elements however the variable n that should keep the number of elements in the array is initialized with the value 6. Another magic number 9 is used in the loop
for (int j = 9; j < n; j++) {
^^^
There is no need to write the outer loop that travers the whole array. Also the program does not report the case when the majority number does not exist in the array.
Using your approach with two loops the program can look the following way
#include <stdio.h>
int main( void )
{
int a[] = { 1, 2, 2, 2, 2, 3, 4 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t i = 0;
for ( ; i < ( N + 1 ) / 2; i++ )
{
size_t count = 1;
for ( size_t j = i + 1; count < N / 2 + 1 && j < N; j++ )
{
if ( a[i] == a[j] ) ++count;
}
if ( !( count < N / 2 + 1) ) break;
}
if ( i != ( N + 1 ) / 2 )
{
printf( "The majority is %d\n", a[i] );
}
else
{
puts( "There is no majority element" );
}
return 0;
}
Its output is
The majority is 2
I want to write an algorithm that finds the n-th most frequent number in an array.
I have a solution but not optimal (testing numbers i've already tested)
I wonder if there is a more optimal solution?
Here is my Solution :
most_freq_element(a,n){
final_cnt = 0, curr_cnt = 1, final_freq_num = -1, curr_freq_num = -1;
for(i = 0; i < n-1; i++)
{
if (a[i]!=-1){
curr_freq_num = a[i];
for(j =i+1; j < n; j++){
if(curr_freq_num == a[j] && final_freq_num != curr_freq_num){
curr_cnt++;
}
}
if(final_cnt < curr_cnt){
final_cnt = curr_cnt;
curr_cnt = 1;
final_freq_num = curr_freq_num;
}
}
}
printf("Num = %d and times = %d", final_freq_num, final_cnt);
}
nth_most_frequent_element(a,n,k){
if(k==1){
return most_freq_element(a,n);
}
else{
for (i=0;i<k;i++){
int most_freq_num = most_freq_element(a,n);
for(i = 0; i < n-1; i++){
if (a[i]==most_freq_num){
a[i]=-1;
}
}
}
return most_freq_element(a,n);
}
}
I would probably make a hashmap/table, and increment each value on collision, so that the number is the key and the value is the number of collisions. Then, when you're done, aggregate it to a sorted list and grab the nth element. Would run in O(n) which is pretty optimal.
Edit: Actually, the sorting would cost n*log(n).
How about this ? Worst complexity is O(2.N.logN + k.min(k,d)), d: number of unique values in a
most_freq_element(a[0..n-1],n,k)
{
count[0..k], value[0..k]; // k + 1 elements
i, j, l;
qsort(a, n)
j = 0;
l = 0;
value[0] = a[0];
count[0] = 1;
for (i = 1; i < n; ++i)
{
if (a[i] != value[j])
{
if (++l > k) l = k;
j = l;
value[j] = a[i];
count[j] = 0;
}
++count[j];
while (j > 0 && count[j] > count[j - 1])
{
swap(count[j], count[j - 1]);
swap(value[j], value[j - 1]);
--j;
}
}
printf("Num = %d and times = %d", value[k - 1], count[k - 1]);
}