Error condition, how to implement it? - c

So what my codes does at the moment is quite simple. It receives an input like this:
5 4
1 2
2 3
3 4
4 5
The first line of the input represents the number of Ids and the number of relations. The following line are those relations. The program sorts these pairs, for example: 1 comes before 2, 2 comes before 3 and so on. In this case the outup will be 1 2 3 4 5.
In case of contradictive input, such as:
4 4
1 2
2 3
3 2
3 4
It returns "Incoerente".
My current problem is my input is "non conclusive" such as:
4 4
1 2
3 1
3 4
4 2
In this case the program doesnt really know where to place the 4 (after or before the 1?). My program right now (with the input above) will print "3 1 2", and ignores the 4 for some reason. When this situation apears I want to print "OTHERERROR".
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
void create_graph();
void add(int vertex);
int del();
int isEmpty();
int find_indegree_of_vertex(int vertex);
int total_vertices;
int adjacent_matrix[MAX][MAX];
int queue[MAX];
int front = -1;
int rear = -1;
FILE *myFile;
int main(){
myFile = fopen("input.txt", "r");
int i;
int numberArray[2];
for(i=0;i<2;i++)
fscanf(myFile, "%1d", &numberArray[i]);
int N = numberArray[0];
int L = numberArray[1];
int vertex, count, topological_sort[MAX], indegree[MAX];
create_graph(N, L);
for(i = 0; i < total_vertices; i++){
indegree[i] = find_indegree_of_vertex(i);
if(indegree[i] == 0){
add(i);
}
}
count = 0;
while(!isEmpty() && count < total_vertices){
vertex = del();
topological_sort[++count] = vertex;
for(i = 0; i < total_vertices; i++){
if(adjacent_matrix[vertex][i] == 1){
if(adjacent_matrix[i][vertex] == 1){
printf("INCOERENTE !!!!!!!!!!!!!!!\n");
}
adjacent_matrix[vertex][i] = 0;
indegree[i] = indegree[i] - 1;
if(indegree[i] == 0){
add(i);
}
}
}
}
if(count < total_vertices){
printf("Incoerente\n");
exit(1);
}
printf("Topological Order of Vertices\n");
for(i = 1; i <= count; i++){
printf("%3d", topological_sort[i]+1);
}
printf("\n");
return 0;
}
void add(int vertex){
if(rear == MAX - 1){
printf("Queue Overflow\n");
}
else{
if (front == -1) {
front = 0;
}
rear = rear + 1;
queue[rear] = vertex ;
}
}
int isEmpty(){
if(front == -1 || front > rear ){
return 1;
}
else{
return 0;
}
}
int del(){
int element;
if (front == -1 || front > rear){
printf("Queue Underflow\n");
exit(1);
}
else{
element = queue[front];
front = front+1;
return element;
}
}
int find_indegree_of_vertex(int vertex){
int count, total_indegree = 0;
for(count = 0; count < total_vertices; count++){
if(adjacent_matrix[count][vertex] == 1){
total_indegree++;
}
}
return total_indegree;
}
void create_graph(int N, int L){
int count, maximum_edges, origin_vertex, destination_vertex;
total_vertices = N;
maximum_edges = L;
int integers[MAX];
int i =0;
int num;
while(fscanf(myFile, "%d", &num) > 0) {
integers[i] = num;
i++;
}
i=0;
printf("1a linha :%d %d\n", N, L);
for(count = 1; count <= maximum_edges; count++){
origin_vertex = integers[i]-1;
destination_vertex = integers[i+1]-1;
printf("pares a ser avaliados :%d %d\n", origin_vertex+1, destination_vertex+1);
if(origin_vertex > total_vertices || destination_vertex > total_vertices || origin_vertex < 0 || destination_vertex < 0){
printf("Edge Co-ordinates are Invalid\n");
count--;
}
else
adjacent_matrix[origin_vertex][destination_vertex] = 1;
if(count == maximum_edges){
break;
}
i+=2;
}
}

Related

Kruskal Algorithm, exited with code=code=3221225477

