8 queens puzzle: using random numbers causes infinite loop - c

When executing this code, my terminal hangs most of the time, but every once in a while I get the solution I want printed out. I know this is not the best way to solve the queens puzzle, so please don't comment on that. Thank you to anyone that takes the time to help.
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int check(int number, int arr[]){
int num = 0;
int i;
for(i = 0; i < 8; i++){
if(arr[i] == number)
num = 1;
}
return num;
}
int main(int argc, char * argv[]){
srand(time(NULL));
int r, r2, i, v;
char arr[8][8];
int sum[8] = {0};
int sum2[8] = {0};
int row[8];
int col[8];
int cRow[8];
int cCol[8];
int count = 0;
int sums = 0;
int sums2 = 0;
//Fill arrays and 2d array.
for(i = 0; i < 8; i++){
row[i] = 0;
col[i] = 0;
cRow[i] = 0;
cCol[i] = 0;
for(v = 0; v < 8; v++){
arr[i][v] = '_';
}
}
for(v = 0; v < 8; v++){
sum[v] = 0;
sum2[v] = 0;
printf("%d", sum[v]);
}
//Loop ends when 8 queens have been drawn
while(count < 8){
r = rand() % 8;
r2 = rand() % 8;
sums = r + r2;
sums2 = r2 - r;
/*If space on board is empty. If row and col value have not been used.
Once a value of both row and col that have not been used has been reached
by random, mark that value between 0-7 as used.*/
if((row[r] == 0) && (col[r2] == 0) && (check(sums, sum)==0)&& (check(sums2, sum2)==0)){
sum[count] = sums;
sum2[count] = sums2;
row[r] = 1;
col[r2] = 1;
/*These two are used to store coordinate values in 2 arrays to be written later.*/
cRow[count] = r;
cCol[count] = r2;
count++;
printf("\n%d\n", r);
printf("%d\n", r2);
printf("%d\n\n", sums);
for(v = 0; v < 8; v++){
//sum[v] = 0;
printf("%d", sum[v]);
}
}
}
//Print the coordinate values.
printf("\n");
for(v = 0;v<8;v++)
printf("%d ", cRow[v]);
printf("\n");
for(v = 0;v<8;v++)
printf("%d ", cCol[v]);
printf("\n");
//Write the coordinate values.
for(i = 0; i < 8; i++){
arr[cRow[i]][cCol[i]] = 'Q';
}
//Print 2d array
for(i = 0; i < 8; i++){
for(v = 0; v < 8; v++){
printf("%c ", arr[i][v]);
}
printf("\n");
}
return 0;
}

The infinite loop problem is because your program cannot "backtrack" if it ever gets to a point where it is not possible to legally place any more queens. At that point, it just loops forever futilely picking spots that won't work. Instead, to break out of this, it needs to "unplace" something it has placed already. (Thus, you will need to explicitly detect when there are no more legal spots remaining in a column, row or diagonal.)

Related

Selection sort not sorting

just testing out sorting methods and I've come across selection sort. I've understood the logic behind the selection sort but I don't get the desired result i wish to see from this program. It doesn't seem to sort at all. Could someone tell me where i went wrong.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int StudentCreation(int StudentRecordArray[10]){
for(int i = 0; i < 10; i++){
StudentRecordArray[i] = rand() % 100; //limiting the marks range from 0 - 100
}
}
int SelectionSort(int SelectionSortarray[]) {
int n = 0;
int tmp = 0;
for(int j = 0; j < 10-1; j++){
int TempMinimum = j;
for(int i = j+1; i < n; i++)
if(SelectionSortarray[i] < SelectionSortarray[TempMinimum])
TempMinimum = i;
if(TempMinimum != j){
tmp = SelectionSortarray[j];
SelectionSortarray[j] = SelectionSortarray[TempMinimum];
SelectionSortarray[TempMinimum] = tmp;
}
}
for (int f = 0; f < 10; f++){
printf("Student %d - %d\n", f+1, SelectionSortarray[f]);
}
}
int main() {
int StudentRecord[10];
int MenuChoice;
srand(time(NULL)); //random number seed generator
StudentCreation(StudentRecord);
printf("the unsorted list:\n");
for (int f = 0; f < 10; f++){
printf("Student %d - %d\n", f+1, StudentRecord[f]);
}
printf("\nthe sorted list:\n\n");
SelectionSort(StudentRecord);
return 0;
}
Is it something wrong with where i have swapped?
There is a typo in the sorting function.
Instead of
int n = 0;
there should be
int n = 10;

