I have to output each string in 'ZOJ' order. the length of string is from 1 to 100. The 'E' means the end of the input.
I test my program with gcc. I try so many examples and the output is fine. However, the online judge turn out to be wrong answer.
Example:
Input:
ZZOOOJJJ
ZZZZOOOOOJJJ
ZOOOJJ
E
Output:
ZOJZOJOJ
ZOJZOJZOJZOO
ZOJOJO
Thank you!
Here is my code.
#include<stdio.h>
#include<string.h>
#define MAX_SIZE 100
main() {
char data[MAX_SIZE];
int len;
int z,o,j;
int i;
char c;
int z_index, o_index,j_index;
while(scanf("%s", data)!= EOF && (strlen(data)>=1 && data[0] != 'E')) {
len = strlen(data);
z = -1;
o = -1;
j = -1;
z_index = -1;
o_index = -1;
j_index = -1;
for(i=0; i<len; i++) {
c = data[i];
switch(c) {
case 'Z':
if(z==-1)
z_index=i,z=i;
else
z = i;
break;
case 'O':
if(o==-1)
o_index=i,o=i;
else
o = i;
break;
case 'J':
if(j==-1)
j_index=i,j=i;
else
j = i;
break;
}
}
while(z_index!=-1 || o_index!=-1 || j_index!=-1) {
if(z_index!=-1 && z_index<=z)
putchar('Z'), z_index++;
else
z_index = -1;
if(o_index!=-1 && o_index<=o)
putchar('O'), o_index++;
else
o_index = -1;
if(j_index!=-1 && j_index<=j)
putchar('J'), j_index++;
else
j_index = -1;
}
putchar('\n');
}
}
You should really make your function int main() rather than just main() therefore you should then return 0 at the end.
#include<stdio.h>
#include<string.h>
#define MAX_SIZE 100
int main() {
char data[MAX_SIZE];
int len;
int z,o,j;
int i;
char c;
int z_index, o_index,j_index;
while(scanf("%s", data)!= EOF && (strlen(data)>=1 && data[0] != 'E')) {
len = strlen(data);
z = -1;
o = -1;
j = -1;
z_index = -1;
o_index = -1;
j_index = -1;
for(i=0; i<len; i++) {
c = data[i];
switch(c) {
case 'Z':
if(z==-1)
z_index=i,z=i;
else
z = i;
break;
case 'O':
if(o==-1)
o_index=i,o=i;
else
o = i;
break;
case 'J':
if(j==-1)
j_index=i,j=i;
else
j = i;
break;
}
}
while(z_index!=-1 || o_index!=-1 || j_index!=-1) {
if(z_index!=-1 && z_index<=z)
putchar('Z'), z_index++;
else
z_index = -1;
if(o_index!=-1 && o_index<=o)
putchar('O'), o_index++;
else
o_index = -1;
if(j_index!=-1 && j_index<=j)
putchar('J'), j_index++;
else
j_index = -1;
}
putchar('\n');
}
return 0;
}
Related
I decided to write another one BF interpreter in order of personal development, and despite the fact that this is his second version written from scratch, one way or another it doesn't work correctly with cycles. Please tell me how this can be rewritten, or what is the logical problem. Below is the code and examples of programs in BF.
#include <stdio.h>
void brainfuck(char* str, int length)
{
char arr[30000] = { 0 };
int ptr = 0, i = 0;
int **brackets = { 0 };
int br_len = 0;
while (i < length)
{
if (str[i] == '[')
{
brackets = (int **)realloc(brackets, (br_len + 1) * sizeof(int *));
brackets[br_len] = (int *)malloc(2 * sizeof(int));
brackets[br_len][0] = '[';
brackets[br_len][1] = i;
br_len++;
}
else if (str[i] == ']')
{
brackets = (int **)realloc(brackets, (br_len + 1) * sizeof(int *));
brackets[br_len] = (int *)malloc(2 * sizeof(int));
brackets[br_len][0] = ']';
brackets[br_len][1] = i;
br_len++;
}
i++;
}
int counter, pos, j; i = 0;
while (i < length)
{
switch (str[i])
{
case '>': ptr++; break;
case '<': ptr--; break;
case '+': arr[ptr]++; break;
case '-': arr[ptr]--; break;
case '.': putchar(arr[ptr]); break;
case ',': arr[ptr] = getchar(); break;
case '[':
if (arr[ptr] == 0)
{
j = 0;
pos = 0;
do
{
pos = j;
j++;
}
while (brackets[j - 1][1] != i);
j = pos + 1;
counter = 1;
while (j < br_len)
{
if (brackets[j][0] == '[')
counter++;
else if (brackets[j][0] == ']')
{
counter--;
if (counter == 0)
break;
}
j++;
}
i = brackets[j][1];
}
break;
case ']':
if (arr[ptr] == 0)
{
j = br_len - 1;
pos = br_len - 1;
do
{
pos = j;
j--;
} while (brackets[j + 1][1] != i);
j = pos - 1;
counter = -1;
while (j >= 0)
{
if (brackets[j][0] == '[')
{
counter++;
if (counter == 0)
break;
}
else if (brackets[j][0] == ']')
counter--;
j--;
}
i = brackets[j][1] - 1;
}
break;
default: break;
}
i++;
}
free(brackets);
}
void main()
{
FILE* fr;
int length;
char* str;
fr = fopen("input.txt", "r");
fseek(fr, 0, SEEK_END);
length = ftell(fr);
rewind(fr);
str = (char*)malloc(length * sizeof(char));
fread(str, 1, length, fr);
brainfuck(str, length);
free(str);
fclose(fr);
}
"Hello World!" with one loop
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++
.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.
------.--------.>+.>.
"Hello World!" with nested loops
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
']' should jump back if cell is nonzero
Hugely convoluted approach; you want to put the matches in the brackets array so it's like
case '[':
if (arr[ptr] == 0)
i = brackets[i];
break;
Why i = brackets[j][1] - 1; and not just i = brackets[j][1]; (extra speed cost)
Having j and pos laboriously correlate is a red flag
Forgot to free all those little 2-int arrays
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Stack
{
char stk[50][50];
int top;
};
typedef struct Stack stack;
void push(stack *p, char c)
{
p->top++;
p->stk[p->top][0] = c ;
p->stk[p->top][1] = '\0';
}
void puush(stack *p, char val[])
{
p->top++;
int i=0 , len = strlen(val);
for( i = 0; i< len ; i++)
p->stk[p->top][i] = val[i];
p->stk[p->top][i] = '\0';
}
void pop(stack *p)
{
p->top--;
}
char *top(stack *p)
{
return p->stk[p->top];
}
void print(stack *p)
{
int i = 0;
while(i <= p->top)
{
printf("index : %d elements : %s\n", i+1, p->stk[i]);
i++;
}
printf("\n");
}
int isOperand(char c)
{
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
return 1;
else return 0;
}
int isOperator(char c)
{
switch(c)
{
case '+':
case '-':
case '*':
case '/':
return 1;
default:
return 0;
}
}
void prefixToInfix(char s[])
{
stack s1;
s1.top = -1;
int i=0, len = strlen(s) - 1;
for(i = len ; i>= 0 ; i--)
{
if(isOperand(s[i]))
{
printf("%c\n\n",s[i]);
push(&s1, s[i]);
print(&s1);
}
if(isOperator(s[i]))
{
char concat[20];
int k,j= -1;
concat[++j] = '(';
char *c1 = top(&s1);
pop(&s1);
int len1 = 0;
len1 = strlen(c1);
for(k=0; k<len1; k++)
{
concat[++j] = c1[k];
}
concat[++j] = s[i];
c1 = top(&s1);
len1 = strlen(c1);
pop(&s1);
for(k= 0; k<len1; k++)
concat[++j] = c1[k];
concat[++j]=')';
concat[++j] = '\0';
printf("gnerated %s\n",concat);
puush(&s1, concat);
print(&s1);
}
}
printf("%s",top(&s1));
}
int main()
{
prefixToInfix("*-A/BC-/AKL");
}
Please help me, I am not getting the correct output as it should be. I am sharing my code thus it will be easier for you all to understand the problem of my Code
Explanation of my problem:
I have been trying to write a code which converts The Prefix form to Infix. I am getting the output as I expected except one extra parenthesis at last:
For example:
The Input: "*-A/BC-/AKL"
Expected Output: ((A-(B/C))*((A/K)-L)
However my Program output:
((A-(B/C))*((A/K)-L)(, the last extra parenthesis is the issue "("
I am dealing with the hsearch function in my progam. I generate my key which is a char *. And the data I stored is an integer.
I always add an element without problem, but when I want to find with
ENTRY *elemp, elem;
elemp = hsearch(elem, FIND).
elemp->data is always a wrong value(not the one inserted).
Is there a known issue about that.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <search.h>
#define N 1
#define B 0
#define U 2
#define TAILLE 100000
char key[1000];
char* convTableToKeyString(int lignes, int colonnes, int joueur_tour, int tab[lignes][colonnes]) {
int indice = 0;
switch (joueur_tour) {
case 0:
key[indice++] = 'B';
break;
case 1:
key[indice++] = 'N';
break;
}
for (int i = 0; i < lignes; i++) {
for (int j = 0; j < colonnes; j++) {
switch (tab[i][j]) {
case 0:
key[indice++] = 'B';
break;
case 1:
key[indice++] = 'N';
break;
case 2:
key[indice++] = 'U';
break;
}
}
}
key[indice++] = '\0';
return key;
}
int valeur_configuration(int couleur_tour, int colonnes, int lignes, int tabEchec[lignes][colonnes]) {
ENTRY elem, *elemp;
int res;
int i,j;
int prochain_joueur = couleur_tour == B ? N : B;
int tabCase1[lignes][colonnes], tabCase2[lignes][colonnes], tabCase3[lignes][colonnes];
int lose_range = couleur_tour == B ? lignes-1 : 0;
int tabConf[3*colonnes];
int nbreCoupsPossibles = 0;
//generate the key and look if it already exist in the table
elem.key = convTableToKeyString(lignes, colonnes, couleur_tour, tabEchec);
elemp = hsearch(elem, FIND);
if (elemp != NULL) {
return (int) (elemp->data);
}
/* The value is not present in the hash, so I can calculate it */
//my code logic check the possible moves and add the value in the hash table
for (i = 0; i < lignes; i++) {
for (j = 0; j < colonnes; j++) {
int front = couleur_tour == B ? i-1 : i+1;
if (tabEchec[i][j] == couleur_tour) {
if (j != 0 && tabEchec[front][j-1] == prochain_joueur) {
/* some operations */
tabConf[nbreCoupsPossibles++] = valeur_configuration(prochain_joueur, colonnes, lignes, tabCase2);
if(tabConf[nbreCoupsPossibles-1] ==0) {
res = 1;
elem.data = (void *) res;
elemp = hsearch(elem, ENTER);
/* there should be no failures */
if (elemp == NULL) exit(EXIT_FAILURE);
return 1;
}
} // if (j != 0 && tabEchec[front][j-1] == prochain_joueur)
if (j != colonnes-1 && tabEchec[front][j+1] == prochain_joueur) {
/* some operations */
tabConf[nbreCoupsPossibles++] = valeur_configuration(prochain_joueur, colonnes, lignes, tabCase3);
if(tabConf[nbreCoupsPossibles-1] ==0) {
res = 1;
elem.data = (void *) res;
elemp = hsearch(elem, ENTER);
/* there should be no failures */
if (elemp == NULL) exit(EXIT_FAILURE);
return 1;
}
} // if (j != colonnes-1 && tabEchec[front][j+1] == prochain_joueur)
if (tabEchec[front][j] == U) {
/* some operations */
tabConf[nbreCoupsPossibles++] = valeur_configuration(prochain_joueur, colonnes, lignes, tabCase1);
if(tabConf[nbreCoupsPossibles-1] ==0) {
res = 1;
elem.data = (void *) res;
elemp = hsearch(elem, ENTER);
/* there should be no failures */
if (elemp == NULL) exit(EXIT_FAILURE);
return 1;
}
} // if (tabEchec[front][j].couleur == U)
} // if (tabEchec[i][j] == couleur_tour)
} // for (j = 0; j < colonnes; j++)
} // for (i = 0; i < lignes; i++)
if(nbreCoupsPossibles == 0) {
//Haven't move, I lost
res = 0;
elem.data = (void *) res;
elemp = hsearch(elem, ENTER);
/* there should be no failures */
if (elemp == NULL) exit(EXIT_FAILURE);
return 0;
}
i = 0;
int maxi = 0;
while (i < nbreCoupsPossibles && tabConf[i] > 0) {
maxi = maxi > tabConf[i] ? maxi : tabConf[i];
i++;
}
if (i >= nbreCoupsPossibles) {
res = -1 * (maxi+1);
elem.data = (void *) res;
elemp = hsearch(elem, ENTER);
/* there should be no failures */
if (elemp == NULL) exit(EXIT_FAILURE);
return res;
} else {
maxi = tabConf[i];
while (i < nbreCoupsPossibles) {
if (tabConf[i] < 0) {
maxi = maxi > tabConf[i] ? maxi : tabConf[i];
}
i++;
}
res = -1 * (maxi-1);
elem.data = (void *) res;
elemp = hsearch(elem, ENTER);
elemp = hsearch(elem, FIND);
/* there should be no failures */
if (elemp == NULL) exit(EXIT_FAILURE);
return res;
} // if (i >= nbreCoupsPossibles)
return 0;
}
/* Function call first call*/
int main() {
int n,m,i,j;
hcreate(TAILLE);
int colonnes;
int lignes;
char b = 'a';
scanf("%d", &n);
scanf("%d", &m);
int tabPions[n][m];
char temp[m];
//Fake : just for flushing scanf internal functions
scanf("%c", &b);
for (i = 0; i < n; i++) {
scanf("%[^\n]%*c", temp);
for (j = 0; j < m; j++) {
if (temp[j] != 'p' && temp[j] != 'P') tabPions[i][j] = U;
if (temp[j] == 'p') tabPions[i][j] = N;
if (temp[j] == 'P') tabPions[i][j] = B;
}
}
colonnes = m;
lignes = n;
int res = valeur_configuration(B, colonnes, lignes, tabPions);
printf("%d\n", res);
hdestroy();
}
I don't completely understand the program, but I think I can explain your hsearch problem.
You are reusing the global char key[1000] buffer for every key. hsearch doesn't allow that. When you add an item to the hash table, hsearch doesn't make a copy of the key string. It only copies the pointer.
Since you're using the same key buffer for all your ENTERs and your FINDs, every key in the hash table matches the one you're looking for, every time, because they're all the same string! Most of them are in the wrong hash bucket, making the result of a lookup somewhat random.
A quick fix would be to do elem.key = strdup(elem.key) just before each ENTER operation.
If you care about freeing the strings before your program exits, you'll have to work a little harder on the memory management. hsearch is not helpful in that area, since it doesn't provide an iterator.
I have a program which solves maze, so that it finds possible route from Start(S) to Exit(E).Here is my Maze:
1111S11110
0000010001
110100010d
t001111110
0100000001
0111111101
1111111101
00000D01T1
0111110001
0000E01110
The possible route to it is :
Start S W W S S S E E E E E E S S S S W W N W W W W W W S S E E E E Exit
which is correct and i get it on CodeBlocks, However when i compile my code on dev through putty i get this:
Start S S S S S W N N W S W N N N W N Exit
Here is my whole code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
// Global Variables for use
int matrixSize,startX,startY,exitX,exitY;
char src[1500] = " ";
char Ndirection[50] = " N ";
char Sdirection[50] = " S ";
char Edirection[50] = " E ";
char Wdirection[50] = " W ";
// Function for finding the array length
int numOfLines(FILE *const mazeFile) {
int c, count;
count = 0;
for (;; ) {
c = fgetc(mazeFile);
if (c == EOF)
break;
if (c == '\n')
++count; // end of line => increment line counter
}
rewind(mazeFile);
return count+1;
}
int capLetter(char ch){
int result = 0;
if(ch >= 'A' && ch <= 'Z'){
result = 1;
}
return result;
}
int lowLetter(char ch){
int result = 0;
if(ch >= 'a' && ch <= 'z'){
result = 1;
}
return result;
}
int isSafe(char Mazearray[matrixSize][matrixSize],int x,int y){
if(x >= 0 && x < matrixSize && y >= 0 && y < matrixSize && Mazearray[x][y] != '1'){
return 1;
}
return 0;
}
void MazeSolution(char Mazearray[matrixSize][matrixSize],int x,int y,char pathArray[matrixSize][matrixSize],char wasHereArray[matrixSize][matrixSize]){
if(recursiveMaze(Mazearray,x,y,pathArray,wasHereArray) == 0){
printf("There does not exist a possible solution!!!");
}
else{
pathArray[startX][startY] = 'S';
}
}
int recursiveMaze(char Mazearray[matrixSize][matrixSize],int x,int y,char pathArray[matrixSize][matrixSize],char wasHereArray[matrixSize][matrixSize]){
if(x == startX && y == startY){
pathArray[x][y] = 'S';
}
if(x == exitX && y == exitY){
pathArray[x][y] = 'E';
return 1;
}
// check if the coordinate is safe to go(not 1)
if(isSafe(Mazearray,x,y) == 1 && wasHereArray[x][y] != '1'){
wasHereArray[x][y] = '1';
// Move North
if(recursiveMaze(Mazearray,x-1,y,pathArray,wasHereArray) == 1){
pathArray[x][y] = 'R';
strcat(src,Ndirection);
return 1;
}
// Move South
if(recursiveMaze(Mazearray,x+1,y,pathArray,wasHereArray) == 1){
pathArray[x][y] = 'R';
strcat(src,Sdirection);
return 1;
}
// Move East
if(recursiveMaze(Mazearray,x,y+1,pathArray,wasHereArray) == 1){
pathArray[x][y] = 'R';
strcat(src,Edirection);
return 1;
}
// Move West
if(recursiveMaze(Mazearray,x,y-1,pathArray,wasHereArray) == 1){
pathArray[x][y] = 'R';
strcat(src,Wdirection);
return 1;
}
}
return 0;
}
// Main Function
int main( int argc, char **argv )
{
// Opening the Matrix File
FILE *mazeFile;
mazeFile = fopen(argv[1], "r" );
if( mazeFile == NULL )
return 1;
matrixSize = numOfLines( mazeFile );
// Reading text file into 2D array
int i,j;
char mazeArray [matrixSize][matrixSize];
for (i = 0; i<matrixSize; i++) {
for (j = 0; j<matrixSize; j++) {
fscanf(mazeFile, "%c", &mazeArray[i][j]);
}
char eol;
fscanf(mazeFile, "%c", &eol);
}
// Variables
//Creating path array
char pathArray[matrixSize][matrixSize];
for (i = 0; i < matrixSize; i++){
for (j = 0; j < matrixSize; j++){
pathArray[i][j] = '0';
}
}
// CheckPoint array
char wasHereArray[matrixSize][matrixSize];
for (i = 0; i < matrixSize; i++){
for (j = 0; j < matrixSize; j++){
wasHereArray[i][j] = '0';
}
}
// Finding start and exit indexes
for (i = 0; i<matrixSize; i++) {
for (j = 0; j<matrixSize; j++) {
if(mazeArray[i][j] == 'S'){
startX = i;
startY = j;
}
if(mazeArray[i][j] == 'E'){
exitX = i;
exitY = j;
}
}
}
MazeSolution(mazeArray,startX,startY,pathArray,wasHereArray);
char *data = src;
int length=strlen(data);
char bytes[length];
int n=0;
while(n<=length)
{
bytes[n] = data[length-n-1];
n++;
}
FILE *f = fopen("path.txt", "w");
fprintf(f, "Start %s Exit",bytes);
fclose(mazeFile);
fclose(f);
return 0;
}
I don't know what is wrong and where to start?
DOS line endings are CR-LF ("\r\n") and *nix line endings are just LF ("\n"). Change these lines main:
char eol;
fscanf(mazeFile, "%c", &eol);
to:
int c = fgetc(mazefile); // Slurp a '\r' carriage return or '\n' linefeed character.
if ('\r' == c) {
c = fgetc(mazefile); // slurp the '\n' linefeed character.
}
iam new to c program and facing difficulty in debugging programs.In the below code test case 2 is not running.I have found that the error is in reading interger n in the second test case.someone please hep me with this issue.Also please recommend me with some tools that can be ued for debugging c programs using terminal.Thanks for help
#include <stdio.h>
#include <stdlib.h>
int read(){
int r = 0;
char c = getchar_unlocked();
while(c >= '0' && c <= '9'){
r = r*10 + c - 48 ;
c = getchar_unlocked();
}
return r;
}
void main(){
int t = 0;
t = read();
int rr = 0;
for(rr = 0;rr < t;rr++){
int i,n = 0;
n = read();
int *p = (int *)calloc(n,sizeof(int));
for(i = 0;i < n;++i){
*(p+i) = getchar_unlocked() - 48;
}
int no,nz = 0;
for(i = 0;i < n;++i){
if(*(p+i) == 0){nz += 1;}
if(*(p+i) == 1){no += 1;}
}
int k = 0;
if(((no)%2 == 0) && ((nz)%2) == 0){
k = -1;
}
if(((no)%2 == 0) && ((nz)%2) == 1){
k = 0;
}
if(((no)%2 == 1) && ((nz)%2) == 0){
k = 1;
}
if(((no)%2 == 1) && ((nz)%2) == 1){
k = 1;
}
int result = 0;printf("%d\n",5556);
if(k == 1){
for(i = 0;i < n;++i){
if(*(p+i) == 1){
result = i+1 ;
break;
}
}
}
if(k == 0){
for(i = 0;i < n;++i){
if(*(p+i) == 0){
result = i+1 ;
break;
}
}
}
printf("%d\n",result);
}
}
Your strategy to read an integer is flawed. You don't have the logic to skip whitespaces. I would change the function name to read_int and change its implementation to
int read(){
int n;
if ( scanf("%d", &n) != 1 )
{
// Deal with the error
}
return n;
}
Also, change
*(p+i) = getchar_unlocked() - 48;
to
*(p+i) = read_int();
or a more intuitive version:
p[i] = read_int();
With those changes, I am able to read and process the numbers. But I still get the wrong output. I'll let you figure the logic error in your code.
Additional Comments
main is expected to return an int. If your compiler didn't complain about that, it's time to up the warning level. I use -Wall by default.
When you are in the process of debugging your code, it's always good to test the code that reads the input to make sure that there is no error in reading the input.
Here's what I did to your code:
#include <stdio.h>
#include <stdlib.h>
int read_int(){
int n;
if ( scanf("%d", &n) != 1 )
{
// Deal with the error.
}
return n;
}
int main(){
int t = 0;
int rr = 0;
t = read_int();
printf("t = %d\n", t);
for(rr = 0;rr < t;rr++){
int i,n = 0;
n = read_int();
printf("n = %d\n", n);
int *p = (int *)calloc(n,sizeof(int));
for(i = 0;i < n;++i){
p[i] = read_int();
printf("p[%d] = %d\n", i, p[i]);
}
int no,nz = 0;
for(i = 0;i < n;++i){
if(*(p+i) == 0){nz += 1;}
if(*(p+i) == 1){no += 1;}
}
int k = 0;
if(((no)%2 == 0) && ((nz)%2) == 0){
k = -1;
}
if(((no)%2 == 0) && ((nz)%2) == 1){
k = 0;
}
if(((no)%2 == 1) && ((nz)%2) == 0){
k = 1;
}
if(((no)%2 == 1) && ((nz)%2) == 1){
k = 1;
}
int result = 0;
// printf("%d\n",5556);
if(k == 1){
for(i = 0;i < n;++i){
if(*(p+i) == 1){
result = i+1 ;
break;
}
}
}
if(k == 0){
for(i = 0;i < n;++i){
if(*(p+i) == 0){
result = i+1 ;
break;
}
}
}
printf("%d\n",result);
}
return 0;
}