#define MAX_VERTICES 10000
#define MAX_EDGES 50000000
#define HEAP_EMPTY(n) (!n)
#define LINE_SIZE 100
#define HEAP_FULL(n) (n == MAX_EDGES-1)
typedef struct {
int weight;
int node1;
int node2;
} element;
element min_heap[MAX_EDGES];
int parent_array[MAX_VERTICES];
element delete_min_heap(int *n) {
/* delete element with the highest key from the heap */
int parent, child;
element item, temp;
if(HEAP_EMPTY(*n)) {
fprintf(stderr, "The heap is empty");
exit(1);
}
/* save value of the element with the largest key */
item = min_heap[1];
/* use the last element in the heap to adjust heap */
temp = min_heap[(*n)--];
parent = 1;
child = 2;
while(child <= *n) {
/* find the larger child of the current parent */
if((child < *n) && (min_heap[child].weight > min_heap[child+1].weight)) child++;
if(temp.weight <= min_heap[child].weight) break;
/* move to the next lower level */
min_heap[parent] = min_heap[child];
parent = child;
child *= 2;
}
min_heap[parent] = temp;
return item;
}
void insert_min_heap(element item, int *n) {
int i;
if(HEAP_FULL(*n)) {
fprintf(stderr, "The heap is full.\n");
exit(1);
}
i = ++(*n);
while((i != 1) && (item.weight < min_heap[i/2].weight)) {
min_heap[i] = min_heap[i/2];
i /= 2;
}
min_heap[i] = item;
}
int simpleFind(int i) {
for( ; parent_array[i] >= 0; i = parent_array[i])
;
return i;
}
void weightedUnion(int i, int j) {
int temp = parent_array[i] + parent_array[j];
if(parent_array[i] > parent_array[j]) {
parent_array[i] = j;
parent_array[j] = temp;
} else {
parent_array[j] = i;
parent_array[i] = temp;
}
}
void main(int argc, char **argv) { //argc = argument 개수 argv argument list
//if(argc != 2) {
//printf("No input file is given or Two many input files are given.\n");
//exit(0);
//}
clock_t start = clock();
FILE *fp1 = fopen("input_large.txt", "r"); //replace to argv[1]
if(fp1 == NULL) {
printf("The input file does not exist.\n");
exit(0);
}
char *command_line;
char buffer[LINE_SIZE];
int cost;
int n_connected;
start = clock();
FILE *f = fopen("hw3_result.txt", "w+");
int line_num= 0;
int num_edges;
int num_vertices;
int n_heap = 0;
while (!feof(fp1)) { //한줄 씩 입력받기
element edge;
command_line = fgets(buffer, sizeof(buffer), fp1);
if(line_num == 0) {num_vertices = atoi(command_line);}
else if(line_num == 1) {num_edges = atoi(command_line);}
else {
int vertex_from = atoi(strtok(command_line, " "));
int vertex_to = atoi(strtok(NULL, " "));
int weigth = atoi(strtok(NULL, " "));
edge.node1 = vertex_from;
edge.node2 = vertex_to;
edge.weight = weigth;
insert_min_heap(edge, &n_heap);
}
line_num++;
}
fclose(fp1);
int i = 0;
for(i = 0; i< num_vertices; i++) { parent_array[i]=-1;}
element edge = delete_min_heap(&n_heap);
int j = 0;
cost = 0;
n_connected =0;
while((n_heap >= 0) && (n_connected != num_vertices)) {
int node1 = edge.node1;
int node2 = edge.node2;
if(j == 0) {
weightedUnion(node1, node2);
cost += edge.weight;
//printf("%d %d %d\n",node1, node2, edge.weight);
n_connected += 2;
j++;
}
else if ( simpleFind(node1) != simpleFind(node2)) {
weightedUnion(node1, node2);
cost += edge.weight;
//printf("%d %d %d\n",node1, node2, edge.weight);
n_connected++;
}
edge = delete_min_heap(&n_heap);
printf("%d %d\n", n_connected, n_heap);
}
printf("END\n");
printf("COST%d\n", cost);
printf("num vertices %d connected %d\n", num_vertices, n_connected);
if(n_connected < num_vertices) printf("DISCONNECTED\n");
if(n_connected == num_vertices) printf("CONNECTED\n");
fclose(f);
clock_t end = clock();
double time_spent = (double)(end - start) / CLOCKS_PER_SEC;
printf("output written to hw3_result.txt\n");
printf("running time :%lf\n", time_spent);
}
I tried to implement Kruskal's Algorithm, but I faced some problems. The format of the input file is like this.
7
9
0 1 28
0 5 10
1 2 16
1 6 14
2 3 12 //source vertex destination vertex weight
3 4 22
3 6 18
4 5 25
4 6 24
The first line is the number of vertices and the second is number of edges. There is no problem when running small input file, but when the input file is very large, the program is exited with code=3221225477.
This code is to find where the code is exited
while((n_heap >= 0) && (n_connected != num_vertices)) {
int node1 = edge.node1;
int node2 = edge.node2;
if(j == 0) {
weightedUnion(node1, node2);
cost += edge.weight;
//printf("%d %d %d\n",node1, node2, edge.weight);
n_connected += 2;
j++;
}
else if ( simpleFind(node1) != simpleFind(node2)) {
weightedUnion(node1, node2);
cost += edge.weight;
//printf("%d %d %d\n",node1, node2, edge.weight);
n_connected++;
}
edge = delete_min_heap(&n_heap);
**printf("%d %d\n", n_connected, n_heap);** //here
}
The result is like this.
...
1657 4998343 //num of connected vertices num of heap's remaining element
1658 4998342
1659 4998341
1660 4998340
1661 4998339
1662
After deleting 1661 element in heap, for some reasons, program doesn't work any more.

