How to print out all combinations? - c

#include <stdio.h>
int main()
{
int day[30],
month[11],
year[2] = { 2000, 2001 };
int combinations[743];
printf("Days:\n");
for (int i = 1; i <= 31; i++)
{
day[i - 1] = i;
printf("%d ", day[i-1]);
}
printf("\n\nMonth:\n");
for (int j = 1; j <= 12; j++)
{
month[j - 1] = j;
printf("%d ", day[j - 1]);
}
printf("\n\nYear:\n%d %d\n\n", year[0], year[1]);
for (int x = 0, y = 0, z = 0, k = 0;
x <= 30, y <= 11, z <= 1, k <= 743;
x++, y++, z++, k++)
{
if (x == 31)
{
x = 0;
}
if (y == 11)
{
y = 0;
}
combinations[k] = day[x],".",month[y],".",year[0];
}
for (int a = 0; a <= 20; a++)
{
printf("Combination: %d \n", combinations[a]);
}
getch();}
I want to make a program that prints out all combinations for birthdays for 2000,2001 people, but I get something weird in the output
It looks like this:
Days:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Month:
1 2 3 4 5 6 7 8 9 10 11 12
Year:
2000 2001
Combination: 1
Combination: 2
Combination: 3
Combination: 4
Combination: 5
Combination: 6
Combination: 7
Combination: 8
Combination: 9
Combination: 10
Combination: 11
Combination: 12
Combination: 13
Combination: 14
Combination: 15
Combination: 16
Combination: 17
Combination: 18
Combination: 19
Combination: 20
Combination: 21

First of all, quick mistakes there:
In the second for-cycle you are printing the day array, the only reason the outut there is correct is because the numbers are the same and the cycle stop at 12. Anyways, you should fix that, for the sake of good programing.
The last cyle shouldnt be done like that, you are literally asking for bugs. Divide that cycle to 3 different ones. The outside cycle is the year, it will be executed twice (2000, 2001), the inner cycle will iterate 12 times( that will be the month) and the last one will iterate 31 times (that will be the days)
Doing it like this, makes it much easier to read and to do it right, since in your code that cycle will only be executed twice, since Z stops at 2 and you increase it every iteration.
for(year = 0; year < 2 ; year ++)
for(month = 0; month < 12; month ++)
for(day = 0; day < 31; day++)
//combination code goes here
Last things, if you want to save the date you cant make it like an int, unless you sum the days and use it as a reference, if you want something like "11-05-2000" you either creat a struct for that or save it as string. Second you are assuming 31 for every month...
Any further question, as you may have, feel free to ask :)

#include <stdio.h>
int main()
{
//changed days to 31 and months to 12
int day[31],
month[12],
year[2] = { 2000, 2001 };
//made three arrays one for days,one for months,one for year storage, or you can use structure array, structure should have three fields
int combinations1[744];
int combinations2[744];
int combinations3[744];
printf("Days:\n");
for (int i = 1; i <= 31; i++)
{
day[i - 1] = i;
printf("%d ", day[i-1]);
}
printf("\n\nMonth:\n");
for (int j = 1; j <= 12; j++)
{
month[j - 1] = j;
printf("%d ", day[j - 1]);
}
printf("\n\nYear:\n%d %d\n\n", year[0], year[1]);
int x,y,z,k=0;
//this will be code for storing all combination of days, looping through all days of a month of a year, then to next month and finally to next year
for(x = 0; x < 2 ; x ++)
{
for(y = 0; y < 12; y ++)
{
for(z = 0; z < 31; z++)
{
combinations1[k]=z+1;
combinations2[k]=y+1;
combinations3[k]=year[x];
k++;
}
}
}
// printing all combinations
for (int a = 0; a < 744; a++)
{
printf("Combination: %d.%d.%d\n", combinations1[a],combinations2[a],combinations3[a]);
}
//getch();
}
I have explained the code in comments. Please read the comments to understand

Related

2022 calendar in C determine starting day