Explain Fibonacci code

#include<stdio.h>
#define max 2000
int arr1[max], arr2[max], arr3[max];
void fib();
int main()
{
int num, i, j, flag = 0;
for(i = 0; i<max; i++)
arr1[i] = arr2[i] = arr3[i] = 0;
arr2[max - 1] = 1;
printf("Enter the term : ");
scanf("%d", &num);
for(i = 0; i<num; i++)
{
fib();
if(i == num - 3)
break;
for(j = 0; j<max; j++)
arr1[j] = arr2[j];
for(j = 0; j<max; j++)
arr2[j] = arr3[j];
}
for(i = 0; i<max; i++)
{
if(flag || arr3[i])
{
flag = 1;
printf("%d", arr3[i]);
}
}
getch();
return 1;
}
void fib()
{
int i, temp;
for(i = 0; i<max; i++)
arr3[i] = arr1[i] + arr2[i];
for(i = max - 1; i>0; i--)
{
if(arr3[i]>9)
{
temp = arr3[i];
arr3[i] %= 10;
arr3[i - 1] += (temp / 10);
}
}
}
The above code generates the nth Fibonacci number. I am not able to understand how this works. Basically the Fibonacci number get stored in a very large array arr3[].
Please explain the logic involved in this code.
How does the fib() function work as well?
Here is a simple Fibonacci loop.
#include <stdio.h>
int main()
{
int term = 20, last2=0, last1=1, fib, i;
for (i=0; i<term; i++) {
fib = last2 + last1;
last2 = last1;
last1 = fib;
}
printf ("Term %d = %d\n", i, fib);
return 0;
}
Program output:
Term 20 = 10946
Although there is more than one idea as to where the sequence starts.
The example code in the original post is dealing with large numbers by storing 1 decimal digit per element in each of the arrays. It initializes arr[3] = arr2[] = arr1[] = 0, then arr2[] = 1. In the loop, fib() performs one instance of arr3[] = arr1[] + arr2[], handling the carries, then the loop does arr[1] = arr2[], arr2[] = arr3[]. If num < 3, the for loop exits on the loop condition i < num, if n >= 3, the loop exit when i == (num-3). (This could be avoided). The print loop skips leading zeroes in arr3[], setting flag once a non-zero value is found. The code needs some minor fixes. Here is a fixed example. Note that getch() may be _getch() in some environments (from conio.h). The second example below only uses two arrays. Fibonacci numbers starting from 0 are 0 1 1 2 3 5 8 ...
#include <conio.h>
#include <stdio.h>
#define max 2000
int arr1[max], arr2[max], arr3[max];
void fib();
int main()
{
int num, i, j;
for(i = 0; i<max; i++)
arr1[i] = arr2[i] = arr3[i] = 0;
arr1[max - 1] = 1;
printf("Enter the term : ");
scanf("%d", &num);
for(i = 0; i<num; i++)
{
fib();
for(j = 0; j<max; j++)
arr1[j] = arr2[j];
for(j = 0; j<max; j++)
arr2[j] = arr3[j];
}
for(i = 0; i < max-1; i++)
if(arr3[i])
break;
for( ; i < max; i++)
printf("%d", arr3[i]);
getch();
return 0;
}
void fib()
{
int i, temp;
for(i = 0; i<max; i++)
arr3[i] = arr1[i] + arr2[i];
for(i = max - 1; i>0; i--)
{
if(arr3[i]>9)
{
temp = arr3[i];
arr3[i] %= 10;
arr3[i - 1] += (temp / 10);
}
}
}
This example only uses two arrays, by alternating which array contains the sum (a1 += a0, a0 += a1). It uses Duff's device to enter the loop. Since the largest sum from digit + digit + carry is < 20, the carry loop in fib() was simplified.
#include <conio.h>
#include <stdio.h>
#define max 2000
void fib(unsigned char *a0, unsigned char *a1);
int main()
{
unsigned char a0[max], a1[max];
size_t i;
int n;
printf("Enter the term : ");
scanf("%d", &n);
for(i = 0; i < max; i++)
a0[i] = a1[i] = 0;
a0[max-1] = n & 1; /* if n even, a0=0=fib(0), a1=1=fib(-1) */
a1[max-1] = 1 - a0[max-1]; /* if n odd, a1=0=fib(0), a0=1=fib(-1) */
switch(n&1){
do{
fib(a0, a1);
case 1:
fib(a1, a0);
case 0:
continue;
}while(0 <= (n -= 2));
}
for(i = 0; i < max-1; i++)
if(a0[i])break;
for( ; i < max; i++)
printf("%d", a0[i]);
getch();
return 0;
}
void fib(unsigned char *a0, unsigned char *a1)
{
size_t i;
for(i = 0; i < max; i++)
a1[i] += a0[i];
for(i = max - 1; i > 0; i--){
if(a1[i] >= 10){
a1[i] -= 10;
a1[i-1] += 1;
}
}
}
Here's a much better implementation of the Fibonacci series
#include<iostream>
using namespace std;
main()
{
int n, c, first = 0, second = 1, next;
cout << "Enter the number of terms of Fibonacci series you want" << endl;
cin >> n;
cout << "First " << n << " terms of Fibonacci series are :- " << endl;
for ( c = 0 ; c < n ; c++ )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
cout << next << endl;
}
return 0;
}

