How to compare a given string with a result - c

I'm very new to this and to C programming. It's my first year and things are not very clear for me. Hopefully I can get better very soon.
I have a code here where i input a number and I get results based on the table I have below.
I would like to know: If i have a given string (in the code it's: test[7]="2 B 1 C")
How can I compare the result i have to this string and see if it's the same to print=good?
it's very hard to explain so please let me know if i'm not clear with my question. You can test the code to see how it works.
#include <stdio.h>
#include <string.h>
void initialize(int poss[1296][4]);
int main()
{
int table[1296][4];
char str[5];
char tmp[5];
int i, j, k;
int bull = 0;
int cow = 0;
char test[7]={"2 B 0 C"};
initialize(table);
printf("Enter 4 digits: ");
scanf("%s", str);
for (i=0; i<1296; i++) // building this table
{
strcpy(tmp, str); // copying string
for (j=0; j<4; j++)
{
for (k=0; k<4; k++)
{
if (table[i][j]==tmp[k]-'0' && j==k) // gets the string as an integer
{
tmp[k] = -1;
bull++;
break;
}
else if (table[i][j]==tmp[k]-'0' && j!=k)
{
tmp[k] = -1;
cow++;
break;
}
}
}
printf ("%d B %d C\n\n", bull, cow);
bull = 0;
cow = 0;
}
}
//------------------------------------TABLE---------------------------------//
void initialize(int poss[1296][4])
{
int i=0;
int j, k=0;
int m;
while (i<=5)
{
for (j=0; j<216 ; j++)
{
poss[k][0]=i;
k++;
}
i++;
}
k=0;
i=0;
j=0;
while (k<1296)
{
for (m=0; m<6; m++)
{
for (j=0; j<6; j++)
{
for (i=0; i<36 ; i++)
{
poss[k][1]=j;
k++;
}
}
}
}
k=0;
i=0;
j=0;
m=0;
while (k<1296)
{
for (j=0; j<6; j++)
{
for (i=0; i<6; i++)
{
poss[k][2]=j;
k++;
}
}
}
k=0;
i=0;
j=0;
m=0;
while (k<1296)
{
for (i=0; i<6; i++)
{
poss[k][3]=i;
k++;
}
}
}

You can use sprintf to generate the result into a string instead of printing it, then use strcmp to compare that string to what you expect it to be. You can also then use printf to print the string you produced with sprintf. (When you sprintf, don't include the newlines since those aren't in your test string; only output those with printf).
What's not clear from your question, however, is that you only have one test string but print 1296 lines ... if those lines aren't all the same then you need an array of 1296 test results ... or a clearer question.

sample
#include <stdio.h>
#include <string.h>
int main(){
char test[8]={"2 B 0 C"};
char result[8];
int bull = 0;
int cow = 0;
bull = 2;//set by program
cow = 0;
sprintf(result, "%d B %d C", bull, cow);
if(strcmp(result, test)==0){
printf("match!\n");
} else {
printf("not match!\n");
}
return 0;
}

Related

Enter text and sort alphabetically

#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char str1[100];
char str2[100];
char str3[100];
int count, tmp;
int i, j=0, k=0;
scanf("%s", str1);
count=strlen(str1);
for(i=0; i<count; i++) {
if(islower(str1[i])) {
str2[j]=str1[i];
j++;
}
else if(isupper(str1[i])) {
str3[k]=str1[i];
k++;
}
}
str2[j]='\0';
str3[k]='\0';
for(i=0; i<strlen(str2); i++) {
for(j=0; j<i; j++) {
if(str2[j]>str2[j+1]) {
tmp=str2[j];
str2[j]=str2[j+1];
str2[j+1]=tmp;
}
}
}
for(i=0; i<strlen(str3); i++) {
for(j=0; j<i; j++) {
if(str3[j]>str3[j+1]) {
tmp=str3[j];
str3[j]=str3[j+1];
str3[j+1]=tmp;
}
}
}
printf("lowercase alignment : %s\n", str2);
printf("uppercase alignment : %s", str3);
return 0;
}
I want to get a string input, divide it into uppercase and lowercase letters, and print it out in alphabetical order. However, errors continue to occur during the sorting process. Why did you do that?
I believe the problem is here:
for (i = 0; i < strlen(str2); i++) {
for (j = 0; j < i; j++) {
For this type of sort, I believe this should be:
for (i = 0; i < strlen(str2); i++) {
for (j = 0; j < strlen(str2) - 1; j++) {
That is, the outer loop needs to be done strlen(str2) times, but its i iteration variable should have no effect on the inner loop which needs to walk (nearly) the entire string on each iteration. Thus the inefficiency of this sort method. Ditto the same looping construct that sorts str3.
My rework of your code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char mixedcase[100];
char lowercase[100];
char uppercase[100];
scanf("%s", mixedcase);
size_t length = strlen(mixedcase);
int l = 0, u = 0;
for (int i = 0; i < length; i++) {
char c = mixedcase[i];
if (isalpha(c)) {
if (islower(c)) {
lowercase[l++] = mixedcase[i];
} else {
uppercase[u++] = mixedcase[i];
}
}
}
lowercase[l] = '\0';
uppercase[u] = '\0';
length = strlen(lowercase);
for (int i = 0; i < length; i++) {
for (int j = 0; j < length - 1; j++) {
if (lowercase[j] > lowercase[j+1]) {
char tmp = lowercase[j];
lowercase[j] = lowercase[j+1];
lowercase[j+1] = tmp;
}
}
}
length = strlen(uppercase);
for (int i = 0; i < length; i++) {
for (int j = 0; j < length - 1; j++) {
if (uppercase[j] > uppercase[j+1]) {
char tmp = uppercase[j];
uppercase[j] = uppercase[j+1];
uppercase[j+1] = tmp;
}
}
}
printf("Lowercase alignment: %s\n", lowercase);
printf("Uppercase alignment: %s\n", uppercase);
return 0;
}
The next thing to do would be to move your sort logic into its own function and call that function on each of the strings to be sorted rather than repeat the code twice in the body of main().

Getting heap overflow even on deallocating memory

I am trying to solve the n-queen problem on leetcode. But it is giving heap overflow error on leetcode.
But on my computer when I give single input it give correct answer but on giving input multiple times it gives segmentation fault: 11 error.
And when I don't print the complete chess board. Just printing the number of different possible solution. Then also it works fine.
#include <stdio.h>
#include <stdlib.h>
#define bool int
#define true 1
#define false 0
//checking positioned queens
bool checkPlacedQueens(char **board, int queeni, int queenj, int n) {
int i=queeni;
int j=queenj;
//checking complete row
for(int i=queeni; i>=0; i--) {
if(board[i][j] == 'Q')
return false;
}
i=queeni;
j=queenj-1;
//checking left diagonal
while(i>=0 && j>=0) {
if(board[i--][j--] == 'Q')
return false;
}
i=queeni;
j=queenj+1;
//checking right diagonal
while(i>=0 && j<=n) {
if(board[i--][j++] == 'Q')
return false;
}
return true;
}
char ***placeQueens(char **board, int queenI, int n, int *returnSize, char ****result) {
//all queens are on their correct position
if(queenI == n) {
(*returnSize)++;
/*
reallocating the memory to save all the outputs in 3D
array
*/
(*result) = (char ***) realloc(*result, sizeof(char **)*(*returnSize));
(*result)[*returnSize-1] = (char **)malloc(sizeof(char *)*n);
for(int i=0; i<n; i++) {
(*result)[*returnSize-1][i] = (char *)malloc(sizeof(char)*n);
}
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
(*result)[*returnSize-1][i][j] = board[i][j];
}
}
return *result;
}//if
for(int j=0; j<n; ++j) {
char save = board[queenI][j];
board[queenI][j] = 'Q';
if(checkPlacedQueens(board, queenI-1, j, n)) {
placeQueens(board, queenI+1, n, returnSize, result);
}
board[queenI][j] = save;
}//for Loop
return *result;
}//function
char *** solveNQueens(int n, int* returnSize) {
char **board;
char ***result = (char ***)malloc(sizeof(char **));
board = (char **)malloc(sizeof(char *)*n);
for(int i=0; i<n; i++) {
board[i] = (char *)malloc(sizeof(char)*n);
}
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
board[i][j] = '.';
}
}
placeQueens(board, 0, n, returnSize, &result);
for(int i=0; i<n; i++)
free(board[i]);
free(board);
return result;
}//char
int main(void) {
int returnSize=0;
int n=4;
char ***arr;
while(n<10) {
arr = solveNQueens(n, &returnSize);
for(int i=0; i<returnSize; ++i) {
for(int j=0; j<n; j++) {
for(int k=0; k<n; k++) {
printf("%c", arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
printf("\n\n\n");
for(int i=0; i<returnSize; ++i) {
for(int j=0; j<n; j++) {
free(arr[i][j]);
}
free(arr[i]);
}
free(arr);
arr=NULL;
n++;
}
}//main
Yoor code has an out-of-bounds read illegal memory access. A live test of it is here segfault diagnoser,
The following is the diagnostic message of the out-of-bounds read.
====== Start of Stensal DTS message == (56.133) == copy start here ======
[out-of-bounds read] is detected by Stensal DTS.
Continuing execution can cause undefined behavior, abort!
+--------------------------------------------------------------------------+
| Reading 1 bytes from 0x80c5054 will read undefined values.
|
| The object to-be-read (start:0x80c5050, size:4 bytes) is allocated at
| file:/prog.c::83, 28
|
| 0x80c5050 0x80c5053
| +------------------------+
| | the object to-be-read |......
| +------------------------+
| ^~~~~~~~~~
| the read starts at 0x80c5054 that is right after the object end.
|
| Stack trace (most recent call first) of the read.
| [1] file:/prog.c::31, 12
| [2] file:/prog.c::67, 12
| [3] file:/prog.c::68, 13
| [4] file:/prog.c::92, 5
| [5] file:/prog.c::107, 15
| [6] [libc-start-main]
+--------------------------------------------------------------------------+
======= End of Stensal DTS message =============== copy end here =========
The problem is that your are not resetting the value of returnSize each time you re-call the solveNQueens function.
The following is a working code:
#include <stdio.h>
#include <stdlib.h>
#define bool int
#define true 1
#define false 0
//checking positioned queens
bool checkPlacedQueens(char **board, int queeni, int queenj, int n) {
int i=queeni;
int j=queenj;
//checking complete row
for(int i=queeni; i>=0; i--) {
if(board[i][j] == 'Q')
return false;
}
i=queeni;
j=queenj-1;
//checking left diagonal
while(i>=0 && j>=0) {
if(board[i--][j--] == 'Q')
return false;
}
i=queeni;
j=queenj+1;
//checking right diagonal
while(i>=0 && j<=n) {
if(board[i--][j++] == 'Q')
return false;
}
return true;
}
char ***placeQueens(char **board, int queenI, int n, int *returnSize, char ****result) {
//all queens are on their correct position
if(queenI == n) {
(*returnSize)++;
/*
reallocating the memory to save all the outputs in 3D
array
*/
(*result) = (char ***) realloc(*result, sizeof(char **)*(*returnSize));
(*result)[*returnSize-1] = (char **)malloc(sizeof(char *)*n);
for(int i=0; i<n; i++) {
(*result)[*returnSize-1][i] = (char *)malloc(sizeof(char)*n);
}
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
(*result)[*returnSize-1][i][j] = board[i][j];
}
}
return *result;
}//if
for(int j=0; j<n; ++j) {
char save = board[queenI][j];
board[queenI][j] = 'Q';
if(checkPlacedQueens(board, queenI-1, j, n)) {
placeQueens(board, queenI+1, n, returnSize, result);
}
board[queenI][j] = save;
}//for Loop
return *result;
}//function
char *** solveNQueens(int n, int* returnSize) {
char **board;
char ***result = (char ***)malloc(sizeof(char **));
board = (char **)malloc(sizeof(char *)*n);
for(int i=0; i<n; i++) {
board[i] = (char *)malloc(sizeof(char)*n);
}
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
board[i][j] = '.';
}
}
placeQueens(board, 0, n, returnSize, &result);
for(int i=0; i<n; i++)
free(board[i]);
free(board);
return result;
}//char
int main(void) {
int n=4;
char ***arr;
while(n<10) {
// Reset the value of returnSize
int returnSize=0;
arr = solveNQueens(n, &returnSize);
for(int i=0; i<returnSize; ++i) {
for(int j=0; j<n; j++) {
for(int k=0; k<n; k++) {
printf("%c", arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
printf("\n\n\n");
for(int i=0; i<returnSize; ++i) {
for(int j=0; j<n; j++) {
free(arr[i][j]);
}
free(arr[i]);
}
free(arr);
arr=NULL;
n++;
}
}//main

I want to print pattern of numbers using c program

If n=3,the output is
1*2*3
7*8*9
4*5*6
If n=5,the output is
1*2*3*4*5
11*12*13*14*15
21*22*23*24*25
16*17*18*19*20
6*7*8*9*10
CODE:
int i, j, a[50][50], k = 1, m = 0;
for (i = 0; i < n; i += 2) {
for (j = 0; j < n; j++) {
a[i][j] = k;
k++;
}
printf("\n");
}
m = k;
for (i = 1; i <= n; i += 2) {
for (j = 0; j < n; j++) {
a[i][j] = m;
m++;
}
printf("\n");
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%d", a[i][j]);
}
printf("\n");
}
I am not so good in c language, but i think it will help you.
please have a look, and you can do making some change if any syntax error occurs but logic is clear.
#include <stdio.h>
#include <math.h>
void printOutput(int n){
int k = ceil(n/2);
int m =1;
int j =1;
int l =k;
int i;
int b;
for(i=1;i<=n;i++){
for(b=m;b<=m+n;b++){
printf(b);
}
printf("\n");
if(i<k){
j= (2*j);
m =n*j+1;
} else{
int z = n-i-1;
m= n+1 +n*(2)*z;
l =z-2;
}
}
}
void main(){
int input;
printf("Enter a Value : ");
scanf(" %d",&input);
printOutput(input);
}
#include<stdio.h>
#include<conio.h>
int k=1;
int main(){
int n;
scanf("%d",&n);
for(int i=1;i<=n/2+1;i++){
for(int j=1;j<=n;j++){
if(j!=1&&j!=n+1){
printf("*");
}
printf("%d",k);
k++;
}
printf("\n \n");
k=k+n;
}
k=k-3*n;
for(int i=1;i<=n/2;i++){
for(int j=1;j<=n;j++){
if(j!=1&&j!=n+1){
printf("*");
}
printf("%d",k);
k++;
}
printf("\n \n");
k=k-(n/2+1)*n;
}
}
This is a rough sketch of what you should do, there are some minor flaws with it... However, the functionality is there. Next time, if you can't understand what algorithm the code calls for, I suggest you write this array out on a sheet of paper and follow each row. Notice where each row gets placed, you should start to come up with a way to do this (there are more ways than this one...) It may seem hard at first, but if you want to be in this field, you have to have the mindset for it. I agree with the others, this is NOT a homework site, rather a site to help build off the knowledge you know, so begin to actually try to write the program, and then submit it here if you're having trouble with it.
#include <stdio.h>
void loadNprint(int size, int a[][size]){
int i,j,count=1,down=size-1, up =0;
for(i=0; i<size; i++){
for(j=0;j<size; j++){
if((i%2) == 0)a[up][j] = count;
if((i%2) == 1)a[down][j]= count;
count++;
}
if((i%2) == 0)up++;//keeping track of the rows in ascending order
if((i%2) == 1)down--;//keeping track of rows in descending order
}
for(i=0; i<size; i++){
for(j=0; j<size; j++){
printf("%4d",a[i][j]);
}
printf("\n");
}
}
void main(){
int input;
printf("Enter a Value : ");
scanf(" %d",&input);
int myarray[input][input];
loadNprint(input,myarray);
}
This program works perfect. But if you want make some changes..do it yourself.
Next time please try some coding yourself before asking. This will print a different pattern for even numbers.
#include<stdio.h>
#include<conio.h>
int n,beginnew,cpy;
int main()
{
printf("Please enter a value : ");
scanf("%d",&n);
//process
beginnew=n-n/2+1;//beginning of new pattern
cpy=n-1;
for(int i=1;i<n+1;i++)
{
if(i<beginnew)
{
for(int h=n-1;h>=0;h--)
printf("%d * ", (n*(2*i-1)-h) );
}
else
{
for(int h=n-1;h>=0;h--)
printf("%d * ",(n*(cpy)-h) );
cpy=cpy-2;
}
printf("\n");
}
getch();
return 0;
}
//this code print Diagonal Pattern if matrix is
1 2 3
4 5 6
7 8 9
output is :
1
4 2
7 5 3
8 6
9
import java.util.*;
class DiagonalPattern
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int x[][];
int i,j,row,col,p,temp=1,last=0;
System.out.println("how many array wants to create and size of array");
row=sc.nextInt();
col=sc.nextInt();
x=new int[row][col];
System.out.println("Enter " +row*col+ " elements of array of array");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
x[i][j]=sc.nextInt();
last=j;
}
}
for(i=0;i<row;i++)
{
System.out.println("");
int k=i;
for(j=0;j<=i;j++,k--)
{
if(j==col)
{
break;
}
else
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
for(p=x.length;p>0;p--,temp++)
{
System.out.println("");
i=x.length-1;
int k=i;
for(j=temp;j<=last;j++,k--)
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
}

Compare table with a given string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I would like to compare a table i have and compare it with a given string number.
I have the table code ready and i guess it's not a problem to scan a string of 4 digits.
The table is initialize[1296][4] and I want it to compare to a given string[4].
I'm new to programming and i'm having a bit of difficulty. I'm actually building a Bulls and Cows game and I need to compare each digit of my table row to the given string of each column.
I hope i was clear with my question because it could get confusing or i'm just not explaining it right. I tried doing it but i can't seem to make it work.
Here's my table. If someone could help i would really appreciate it. Thanks.
void initialize(int poss[1296][4])
{
int i=0;
int j, k=0;
int m;
while (i<=5)
{
for (j=0; j<216 ; j++)
{
poss[k][0]=i;
k++;
}
i++;
}
k=0;
i=0;
j=0;
while (k<1296)
{
for (m=0; m<6; m++)
{
for (j=0; j<6; j++)
{
for (i=0; i<36 ; i++)
{
poss[k][1]=j;
k++;
}
}
}
}
k=0;
i=0;
j=0;
m=0;
while (k<1296)
{
for (j=0; j<6; j++)
{
for (i=0; i<6; i++)
{
poss[k][2]=j;
k++;
}
}
}
k=0;
i=0;
j=0;
m=0;
while (k<1296)
{
for (i=0; i<6; i++)
{
poss[k][3]=i;
k++;
}
}
}
Make sure to reduce the number of rows they can't be shown all at once on console.
Another think you have to read the definition of the bulls and cows (http://en.wikipedia.org/wiki/Bulls_and_cows). Your implimentation is not right.
Link to your code http://ideone.com/uTZf7R.
EDIT:
#include <stdio.h>
#include <string.h>
void initialize(int poss[1296][4]);
int main()
{
int table[1296][4];
char str[5];
char tmp[5];
int i, j, k;
int bull = 0;
int cow = 0;
initialize(table);
printf("Enter 4 digits: ");
gets(str);
for (i=0; i<100; i++){
strcpy(tmp, str);
for (j=0; j<4; j++){
for (k=0; k<4; k++){
if (table[i][j]==tmp[k]-'0' && j==k){
tmp[k] = -1;
bull++;
break;
}
else if (table[i][j]==tmp[k]-'0' && j!=k){
tmp[k] = -1;
cow++;
break;
}
}
}
printf ("Number: %d%d%d%d, Input: %s\n",table[i][0], table[i][1], table[i][2], table[i][3], str);
printf ("%d bulls and %d cows\n\n", bull, cow);
bull = 0;
cow = 0;
}
}
void initialize(int poss[1296][4])
{
int i=0;
int j, k=0;
int m;
while (i<=5)
{
for (j=0; j<216 ; j++)
{
poss[k][0]=i;
k++;
}
i++;
}
k=0;
i=0;
j=0;
while (k<1296)
{
for (m=0; m<6; m++)
{
for (j=0; j<6; j++)
{
for (i=0; i<36 ; i++)
{
poss[k][1]=j;
k++;
}
}
}
}
k=0;
i=0;
j=0;
m=0;
while (k<1296)
{
for (j=0; j<6; j++)
{
for (i=0; i<6; i++)
{
poss[k][2]=j;
k++;
}
}
}
k=0;
i=0;
j=0;
m=0;
while (k<1296)
{
for (i=0; i<6; i++)
{
poss[k][3]=i;
k++;
}
}
}
Change the variable names the way they serve you.
Note that string[j] - '0' is to get string[j] as an integer.

How to print a 2d array with a function in C?

I'm trying to print a 2d array with a function, but I keep getting the error "pointer expected"
I'm trying to make a battleship-type grid. I'm fine with printing out the co-ordinate row and column, but I can't actually get the 2d array (which contains "." in every element) to print at all.
Any help would be appreciated, I'm very new to this. Thanks! :)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int length;
int width;
int i;
int j;
char invisible_board;
void board_setup(int *rows, int *columns){
char *invisible_board[*rows][*columns];
char *player_board[*rows][*columns];
for (i = 0; i < *rows; i++){
for (j = 0; j < *columns; j++){
invisible_board[i][j] = "."; //Sets all elements in hidden board to water
}
}
for (i = 0; i < *rows; i++){
for (j = 0; j < *columns; j++){
player_board[i][j] = ".";
}
}
}
void display(int *rows, int *columns, char *invisible_board){
printf(" ");
for (i=1; i < *rows +1;i++){
printf("%d ",i);
}
printf("\n"); //Prints top row of co-ordinates
for (i=1; i < *columns+1;i++){
printf("%d ",i);
for (j=0;j < *columns;j++){ //Prints left column of co- ordinates and rows of game board
printf(" %c ",invisible_board[i-1][j]);
}
printf("\n");
}
}
int main(void){
printf("Please enter the amount of rows in your board\n");
scanf("%d",&length);
printf("Please enter the amount of columns in your board\n");
scanf("%d",&width);
board_setup(&length,&width);
display(&length,&width,&invisible_board);
return (0);
}
this is the simplest changes I could make to your code to get you to working code.... now.... this isn't good code yet. But gets you started.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int length;
int width;
int i;
int j;
char invisible_board[100][100]; // dynamically allocate....
char player_board[100][100]; // dynamically allocate....
void board_setup(int *rows, int *columns){
for (i = 0; i < *rows; i++){
for (j = 0; j < *columns; j++){
invisible_board[i][j] = '.'; //Sets all elements in hidden board to water
}
}
for (i = 0; i < *rows; i++){
for (j = 0; j < *columns; j++){
player_board[i][j] = '.';
}
}
}
void display(int *rows, int *columns){
printf(" ");
for (i=1; i < *rows +1;i++){
printf("%d ",i);
}
printf("\n"); //Prints top row of co-ordinates
for (i=1; i < *columns+1;i++){
printf("%d ",i);
for (j=0;j < *columns;j++){ //Prints left column of co- ordinates and rows of game board
printf(" %c ",invisible_board[i-1][j]);
}
printf("\n");
}
}
int main(void){
printf("Please enter the amount of rows in your board\n");
scanf("%d",&length);
printf("Please enter the amount of columns in your board\n");
scanf("%d",&width);
board_setup(&length,&width);
display(&length,&width);
return (0);
}

Resources