I need to write a program in C that it prints a month chosen by the user from the year 2022.
If the user enter January (has 31 days) and the user enter to print 20 days, then should be printed from 1st January untill 20 January.
Same for every month.
I have this pice of code but I'm not happy with it and I googled everything.
void print_month(char *mo, int number_day_userInput){
int i,j; // as counters
int week = 7; // as 7 days in a week
int day=1;
int day_of_the_week=1;
printf("M\tT\tW\tT\tF\tS\tS");
//January
if(strcmp(mo, "January")== 0){
for(i=0;i<=5;i++){ // this 5 is as 5 weeks in January
printf("\n");
for(j=1;j<=week;j++){
if(day_of_the_week>=6){ // 1st day start printing
printf("%i",day);
day++;
if(day > number_day_userInput){
break;
}
}
day_of_the_week++;
printf("\t");
}
}
printf("\n\nJanuary has 31 days");
}
I can't figure it out, how to determine for each month where to start printing the first day. For example, January 1st starts on a Saturday, the 6th day. February starts on 2nd day. Also, I don't know how to determine how many weeks are in a month. Could you please share some ideas ? Not necessarily in C, but an advice will be welcomed. Thank you
Here I started with Sunday as day 0 (Gregorian calendar). It should print out correctly based on the month given. Core concept here is just using the modulus operator % to find remainders, and basic for-loop stuff :)
#include <stdio.h>
#include <string.h>
static int daysOfMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
static int start = 6;
void print_month(char *mo, int number_day_userInput)
{
int j = 0;
if(strcmp(mo, "February") == 0) { j = 1; }
else if(strcmp(mo, "March") == 0) { j = 2; }
else if(strcmp(mo, "April") == 0) { j = 3; } // and so on...
for(int i = 0; i < j; ++i)
{
start += daysOfMonth[i];
}
int startDay = start % 7;
printf("S\tM\tT\tW\tT\tF\tS\n");
for(int tab = 0; tab < startDay; ++tab)
{
printf("\t");
}
for(int day = 1; day <= number_day_userInput; ++day)
{
printf("%d\t", day);
if(++startDay % 7 == 0)
{
printf("\n");
}
}
printf("\n");
}
int main()
{
print_month("March", 20);
}
SAMPLE OUTPUT of print_month("January", 31):
S M T W T F S
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31

Why is my program not dividing even numbers by two?

It should scan 10 int numbers and then display them backwards, dividing the even ones by two, but it just displays them without dividing.
es:
10 9 8 7 6 5 4 3 2 1 ==> 1 2 3 2 5 3 7 4 9 5
but mine does:
10 9 8 7 6 5 4 3 2 1 ==> 1 2 3 4 5 6 7 8 9 10
#include <stdio.h>
int main(void)
{
int a[10];
for(int i = 0; i < 10; i++)
scanf("%d", &a[i]);
for (int i = 0; i < 10; i++) {
if (a[i] % 2 == 0 ) {
a[i] = a[i] / 2; i++;
}
else
i++;
}
for(int i = 9; i > -1; i--)
printf("%d\n", a[i]);
return 0;
}
The middle loop incorrectly increments i twice per iteration:
for (int i = 0; i < 10; i++) { // <<== One increment
if (a[i]%2 == 0 ) {
a[i] = a[i]/2; i++; // <<== Another increment - first branch
}
else
i++; // <<== Another increment - second branch
}
In your case, all even numbers happen to be stored at even positions that your loop skips.
Note: A better solution is to drop the middle loop altogether, and do the division at the time of printing.
The body of your second for loop advances i. Since it's also advanced in the loop's clause, it's advanced twice, effectively skipping any other element. Remove those advancements, and you should be OK:
for(int i=0; i<10; i++) {
if (a[i] % 2 == 0) {
a[i] /= 2;
}
}
In your program you incrementing the for loop variable i two times inside the loop and loop also increment the value one time so the values are skipped that is the reason you are getting wrong output.herewith i have attached the corrected program and its output.hope you understand the concept .Thank you
#include <stdio.h>
int main(void)
{
int a[10];
printf("\n Given Values are");
printf("\n-----------------");
for(int i = 0; i < 10; i++)
scanf("%d", &a[i]);
for (int i = 0; i < 10; i++)
{
if (a[i] % 2 == 0 )
{
a[i] = a[i] / 2;
}
}
printf("\n After dividing the even numbers by 2 and print in reverse order");
printf("\n ----------------------------------------------------------------\n");
for(int i = 9; i > 0; i--)
printf("%d\n", a[i]);
return 0;
}
Output
Given Values are
-----------------
1
2
3
4
5
6
7
8
9
10
After dividing the even numbers by 2 and print in reverse order
----------------------------------------------------------------
5
9
4
7
3
5
2
3
1