C programming with functions

I have got some more problems with the code. This program ask the user to specify the nr of throws then it throws 3 dices and add these 3 dices to sum.
Then another function sorts the sum form the smallest to the largest with a bubble sorting algorithm.
the first two functions seems to work but the program does not print out the result of the 3rd sorting function.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 100
//This function ask the user for the amout of throws
int numberofthrows() {
int throws
printf("Type in the number of throws");
scanf("%d", &throws);
return throws;
}
//This function makes the random throws of 3 dices with regard to the number of throws
int filler(int thrownr, int dice1[MAX], int dice2[MAX], int dice3[MAX], int sum[MAX]) {
int i, nr;
srand(time(NULL));
for(i = 0; i <= thrownr; i++) {
nr = rand()%6;
dice1[i] = nr + 1;
nr = rand()%6;
dice2[i] = nr + 1;
nr = rand()%6;
dice3[i] = nr + 1;
sum[i] = dice1[i] + dice2[i] + dice3[i];
}
int j;
for(j = 0; j <= thrownr; j++) {
printf("%d ", dice1[j]);
printf("%d ", dice2[j]);
printf("%d ", dice3[j]);
printf("%d\n", sum[j]);
}
}
//This function sorts the result in form the sum array
int sorter(int thrownr, int sum[MAX], int sortsum[MAX]) {
int tmp, i, j, k, m;
for(i = 0; i <= thrownr; i++) {
sortsum[i] = sum[i];
}
for(m = 0; m <= 10; m++) {
for(j = 0; j <= thrownr; i++) {
if (sortsum[j] > sortsum[j+1]) {
tmp = sortsum[j];
sortsum[j] = sortsum[j+1];
sortsum[j+1] = tmp;
}
}
}
for(k = 0; k <= thrownr; k++) {
printf("%d\n", sortsum[k]);
printf("%d\n", sum[k]);
}
}
int main(void) {
srand(time(NULL));
int dice1[MAX];
int dice2[MAX];
int dice3[MAX];
int sum[MAX];
int sortsum[MAX];
int numberofthrows2;
numberofthrows2 = numberofthrows();
filler(numberofthrows2, dice1, dice2, dice3, sum);
sorter(numberofthrows2, sum, sortsum);
return 0;
}
The code for sorting is a bit wrong. Change
for(m = 0; m <= 10; m++)
To
for(m = 0; m <= thrownr-1; m++)
And
for(j = 0; j <= thrownr; i++)
To
for(j = 0; j < thrownr-m-1; i++)
To fix it. Also, call srand once at the start of main. Don't call it more than once in a program or you might get the same "random" numbers everytime you run your program.