Dynamically Allocating Memory In

I created the four in a row game in c. Now I want to dynamically allocate the memory of the board. It is a two-dimensional array and I want it stored there for use. I declare it as a global double-pointer and declare it in my initialization method in the code below. I am new to c and I'm not entirely sure how to go about handling the segmentation fault(core dumped) error that I get.
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 50
//size of board
#define rows 6
#define column 7
//player's name
char player1[100];
char player2[100];
//pointer to keep track of playes turn
char *playersTurn;
//counter to keep track of where we are on each column
int a = rows - 1;
int b = rows - 1;
int c = rows - 1;
int d = rows - 1;
int e = rows - 1;
int f = rows - 1;
int g = rows - 1;
//array of the board
//int board[rows][column];
int **board;
//boardlaying array elements
void boardlayArray(){
printf("Two Dimensional array elements:\n");
for(int i=0; i<rows; i++) {
for(int j=0;j<column;j++) {
printf("%d ", board[i][j]);
if(j==6){
printf("\n");
}
}
}
}
//recostruct board to empty places
void teardown(){
/*Counter variables for the loop*/
int i, j;
for(int i=0; i<rows; i++) {
for(int j=0;j<column;j++) {
board[i][j]=0;
}
}
boardlayArray();
}
//checks if the four in a row are the same
int checkFour(int a, int b, int c, int d){
return a == b && b == c && c == d;
}
//check for the horizontal win
void checkHorizontal(int player){
for(int i=0; i < rows; i++){
for(int j=0; j < column - 3; j++){
if ((board[i][j] != 0) && (board[i][j+1] != 0) && (board[i][j+2]!= 0) && (board[i][j+3] != 0)){
if (checkFour(board[i][j],board[i][j+1],board[i][j+2],board[i][j+3]) == 1){
printf("Game Over\n");
exit(0);
}
}
}
}
}
//check for vertical win
void checkVertical(int player){
for(int j=0; j < column; j++){
for(int i=rows - 1; i > rows - 3; i--){
if ((board[i][j] != 0) && (board[i-1][j] != 0) && (board[i-2][j]!= 0) && (board[i-3][j] != 0)){
if (checkFour(board[i][j],board[i-1][j],board[i-2][j],board[i-3][j]) == 1){
printf("Game Over\n");
exit(0);
}
}
}
}
}
//check for diagonal win
void checkDiagonal (int player){
// ascendingDiagonalCheck
for (int i=3; i<column; i++){
for (int j=0; j<rows-3; j++){
if ((board[i][j] != 0) && (board[i-1][j+1] != 0) && (board[i-2][j+2]!= 0) && (board[i-3][j+3] != 0)){
if (checkFour(board[i][j],board[i-1][j+1],board[i-2][j+2],board[i-3][j+3]) == 1){
printf("Game Over\n");
exit(0);
}
}
}
}
// descendingDiagonalCheck
for (int i=3; i<column; i++){
for (int j=3; j<rows; j++){
if ((board[i][j] != 0) && (board[i-1][j-1] != 0) && (board[i-2][j-2]!= 0) && (board[i-3][j-3] != 0)){
if (checkFour(board[i][j],board[i-1][j-1],board[i-2][j-2],board[i-3][j-3]) == 1){
printf("Game Over\n");
exit(0);
}
}
}
}
}
//places the players puck into the correct place and gives it a corresponding value
//Also checks and correspondingly updtaes the turn to same player if row is full
int updateWorld(char w, int playerNumber){
switch(w)
{
case 'A':
if(a == -1){
printf("This row is full\n");
return 0;
}
board[a][0] = playerNumber;
a--;
break;
case 'B' :
if(b == -1){
printf("This row is full\n");
return 0;
}
board[b][1] = playerNumber;
b--;
break;
case 'C' :
if(c == -1){
printf("This row is full\n");
return 0;
}
board[c][2] = playerNumber;
c--;
break;
case 'D' :
if(d == -1){
printf("This row is full\n");
return 0;
}
board[d][3] = playerNumber;
d--;
break;
case 'E' :
if(e == -1){
printf("This row is full\n");
return 0;
}
board[e][4] = playerNumber;
e--;
break;
case 'F' :
if(a == -1){
printf("This row is full\n");
return 0;
}
board[f][5] = playerNumber;
f--;
break;
case 'G' :
if(g == -1){
printf("This row is full\n");
return 0;
}
board[g][6] = playerNumber;
g--;
break;
case ' ' : printf("Nothing was entered\n");
break;
case 'Q' : printf("%s has quit game\n", playersTurn);
teardown();
exit(0);
break;
default: printf("Enter a wrong option\n");
}
boardlayArray();
checkHorizontal(playerNumber);
checkVertical(playerNumber);
checkDiagonal(playerNumber);
return 1;
}
//get player's names and dynamicaaly allocate memory for board
void initialization(){
printf("Enter the name of player 1:\n");
fgets(player1,MAX, stdin);
printf("Enter the name of player 2:\n");
fgets(player2,MAX, stdin);
board = (int **)malloc(rows * sizeof(int *));
for (int i=0; i<rows; i++)
board[i] = (int *)malloc(column * sizeof(int));
}
//get where player wants to play
char acceptInput(){
printf("Enter where you want to put the disc A-G. Enter Q if you want to quit.\n");
char w;
scanf("%[^\n]",&w);
return w;
}
int main(){
initialization();
char w;
//runs for the size of the board
for(int i = 1; i <= (rows * column); i++){
w = acceptInput();
w = toupper(w);
if(i%2 == 0){
playersTurn = (char*) player2;
if(updateWorld(w,2) == 0){
playersTurn = (char*) player1;
printf("%s won the game",playersTurn);
exit(0);
}
}
else{
playersTurn = (char*) player1;
if(updateWorld(w,1) == 0){
playersTurn = (char*) player2;
printf("%s won the game",playersTurn);
exit(0);
}
}
while(getchar() != '\n');
}
return 0;
}
How About using the heap?? That's the goto of a programmer for dynamic memory allocation , here is a simple 2d array allocation code :
int main()
{
int r = 3, c = 4, i, j, count;
int *arr[r];
//allocating memory for an array
for (i=0; i<r; i++)
arr[i] = (int *)malloc(c * sizeof(int));
/*code to debug */
//free memory before allocating again
for(i=0; i<r; i++)
free(arr[i]);
//reallocating memory for an array
for(i=0; i<r+2; i++)
arr[i] = (int *)malloc(c * sizeof(int));
return 0;
/* code to work on reallocated array */
}