strings to array and locating a character in a string

i am working on a program where the input is an ID of 9 numbers :
program checks if the id is correct or not by :-
checking if the string is formed by numbers only .
every number has a weight of 1 or 2 so it should be 1 2 1 2 1 2 1 2
1
multiply the weight and the number
if the number is bigger than 9 then add the numbers forming it .
if the number is from multiplication of 10 then the ID is correct ..
example :-
1 7 9 3 7 9 2 5 0-ID
1 2 1 2 1 2 1 2 1-Weight
1 14 9 6 7 18 2 10 0-num x weight
1 5 9 6 7 9 2 1 0-(4)
sum = 40 then it is a correct ID.
I wrote most of it but then i noticed that it has to be a string . so my questions are :
is there a way to put a string into an array?as doing it with an
array is way easier.
how do i locate a place in a string ? like if i want the third
character in a string how do i locate it?.
and here is the code that i did it does not work yet and it needs alot of changes but i guess i will put it anyways :-
#include<stdio.h>
#define N 9
void input(int num[N]);
int check(int num[N]);
int main()
{
int num[N],a;
input(num);
a = check(num);
if (a = 1)
printf("ID is correct");
else printf("ID is NOT correct");
}
void input(int num[N])
{
int i;
printf("Enter your ID (9digits) :-");
for (i = 0;i < N;i++)
scanf("%d",num[i]);
}
int check(int num[N])
{
int w[N] = { 1,2,1,2,1,2,1,2,1 },wxnum[N],i,tota[N],sum,g;
for (i = 0;i < N;i++)
wxnum[i] = num[i] * w[i];
for (i = 0;i < N;i++)
{
if (wxnum[i] > 9)
tota[i] = wxnum[i] / 10 + wxnum[i] % 10;
else tota[i] = wxnum[i];
}
sum = tota[0] + tota[1] + tota[2] + tota[3] + tota[4] + tota[5] + tota[6] + tota[7] + tota[8];
g = sum % 10;
if (g = 0)
return 1;
else
return 0;
}
Thanks everyone for your help.
You can get a string by doing
/*N is defined as 9 in your code.*/
/*Considering there is always a '\0' in every string, we should allocat N + 1 slot for your nine numbers and the extra '\0'.*/
char chStr[N + 1];
scanf("%s", chStr);
After you got the string, you can take advantage of the values of charactor '0' - '9' (their values are from 48 to 57 correspondingly) in ASCII table, and easily transfer the charactors into integers by doing:
int i = 0;
for (i = 0; i < N; i++)
{
chStr[i] = chStr[i] - '0';
}
If you are restrict on the type, you can transfer these char values into int values by adding extra two lines:
int num[N];
int i = 0;
for (i = 0; i < N; i++)
{
chStr[i] = chStr[i] - '0';
num[i] = (int) chStr[i];
}
Please note that my code didn't check the validation of user input. To make it more secure, you can use
scanf("%9s", chStr);
to declare the maximum length that the user can input.

How to find all subsets whose sum adds up to the value of a target value using dynamic programming in C