how to generate number pattern in triangular form [duplicate]

I want to print this pattern like right angled triangle
0
909
89098
7890987
678909876
56789098765
4567890987654
345678909876543
23456789098765432
1234567890987654321
I wrote the following code:
#include <stdio.h>
#include <conio.h>
void main()
{
clrscr();
int i,j,x,z,k,f=1;
for ( i=10;i>=1;i--,f++)
{
for(j=1;j<=f;j++,k--)
{
k=i;
if(k!=10)
{
printf("%d",k);
}
if(k==10)
{
printf("0");
}
}
for(x=1;x<f;x++,z--)
{
z=9;
printf("%d",z);
}
printf("%d/n");
}
getch();
}
What is wrong with this code? When I check manually it seems correct but when compiled gives different pattern
Fairly simple: use two loops, one for counting up and one for counting down. Print literal "0" between the two.
#include <stdio.h>
int main()
{
for (int i = 0; i < 10; i++) {
for (int j = 10 - i; j < 10; j++)
printf("%d", j);
printf("0");
for (int j = 9; j >= 10 - i; j--)
printf("%d", j);
printf("\n");
}
return 0;
}
Like H2CO3's, but since we're only printing single digits why not use putchar():
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i, j;
for(i = 0; i < 10; ++i)
{
// Left half.
for(j = 0; j < i; ++j)
putchar('9' - i + j + 1);
// Center zero.
putchar('0');
// Right half.
for(j = 0; j < i; ++j)
putchar('9' - i + j + 1);
putchar('\n');
}
return EXIT_SUCCESS;
}
Modified Code:
Check your errors:
# include<stdio.h>
# include<conio.h>
int main()
{
// clrscr();
int i,j,x,z,k,f=1;
for ( i=10;i>=1;i--,f++)
{
k=i; // K=i should be outside of loop.
for(j=1;j<=f;j++,k++)
{
if(k!=10)
{
printf("%d",k);
}
if(k==10)
{
printf("0");
}
}
z=9; //z=9 should be outside loop.
for(x=1;x<f;x++,z--)
{
printf("%d",z);
}
printf("\n");
}
//getch();
return 0;
}
You are defining k=i inside the for loop(loop which has j) so every time k gets value of i and thus it always get value of i and prints that value and your another condition(if(k==10)) will never be true because every time k takes value of i and i is less than 10 after first iteration of loop and z=9 inside loop so every time loop is executed it is taking value z=9 so it is printing wrong value.
Here's a C# version:
static void DrawNumberTriangle()
{
for (int line = 10; line >=1; line--)
{
for (int number = line; number < 10; number++)
{
System.Console.Write(number);
}
System.Console.Write("0");
for (int number = 9; number > line - 1; number--)
{
System.Console.Write(number);
}
System.Console.WriteLine();
}
}
I'd suggest renaming your i,j,x,z,k,f variables to ones that have meaning like the one's I used. This helps making your code easier to follow.
Rather than output the mid 0 using printf, why not print it using the loops itself.
The following short and simple code can be used:
int main()
{
int m = 10, n, p;
while(m >= 1)
{
for(n = m; n <= 10; n++)
printf("%d", n % 10);
for(p = n - 2; p >= m; p--)
printf("%d", p );
printf("\n");
m--;
}
return 1;
}
For high throughput (though of questionable merit in terms of clarity):
#include <stdio.h>
int main() {
char const digits[] = "1234567890";
char const rdigits[] = "9876543210";
for (int i = 0; i < 30; ++i) {
int k = i % 10;
fputs(digits + 9 - k, stdout);
for (int j = 9; j < i; j += 10) fputs(digits, stdout);
for (int j = 9; j < i; j += 10) fputs(rdigits, stdout);
fwrite(rdigits, 1, k, stdout);
fputs("\n", stdout);
}
}
#include <stdio.h>
void print(int i){
if(i == 10){
putchar('0');
return ;
} else {
printf("%d", i);
print(i+1);
printf("%d", i);
}
}
int main(void){
int i;
for(i = 10; i>0; --i){
print(i);
putchar('\n');
}
return 0;
}