Array issue in C

I have an university project in C programming. I ran into a problem with the following task. My program should order numbers in two arrays. In the first array i must save (the biggest of every fifth element) and that is my problem. I am not sure how to make the loop which reads five elements compare them, take the biggest one, and then continue doing this with the other elements. I am hoping someone to help because I blocked.
#define A 100
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void show(int x[], int nx); //функция за показване на масивите
float vavedi(int x[], int nx); //функция, чрез която ръчно въвеждаме числата и ги обработваме
FILE* readFile(char* fname); //функция която чете файл и представя съдържанието му като масиви
int main()
{
int call, a = 0, b = 0, mode = 0, i = 0;
int check = 0;
char fail[A];
char* menu[] = {
"PROGRAM STARTED!",
"Enter an option:",
"1 : Write the numbers.",
"2 : Choose from a file.",
"0 : Exit."
};
do {
for (i = 0; i < 5; i++)
printf("%s\n", menu[i]);
check=scanf("%d", &mode);
if (check != 1)
printf("ERROR! Try again!");
switch (mode)
{
case 1: {
//в случай 1 числата се въведждат от потребителя
call = vavedi(a, b);
break;
}
case 2: {
//в случай 2 потребителя използва съществуващ файл
printf("Enter the path of the file you want to open:\n");
scanf("%s", fail);
call = readFile(fail);
if (call == NULL) {
printf("The file doesn't exist! Try again!\n");
}
break;
}
case 0:
break;
default:
{
printf("ERROR! Try again!\n");
}
}
} while (mode != 0);
printf("\nThe program ended!\n");
return 0;
}
void show(int x[], int nx)
{
int k;
for (k = 0; k < nx; k++)
{
printf("\n Element[%d]= %d", k, x[k]);
}
}
float vavedi(int x[], int nx)
{
int call=0;
int enter=0;
int imin, max;
int b[A], c[A];
int i, j, j1, count;
j = 0;
do {
printf("\nCount of the elements:");
scanf("%d", &count);
if (count <= 0 || count > 100)
printf("Invalid input! Try again!\n");
} while (count <= 0 || count > 100);
for (i = 0; i < count; i++)
{
printf("\nEnter an element:");
scanf("%d", &c[i]);
}
printf("\n");
return enter;
}
Update : Including header file mentioned by #pmg.
If i understand correctly, your problem is to find largest element for every five elements:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <limits.h> // Put this after your header files
..
.. //Rest of the code.
..
for (i = 0; i < count; i++)
{
printf("\nEnter an element:");
scanf("%d", &c[i]);
}
size_t size = ceil(count/5.0);
memset(b , INT_MIN , size);
for(int i = 0 ; i < count ; i++)
{
b[i/5] = b[i/5] > c[i] ? b[i/5] : c[i];
}
// Print b like this:
for(i = 0 ; i < size; i++)
printf("%d" , b[i] );
Let's see how this works for array of size 9. array's indices will go from 0 to 8 . If I divide each of them by 5, I get 0 for i = 0 to 4 and 1 for i = 5 to 8. Now we can take max over elements in buckets of 5. You seem to be a beginner, hope this helps you in creating better understanding.
The other problem is the following:
{
int c[A], b[A];
int i = 0, j = 0, k = 0, num;
FILE* fp= NULL; //указател за файл
fp = fopen(fname, "r");
if (fp)
{
while (fscanf(fp, "%d", &c[i]) != EOF)
i++;
num=i;
size_t size = ceil(num/5.0);
memset(b , INT_MIN , size);
for(i = 0 ; i < num ; i++)
{
b[i/5] = b[i/5] > c[i] ? b[i/5] : c[i];
}
printf("\nARRAY1:\n");
for(i = 0 ; i < size; i++)
{
buble(b, i);
printf(" Element[%d]=%1d\n", i, b[i]);
}
printf("\nARRAY2:");
buble(c, num);
show(c, num);
printf("\n");
}
fclose(fp);
return fp;
}
It doesn't calculate the rigth way.