So I have been trying to do a variant of the subset sum problem, which I want to do using dynamic programming. So what I am aiming for is for example, to have an input of
m = 25 // Target value
n = 7 // Size of input set
and the input set to be for example {1, 3, 4, 6, 7, 10, 25}. So the wanted output would be something like
{1, 3, 4, 7, 10} and {25}.
Here is the code
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Get input sequence
int n = 7; // Size of input set
int m = 25; // Target value
int *S; // Input set
int **C; // Cost table
int i,j,potentialSum,leftover;
S=(int*) malloc((n+1)*sizeof(int));
C=malloc((m+1)*sizeof(int*));
for (int rows = 0; rows<=m; rows++) {
C[rows] = malloc((m+1)*sizeof(int));
}
if (!S || !C)
{
printf(" FAILED %d\n",__LINE__);
exit(0);
}
S[0] = 0;
S[1] = 1;
S[2] = 3;
S[3] = 4;
S[4] = 6;
S[5] = 7;
S[6] = 10;
S[7] = 25;
// Initialize table for DP
C[0][0]=0; // DP base case
// For each potential sum, determine the smallest index such
// that its input value is in a subset to achieve that sum.
for (potentialSum=1; potentialSum<=m; potentialSum ++)
{
for (j=1;j<=n;j++)
{
leftover=potentialSum-S[j]; // To be achieved with other values
if (leftover<0) // Too much thrown away
continue;
if (C[leftover][0] == (-1)) // No way to achieve leftover
continue;
if (C[leftover][0]<j) // Indices are included in
break; // ascending order.
}
C[potentialSum][0]=(j<=n) ? j : (-1);
}
// Output the input set
printf(" i S\n");
printf("-------\n");
for (i=0;i<=n;i++)
printf("%3d %3d\n",i,S[i]);
// Output the DP table
printf("\n\n i C\n");
printf("-------\n");
for (i=0;i<=m;i++)
printf("%3d %3d\n",i,C[i][0]);
if (C[m][m]==(-1))
printf("No solution\n");
else
{
printf("\n\nSolution\n\n");
printf("(Position) i S\n");
printf("------------------\n");
for (i=m;i>0;i-=S[C[i][0]])
printf(" %3d %3d\n",C[i][0],S[C[i][0]]);
}
}
This will output the following
i S
-------
0 0
1 1
2 3
3 4
4 6
5 7
6 10
7 25
i C
-------
0 0
1 1
2 -1
3 2
4 2
5 3
6 4
7 3
8 3
9 4
10 4
11 4
12 5
13 4
14 4
15 5
16 5
17 5
18 5
19 6
20 5
21 5
22 6
23 6
24 6
25 6
Solution
(Position) i S
------------------
6 10
5 7
3 4
2 3
1 1
Program ended with exit code: 0
My problem is that I can only output one solution, and that is the solution that needs the smaller values and goes up to 25, so when 25 is used it isn't in the solution. The C array in the code is a 2-D array, since I thought I could maybe do another backtrace while computing the first one? I couldn't figure out how to do so, so I left C[i][0] fixed to the first column, just to demonstrate a single solution. Any tips in the right direction would be greatly appreciated. I found a solution using Python, but the problem is solved recursively, which I don't think helps me, but that code is here.
Thanks for all the help in advance.
I did not fully understand your code. But here is a C code which finds all the subsets that sum to target.
#include <stdio.h>
int a[] = { 0, 1, 3, 4, 6, 7, 10, 25 }; //-- notice that the input array is zero indexed
int n = 7;
int target = 25;
int dp[8][26];
int solutions[1 << 7][8]; //-- notice that the number of subsets could be exponential in the length of the input array a.
int sz[1 << 7]; //-- sz[i] is the length of subset solutions[i]
int cnt = 0; //-- number of subsets
void copy(int srcIdx, int dstIdx){
int i;
for (i = 0; i < sz[srcIdx]; i++)
solutions[dstIdx][i] = solutions[srcIdx][i];
sz[dstIdx] = sz[srcIdx];
}
//-- i, and j are indices of dp array
//-- idx is the index of the current subset in the solution array
void buildSolutions(int i, int j, int idx){
if (i == 0 || j == 0) return; // no more elements to add to the current subset
if (dp[i - 1][j] && dp[i - 1][j - a[i]]){ // we have two branches
cnt++; // increase the number of total subsets
copy(idx, cnt); // copy the current subset to the new subset. The new subset does not include a[i]
buildSolutions(i - 1, j, cnt); //find the remaining elements of the new subset
solutions[idx][sz[idx]] = a[i]; // include a[i] in the current subset
sz[idx]++; // increase the size of the current subset
buildSolutions(i - 1, j - a[i], idx); // calculate the remaining of the current subset
}
else if (dp[i - 1][j - a[i]]){ // we only have one branch
solutions[idx][sz[idx]] = a[i]; // add a[i] to the current subset
sz[idx]++;
buildSolutions(i - 1, j - a[i], idx); // calculate the remaining of the current subset
}
else buildSolutions(i - 1, j, idx); // a[i] is not part of the current subset
}
int main(){
int i, j;
// initialize dp array to 0
for (i = 0; i <= n; i++)
for (j = 0; j <= target; j++) dp[i][j] = 0;
//-- filling the dp array
for (i = 0; i <= n; i++)
dp[i][0] = 1;
for (i = 1; i <= n; i++){
for (j = 1; j <= target; j++){
if (j < a[i])
dp[i][j] = dp[i - 1][j];
else
dp[i][j] = dp[i - 1][j] || dp[i - 1][j - a[i]];
}
}
//-- building all the solutions
for (i = 0; i < sizeof(sz); i++) sz[i] = 0; //-- initializing the sz array to 0
buildSolutions(n, target, 0);
//-- printing all the subsets
for (i = 0; i <= cnt; i++){
for (j = 0; j < sz[i]; j++){
printf("%d ", solutions[i][j]);
}
printf("\n");
}
}
If you have any questions about the code, do not hesitate to ask.