How do I generate number pattern in triangular form

I want to print this pattern like right angled triangle
0
909
89098
7890987
678909876
56789098765
4567890987654
345678909876543
23456789098765432
1234567890987654321
I wrote the following code:
#include <stdio.h>
#include <conio.h>
void main()
{
clrscr();
int i,j,x,z,k,f=1;
for ( i=10;i>=1;i--,f++)
{
for(j=1;j<=f;j++,k--)
{
k=i;
if(k!=10)
{
printf("%d",k);
}
if(k==10)
{
printf("0");
}
}
for(x=1;x<f;x++,z--)
{
z=9;
printf("%d",z);
}
printf("%d/n");
}
getch();
}
What is wrong with this code? When I check manually it seems correct but when compiled gives different pattern
Fairly simple: use two loops, one for counting up and one for counting down. Print literal "0" between the two.
#include <stdio.h>
int main()
{
for (int i = 0; i < 10; i++) {
for (int j = 10 - i; j < 10; j++)
printf("%d", j);
printf("0");
for (int j = 9; j >= 10 - i; j--)
printf("%d", j);
printf("\n");
}
return 0;
}
Like H2CO3's, but since we're only printing single digits why not use putchar():
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i, j;
for(i = 0; i < 10; ++i)
{
// Left half.
for(j = 0; j < i; ++j)
putchar('9' - i + j + 1);
// Center zero.
putchar('0');
// Right half.
for(j = 0; j < i; ++j)
putchar('9' - i + j + 1);
putchar('\n');
}
return EXIT_SUCCESS;
}
Modified Code:
Check your errors:
# include<stdio.h>
# include<conio.h>
int main()
{
// clrscr();
int i,j,x,z,k,f=1;
for ( i=10;i>=1;i--,f++)
{
k=i; // K=i should be outside of loop.
for(j=1;j<=f;j++,k++)
{
if(k!=10)
{
printf("%d",k);
}
if(k==10)
{
printf("0");
}
}
z=9; //z=9 should be outside loop.
for(x=1;x<f;x++,z--)
{
printf("%d",z);
}
printf("\n");
}
//getch();
return 0;
}
You are defining k=i inside the for loop(loop which has j) so every time k gets value of i and thus it always get value of i and prints that value and your another condition(if(k==10)) will never be true because every time k takes value of i and i is less than 10 after first iteration of loop and z=9 inside loop so every time loop is executed it is taking value z=9 so it is printing wrong value.
Here's a C# version:
static void DrawNumberTriangle()
{
for (int line = 10; line >=1; line--)
{
for (int number = line; number < 10; number++)
{
System.Console.Write(number);
}
System.Console.Write("0");
for (int number = 9; number > line - 1; number--)
{
System.Console.Write(number);
}
System.Console.WriteLine();
}
}
I'd suggest renaming your i,j,x,z,k,f variables to ones that have meaning like the one's I used. This helps making your code easier to follow.
Rather than output the mid 0 using printf, why not print it using the loops itself.
The following short and simple code can be used:
int main()
{
int m = 10, n, p;
while(m >= 1)
{
for(n = m; n <= 10; n++)
printf("%d", n % 10);
for(p = n - 2; p >= m; p--)
printf("%d", p );
printf("\n");
m--;
}
return 1;
}
For high throughput (though of questionable merit in terms of clarity):
#include <stdio.h>
int main() {
char const digits[] = "1234567890";
char const rdigits[] = "9876543210";
for (int i = 0; i < 30; ++i) {
int k = i % 10;
fputs(digits + 9 - k, stdout);
for (int j = 9; j < i; j += 10) fputs(digits, stdout);
for (int j = 9; j < i; j += 10) fputs(rdigits, stdout);
fwrite(rdigits, 1, k, stdout);
fputs("\n", stdout);
}
}
#include <stdio.h>
void print(int i){
if(i == 10){
putchar('0');
return ;
} else {
printf("%d", i);
print(i+1);
printf("%d", i);
}
}
int main(void){
int i;
for(i = 10; i>0; --i){
print(i);
putchar('\n');
}
return 0;
}

Resources