Why does it say 'expected declaration specifiers before 'main''

first of all, I understand mostly everything in this program that I copied from this book.
second, i just wanted to see if it worked ,
the only problem is that it says 'expected declaration specifiers before 'main''
and i don't know what it means
ps this is a really long program (300+ lines)
#include <stdio.h>
#include <time.h>
#include <ctype.h>
#include <stdlib.h>
#define FALSE 0
#define TRUE 1
void printGreeting();
int getBet();
char getSuit(int suit);
char getRank(int rank);
void getFirstHand(int cardRank[], int cardSuit[]);
void getFinalHand
(int cardRank[], int cardSuit[], int finalRank[], int finalSuit[], int
ranksinHand[], int suitsinHand[])
int analyzeHand(int ranksinHand[], int suitsinHand[]);
main()
{
int bet;
int bank = 100;
int i;
int cardRank [5];
int cardSuit [5];
int finalRank[5];
int finalSuit[5];
int ranksinhand[13];
int suitsinhand[4];
int winnings;
time_t t;
char suit, rank, stillPlay;
printGreeting();
do{
bet = getBet();
srand(time(&t));
getFirstHand(cardRank, cardSuit);
printf("Your five cards: \n\n");
for (i = 0; i < 5; i++)
{
suit = getSuit(cardsSuit[i]);
rank = getRank(cardRank[i]);
printf("Card #%d: %c%c\n\n", i+1, rank, suit);
}
for (i=0; i < 4; i++)
{
suitsinHand[i] = 0;
}
for (i=0; i < 13; i++)
{
ranksinHand[i] = 0;
}
getFinalHand(cardRank, cardSuit, finalRank, finalSuit, ranksinHand,
suitsinHand);
printf("Your five final cards:\n\n");
for (i = 0; i < 5; i++)
{
suit = getSuit(finalSuit[i]);
rank = getRank(finalRank[i]);
printf("Card #%d: %c%c\n\n", i+1, rank, suit);
}
winnings = analyzeHand(ranksinHand, suitsinHand);
printf("You won %d!\n\n", bet*winnings);
bank = bank - bet + (bet*winnings)
printf("\n\nYour bank is now %d.\n\n", bank);
printf("Want to play again? ");
scanf(" %c", &stillPlay);
}while (toupper(stillPlay) == 'Y');
return;
}
/*************************************************************************/
void printGreeting();
{
printf("**********************************************************\n\n");
printf("\n\n\tWelcome to the Absolute Beginner's Casino\n\n");
printf("\tHome of the Video Draw Poker");
printf("**********************************************************\n\n");
printf("Here are the rules\n");
printf("You start with 100 credits, and you make a bet from");
printf("1 to 5 credits.\n");
printf("You are dealt 5 cards, and then you choose which ");
printf("cards to keep");
printf("or discard\n");
printf("You want to make the best possible hand.\n");
printf("\nHere is the table for winnings (assuming a ");
printf("bet of 1 credit):");
printf("\nPair \t\t\t\t1 credit");
printf("\nTwo pairs\t\t\t2 credits");
printf("\nThree of a kind\t\t\t3 credits");
printf("\nStraight \t\t\t4 credits");
printf("Flush\t\t\t\t5 credits");
printf("Full House\t\t\t8 credits");
printf("Four of a Kind\t\t\t10 credits");
printf("Straight Flush\t\t\t20 credits");
printf("\n\nHave fun!!\n\n");
}
void getFirstHand(int cardRank[], int cardSuit[]);
{
int i,j;
int carDup;
for(i=0; i < 5; i++)
{
carDup = 0;
do{
cardRank[i] = (rand() % 13);
cardSuit[i] = (rand() % 4);
for (j=0; j < i; j++)
{
if ((cardRank[i] == cardRank[j] &&
cardSuit[i] == cardSuit[j]))
{
carDup = 1;
}
}
}while (carDup == 1;);
}
}
char getSuit(int suit)
{
switch
{
case 0:
return('C');
case 1:
return('D');
case 2:
return('H');
case 3:
return('S');
}
}
char getRank(int rank)
{
switch (rank)
{
case 0:
return('A');
case 1:
return('2');
case 2:
return('3');
case 3:
return('4');
case 4:
return('5');
case 5:
return('6');
case 6:
return('7');
case 7;
return('8');
case 8:
return('9');
case 9:
return('T');
case 10:
return('J');
case 11:
return('Q');
case 12:
return('K');
}
}
int getBet()
{
int bet;
do
{
printf("How much do you want to bet?(Enter a number");
printf("from 1 to 5, or 0 to quit the game): ");
scanf(" %d", &bet);
if (bet >= 1 && bet <= 5)
{
return(bet);
}
else if (bet == 0)
{
exit(1);
}
else
{
printf("\n\nPlease enter a bet from 1-5 or ");
printf("0 to quit the game\n\n");
}
}while ((bet < 0) || (bet > 5));
}
int analyzeHand(int ranksinHand[], int suitsinHand[])
{
int num_consec = 0;
int i, rank, suit;
int straight = FALSE;
int flush = FALSE;
int four = FALSE;
int three = FALSE;
int pairs = 0;
for (suit = 0; suit < 4; suit++)
if (suitsinHand[suit] == 5)
flush = TRUE;
rank = 0;
while (ranksinHand[rank] == 0)
rank++;
for (; rank < 13 && ranksinHand[rank]; rank++)
num_consec++;
if(num_consec == 5) {
straight = TRUE;
}
for (rank = 0; rank < 13; rank++){
if (ranksinHand[rank] == 4)
four == TRUE;
if (ranksinHand[rank] == 3)
three == TRUE;
if (ranksinHand[rank] == 2)
pairs++;
}
if (straight && flush){
printf("Straight Flush\n\n");
return(20);
}
else if (four){
printf("Four of a kind\n\n");
return (10);
}
else if (three && pairs == 1){
printf("Full House\n\n");
return (8);
}
else if (flush){
printf("Flush\n\n");
return (5);
}
else if (straight){
printf("Straight\n\n");
return (4);
}
else if (three){
printf("Three of a Kind\n\n");
return (3);
}
else if (pairs == 2){
printf("Two Pairs\n\n");
return (2);
}
else if (pairs == 1){
printf("Pair\n\n");
return (1);
}
else{
printf("High Card\n\n");
return (0);
}
}
void getFinalHand
(int cardRank[], int cardSuit[], int finalRank[], int finalSuit[], int
ranksinHand[], int suitsinHand[])
{
int i, j, carDup;
char suit, rank, ans;
for (i=0; i < 5; i++)
{
suit = getSuit(cardSuit[i]);
rank = getRank(cardRank[i]);
printf("Do you want to keep card #%d: %c%c", i+1, rank, suit);
printf("\nPlease answer (Y/N):");
scanf(" %c", &ans);
if (toupper(ans) == 'Y')
{
finalRank[i] = cardRank[i];
finalSuit[i] = cardSuit[i];
ranksinHand[finalRank[i]]++;
suitsinHand[finalSuit[i]]++;
continue;
}
else if (toupper(ans) == 'N')
{
carDup = 0;
do{
carDup = 0;
finalRank[i] = (rand() % 13);
finalSuit[i] = (rand() % 4);
for (j=0; j < 5; j++)
{
if((finalRank[i] == finalRank[j]) && (finalSuit[i] ==
finalSuit[j]))
{
carDup = 1;
}
}
for (j=0; j < i; j++)
{
if((finalRank[i] == finalRank[j]) && (finalSuit[i] ==
finalSuit[j]))
{
carDup = 1;
}
}
}while (carDup == 1);
ranksinHand[finalRank[i]]++;
suitsinHand[finalSuit[i]]++;
}
}
}
By convention main() must return an integer. You have to declare it like that:
int main()
{
// Your method
return 0;
}
int mainor
void main
would do the work. Here, int main is shown to be the C standard. Refer to
Return type of main() too.