Creating a 2D array board

I am trying to create a 2d matrix board which side is determined by the user input. I created the two D array but it is not printing the right numbers. For example if the user enters 3, it is suppose to create a 3 * 3 board with the number 8, 7, 6, 5, 4, 3, 2, 1, 0.
However it keeps printing the same numbers in each row eg 876, 876, 876
I know it is doing what I have written but I cant figure out how to correct it...I am thinking that I need a counter that resets to zero and perhaps the [i][j] = counter's value.
Anyway here is the code that is giving the trouble.
for (i =0; i< row; i++)
{
for (j =0; j < col; j++)
{
game [i][j] = ((row * row)-1) - j;
printf( "%i", game[i][j] );
}
How can I populate the board so it prints from (row * col) - 1 to zero. Thanks a million.
for ((i=0, k=0); i< row; i++)
{
for (j =0; j < col; j++)
{
game [i][j] = ((row * col)-1) - (k++);
printf( "%i", game[i][j] );
}
}
The basic mistake in the code is that, in each iteration, the value getting subtracted from the game[i][j] gets re-initialized to 0. Since, the value of (row * col) is constant for a given value of both, subtracting (0, 1, 2) each time from the sum results in the reproduction of the same numbers.
As given in the example, row=3, col=3, so 3*3 = 9 (Indexed from 0 to 8).
So, we do :
8 - 0 = 8
8 - 1 = 7
8 - 2 = 6
again j gets re-init to 0, so again we have,
8 - 0 = 8
8 - 1 = 7
8 - 2 = 6
.
The solution is, the value getting subtracted should get uniformly reduced, such that it doesn't get re-init inside the loop.
Result :
8 - 0 = 8
8 - 1 = 7
8 - 2 = 6
8 - 3 = 5
.
.
.
.
8 - 8 = 0.
Hope this clears the problem.
As suggested by "self", using a third variable is the easiest way (and actually the most efficient : only one decrement per iteration)
int count = row * col - 1;
for (size_t i =0; i< row; i++)
{
for (size_t j =0; j < col; j++)
{
game [i][j] = count--;
printf( "%i", game[i][j] );
}
}
Output:
24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

Resources