Replacing elements in an array

I have a problem thats giving me a huge ache.
This piece of code purpose is to fill up an array with integer values and at the same time defend against strings and etc....but it doesn't defend against duplicates, but tried I got to far as replacing the number with a new number for example
Enter 6 integers
1, 2, 2, 3, 4, 5
my code will let me replace that 2 at position 1 with another number. What I want it to do is not to repeat the same number again, for example please replace 2 at position 1. I dont want the user to enter 2 again... and I want to make it to double check the work the array if any repeating numbers exists thank you.
system("clear");
printf("\nEntering Winning Tickets....\n");
nanosleep((struct timespec[]){{1, 0}}, NULL);
system("clear");
char userInput[256];
char c;
int duplicationArray[6] = {-1, -1, -1, -1, -1, -1};
for (i = 0; i < 6; i++)
{
printf("\nPlease enter the %d winning ticket number!(#'s must be between 1-49): ", i+1);
fgets(userInput, 256, stdin);
if ((sscanf(userInput, "%d %c", &winningNumbers[i], &c) != 1 || (winningNumbers[i] <= 0) || winningNumbers[i] >= 50))
{
printf("\nInvalid Input.\n") ;
nanosleep((struct timespec[]){{0, 350000000}}, NULL);
system("clear");
i = i - 1;
}
}
for (i = 0; i < 6 - 1; ++i)
{
min = i;
for (j = i+1; j < 6; ++j)
{
if (winningNumbers[j] < winningNumbers[min])
min = j;
}
temp = winningNumbers[i];
winningNumbers[i] = winningNumbers[min];
winningNumbers[min] = temp;
}
for (i = 0; i < 6; i++)
{
if (winningNumbers[i] == winningNumbers[i+1])
{
duplicationArray[i] = i;
duplicationCounter++;
}
else
{
duplicationCounter--;
}
}
if (duplicationCounter > -6)
{
for (i = 0; i < 6; i++)
{
int j, min, temp;
min = i;
for (j = i+1; j < 6; ++j)
{
if (duplicationArray[j] > duplicationArray[min])
min = j;
}
temp = duplicationArray[i];
duplicationArray[i] = duplicationArray[min];
duplicationArray[min] = temp;
}
for (i = 0; i < 6; i++)
{
if (duplicationArray[i] == -1)
{
zeroCounter++;
}
}
int resize = (6 - zeroCounter)+1;
for (i = 0; i <= resize; i++)
{
if (duplicationArray[i] == -1)
{
i++;
}
else if (duplicationArray[i] != -1)
{
system("clear");
printf("\nDuplicated numbers has been dected in your array. ");
printf("\nPlease replace the number %d at postion %d with another number: ", winningNumbers[duplicationArray[i]], duplicationArray[i]);
fgets(userInput, 256, stdin);
if ((sscanf(userInput, "%d %c", &winningNumbers[duplicationArray[i]], &c) != 1 || (winningNumbers[i] <= 0) || winningNumbers[i] >= 50))
{
printf("\nInvalid Input.\n") ;
nanosleep((struct timespec[]){{0, 350000000}}, NULL);
system("clear");
i = i - 1;
}
}
}
duplicationCounter = 0;
for (i = 0; i < 6; i++)
{
if (winningNumbers[i] == winningNumbers[i+1])
{
duplicationArray[i] = i;
duplicationCounter++;
}
else
{
duplicationCounter--;
}
}
printf("%d, ", duplicationCounter);
}
#include <stdio.h>
#include <stdint.h>
#define DATA_SIZE 6
int main(void){
char userInput[256];
int inputNum, winningNumbers[DATA_SIZE];
uint64_t table = 0;
int i=0;
while(i<DATA_SIZE){
printf("\nPlease enter the %d winning ticket number!(#'s must be between 1-49): ", i+1);
fgets(userInput, sizeof(userInput), stdin);
if(sscanf(userInput, "%d", &inputNum) != 1 || inputNum <= 0 || inputNum >= 50)
continue;
uint64_t bit = 1 << inputNum;
if(table & bit)
continue;
table |= bit;
winningNumbers[i++] = inputNum;
}
for(i=0;i<DATA_SIZE;++i)
printf("%d ", winningNumbers[i]);
printf("\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#define DATA_SIZE 6
int inputNumberWithRangeCheck(const char *msg, const char *errMsg, int rangeStart, int rangeEnd){
char inputLine[256];
int n;
for(;;){
printf("%s", msg);
fgets(inputLine, sizeof(inputLine), stdin);
if(sscanf(inputLine, "%d", &n) != 1 || n < rangeStart || n > rangeEnd)
fprintf(stderr, "%s", errMsg);
else
return n;
}
}
int inputNumber(void){
return inputNumberWithRangeCheck(
"\nPlease enter the winning ticket number!(#'s must be between 1-49): ",
"Invalid Input.\n",
1,49);
}
int *inputArray(int *array, size_t size){
int i;
for(i=0;i<size;++i){
printf("\nInput for No.%d\n", i+1);
array[i] = inputNumber();
}
return array;
}
int **duplicateCheck(int *array, size_t size){
int **check, count;
int i, j;
check = malloc(size*sizeof(int*));
if(!check){
perror("memory allocate\n");
exit(-1);
}
//There is no need to sort the case of a small amount of data
//(Cost of this loop because about bubble sort)
for(count=i=0;i<size -1;++i){
for(j=i+1;j<size;++j){
if(array[i] == array[j]){
check[count++] = &array[i];
break;
}
}
}
check[count] = NULL;
if(count)
return check;
else {
free(check);
return NULL;
}
}
int main(void){
int winningNumbers[DATA_SIZE];
int **duplication;
int i, j;
inputArray(winningNumbers, DATA_SIZE);
while(NULL!=(duplication = duplicateCheck(winningNumbers, DATA_SIZE))){
for(i=0;i<DATA_SIZE;++i){
if(duplication[i]){
printf("\nyour input numbers : ");
for(j=0;j<DATA_SIZE;++j)
printf("%d ", winningNumbers[j]);
fprintf(stderr, "\nThere is duplicate. Please re-enter.\n");
*duplication[i] = inputNumber();
} else
break;
}
free(duplication);
}
for(i=0;i<DATA_SIZE;++i)
printf("%d ", winningNumbers[i]);
printf("\n");
return 0;
}

Resources