Magic Number output - c++

Alright so I have created this code. However, when i run it, it stops when it displays 104 for the counter??? I am so frustrated because I don't know how this could happen. The purpose of the code is to do the typical magic number output where the rows all add up to the same thing, the columns all add up to the same thing, and the diaganols all add up to the same thing. I believe the functions to do these calculations are correct, but the counter keeps stopping short of the 10000 attempts I am trying to do.
#include <iostream>
#include<time.h>
#include<stdlib.h>
using namespace std;
void getrandom();
void insertnumber(int n);
bool magic();
void create();
const int rows = 3;
const int cols = 3;
int arr[rows][cols] = { {0,0,0}, {0,0,0} , {0,0,0} };
int main() {
int counter = 0;
do
{
counter++;
cout << counter << endl;
getrandom();
if (counter == 100000)
break;
} while (!magic());
create();
cout << "It took " << counter << " tries." << endl;
return 0;
}
void getrandom() {
int n = 0;
const int size = 9;
int oldnum[size];
for (int i = 0; i < rows * cols; i++) {
oldnum[i] = 0;
}
srand(time(NULL)); // had to import the new libraries to use this
bool used = true;
for (int i = 0; i < size; i++) {
do
{
used = true;
n = rand() % 9 + 1;
if (oldnum[n - 1] == 0)
{
oldnum[n - 1] = n;
used = false;
}
} while (used);
insertnumber(n);
}
}
void insertnumber(int n) {
for (int i = 0; i < rows; i++) {
for (int j = 0; i < cols; j++) {
if (arr[i][j] == 0) {
arr[i][j] = n;
return;
}
}
}
}
bool magic() {
int rowsum = arr[0][0] + arr[0][1] + arr[0][2];
for (int i = 1; i < cols; i++)
{
if (arr[i][0] + arr[i][1] + arr[i][2] != rowsum)
return false;
}
for (int j = 0; j < rows; j++)
{
if (arr[0][j] + arr[1][j] + arr[2][j] != rowsum)
return false;
}
if (arr[0][0] + arr[1][1] + arr[2][2] != rowsum)
return false;
if (arr[0][2] + arr[1][1] + arr[2][0] != rowsum)
return false;
return true;
}
void create() {
{
for (int i = 0; i < rows; i++) {
for (int j = 0; i < cols; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
}

You can try using a debugger for such problems.
I think you code crashes because of this:
for (int i = 0; i < rows; i++) {
for (int j = 0; i < cols; j++) {
It looks like you mean j < cols here :)

Check line 76. When I compile and run the code, line 76 is where the exception is thrown.
This line specifically
arr[i][j] = n;
It seems your insertnumber() function is the culprit.

Related

5 queens on 8x8 board using backtracking

#include <iostream>
#include <fstream>
using namespace std;
void PrintSolution(int board[8][8], ofstream& out, int& count)
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++) {
out << board[i][j] << " ";
}
out << endl;
}
out << endl;
count++;
}
int IsSafely(int board[][8], int row, int col)
{
for (int i = 0; i < row; i++)
{
if (board[i][col] == 1)
{
return 0;
}
}
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--)
{
if (board[i][j] == 1)
{
return 0;
}
}
for (int i = row, j = col; i >= 0 && j < 8; i--, j++)
{
if (board[i][j] == 1)
{
return 0;
}
}
return 1;
}
void FindSolution(int board[][8], int row, ofstream& out, int& count)
{
if (row == 8)
{
PrintSolution(board, out, count);
return;
}
for (int i = 0; i < 8; i++)
{
if (IsSafely(board, row, i))
{
board[row][i] = 1;
FindSolution(board, row + 1, out, count);
board[row][i] = 0;
}
}
}
void FillTheBoard(int board[][8])
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
board[i][j] = 0;
}
}
}
int main()
{
int board[8][8];
int count = 0;
ofstream output;
output.open("out.txt");
FillTheBoard(board);
FindSolution(board, 0, output, count);
output << count << endl;
output.close();
}
Hello everyone, I have a program that counts the number of arrangements of 8 queens on an 8x8 chessboard. I need to make a program to count the number of arrangements for 5 queens on an 8x8 board. Could you help me? What can I change in my program? For 8 queens, the program works correctly, it gives 92 solutions. For 5 queens, there should be 728 solutions on the 8x8 board.

segment fault in recursion, when trying to backtrack during sudoku solver algorithm in c++

I did the same question a while ago, but It got closed. I'll try to express myself better this time.
I want to make an algorithm that can solve a sudoku puzzle, looks like It is working, but in the backtracking part(where I need to go back to a previous recursion to test a different value), It doesn't, showing a "segment fault" error.
Also, I use "0" as a blank space, so that's why "if (!board[i][j]) //do something"
// Solves the game
vector<vector<int>> sudokuSolver(vector<vector<int>> board) {
if (isFull(board)) {
return board;
}
bool found = false;
int line = 0;
int col = 0;
for (int i = 0; i <= 8; i++) {
for (int j = 0; j <= 8; j++) {
if (!board[i][j]) {
line = i;
col = j;
found = true;
break;
}
}
if (found) break;
}
vector<int> possibleNumbers = possibilities(board, line, col);
cout << '\n';
printBoard(board);
cout << '\n';
cout << line << ' ' << col << '\n';
cout << '\n';
printVector(possibleNumbers);
int size = possibleNumbers.size();
for (int k = 0; k < size; k++) {
board[line][col] = possibleNumbers[k];
cout << k << '\n';
sudokuSolver(board);
// the code doesn't pass to the next cout. Why?
cout << "it doesn't reach here :/" << '\n';
}
cout << "backtracking!!" << '\n';
board[line][col] = 0;
cout << "agora:" << '\n';
printBoard(board);
}
I put some "couts" to help me visualize the problem. The "backtracking!!" cout is working properly, but the "it doesn't reach here" cout is not. I thought that, after the code realize It doesn't have possible solutions, It would simply go back to the last recursion, but It's not, giving "segmento fault" error. I don't understand
for (int k = 0; k < size; k++) {
board[line][col] = possibleNumbers[k];
cout << k << '\n';
sudokuSolver(board);
// the code doesn't pass to the next cout. Why?
cout << "it doesn't reach here :/" << '\n';
}
Am I not getting something?
Also, if It's not clear, "isFull" checks if the board is full (base case, game is complete), and possibilities checks the number possibilities of a single cell
Thanks in advance. I guess the details are way better this time, hope I did It right
Edit: The extra couts are ways of showing me where the code is. They are not important for the algorithm itself
Final edit: I did it! Thanks you all. For anyone who wants the full code, here it is:
#include <bits/stdc++.h>
using namespace std;
bool gameRunning = true;
void printBoard(vector<vector<int>> board) {
for (int i = 0; i <= 8; i++) {
for (int j = 0; j <= 8; j++) {
cout << board[i][j] << ' ';
}
cout << '\n';
}
cout << '\n';
}
void printVector(vector<int> v) {
for (auto x : v) {
cout << x << ' ';
}
cout << '\n';
cout << '\n';
}
// Checks if the board is full, deciding if the game is already won
bool isFull(vector<vector<int>> board) {
for (int i = 0; i <= 8; i++) {
for (int j = 0; j <= 8; j++) {
if (!board[i][j]) return false;
}
}
return true;
}
// Generates all number possibilites for a given cell on the board
vector<int> possibilities(vector<vector<int>> board, int i, int j) {
bitset<9> p;
for (int i = 1; i <= 9; i++) {
p[i] = 1;
}
//horizontal check
for (int col = 0; col <= 8; col++) {
if (board[i][col]) {
p[board[i][col]] = 0;
}
}
//vertical check
for (int line = 0; line <= 8; line++) {
if (board[line][j]) {
p[board[line][j]] = 0;
}
}
//mini-square check
int linesquare = (i / 3) * 3;
int colsquare = (j / 3) * 3;
for (int l = linesquare; l <= linesquare + 2; l++) {
for (int c = colsquare; c <= colsquare + 2; c++) {
if (board[l][c]) {
p[board[l][c]] = 0;
}
}
}
vector<int> numberPossibilities;
for (int k = 1; k <= 9; k++) {
if (p[k]) numberPossibilities.push_back(k);
}
return numberPossibilities;
}
// Solves the game
void sudokuSolver(vector<vector<int>> board) {
if (isFull(board)) {
printBoard(board);
gameRunning = false;
}
if (gameRunning) {
bool found = false;
int line = 0;
int col = 0;
for (int i = 0; i <= 8; i++) {
for (int j = 0; j <= 8; j++) {
if (!board[i][j]) {
line = i;
col = j;
found = true;
break;
}
}
if (found) break;
}
vector<int> possibleNumbers = possibilities(board, line, col);
int size = possibleNumbers.size();
for (int k = 0; k < size; k++) {
board[line][col] = possibleNumbers[k];
sudokuSolver(board);
}
board[line][col] = 0;
}
}
int main() {
/*
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
*/
vector<vector<int>> v;
for (int i = 0; i < 9; i++) {
vector<int> hold;
for (int j = 0; j < 9; j++) {
int a;
cin >> a;
hold.push_back(a);
}
v.push_back(hold);
}
cout << '\n';
sudokuSolver(v);
return 0;
}
Bye, have a great day

Vector subscription out of range error c++

I am trying to create a simulation of conway's game of life.
I keep getting a "vector subscript out of range" error after about 300 generation and I don't understand the reason. From what I could gather it's caused by using an invalid index. The most likely section is the first part of the draw function where I find empty rows and replace them with "\n" to save time.
I've started learning to code not too long ago so I may be making baby mistakes.
Edit: visual studio point the error after the third for loop in the frame function, on if (emptyRows[m] == i)
Here's the full code :
#include <array>
#include <time.h>
#include <vector>
const int WIDTH = 150;
const int HEIGHT = 50;
bool table[WIDTH][HEIGHT];
bool tableNew[WIDTH][HEIGHT];
std::string buffer;
int total;
int counter = 0;
std::vector<int> emptyRows;
int numberOfNeighbours(int Y, int X) {
if (X == 0 || Y == 0 || X == WIDTH || Y == HEIGHT)
return 2;
total = 0;
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
if (table[X + j][Y + i] == true)
total++;
}
}
total -= table[X][Y];
return total;
}
void draw() {
srand((int)time(0));
int m = 0;
bool check = 0;
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (table[j][i] == 1)
check = 1;
}
if (check == 0)
emptyRows.push_back(i);
else
check = 0;
}
for (int i = 0; i < HEIGHT; i++) {
if (emptyRows.size() >= 1) {
if (emptyRows[m] == i) {
buffer.append("\n");
m++;
continue;
}
}
for (int j = 0; j < WIDTH; j++) {
if (table[j][i] == 1) buffer.push_back('#');
else buffer.push_back(' ');
}
buffer.append("\n");
}
std::cout << buffer;
std::cout << std::endl << "Generazione numero:" << counter;
emptyRows.erase(emptyRows.begin(), emptyRows.end());
buffer.erase(buffer.begin(), buffer.end());
m = 0;
}
void reset() {
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
table[j][i] = tableNew[j][i];
}
}
}
void logic() {
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
int k = numberOfNeighbours(i, j);
if (table[j][i] == 0 && k == 3)
tableNew[j][i] = 1;
else if (table[j][i] == 1 && k != 2 && k != 3)
tableNew[j][i] = 0;
else
tableNew[j][i] = table[j][i];
}
}
}
int main(){
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if ((rand() % 2) == 1)
table[j][i] = 1;
}
}
while (true) {
counter++;
draw();
logic();
reset();
system("cls");
}
return 0;
}

Not receiving input from user for 3x3 sliding tile slide

I'm trying to create a 3x3 sliding tile puzzle game and I made the puzzle in a 2d array and now im trying to get the puzzle to slide a tile.
I'm new to debugging and cannot find out why the program isn't receiving the users input for the slide.
#define SLIDE_UP 1
#define SLIDE_DOWN 2
#define SLIDE_LEFT 3
#define SLIDE_RIGHT 4
void InitializeBoard(int[NUM_ROWS][NUM_COLS]);
void PrintBoard(int[NUM_ROWS][NUM_COLS]);
bool slideTile(int[NUM_ROWS][NUM_COLS], int);
void scrambleBoard(int[NUM_ROWS][NUM_COLS]);
bool isBoardSolved(int[NUM_ROWS][NUM_COLS]);
void DeallocateMemory(int[NUM_ROWS][NUM_COLS]);
int** ppRootPointer = NULL;
int main() {
int slidingBoard[NUM_ROWS][NUM_COLS];
char keyStroke = ' ';
int directionCode = UNSET;
int slideDirection = 0;
InitializeBoard(slidingBoard);
PrintBoard(slidingBoard);
slideTile(slidingBoard,slideDirection);
PrintBoard(slidingBoard);
_getch();
DeallocateMemory(slidingBoard);
return 0;
}
void InitializeBoard(int theBoard[NUM_ROWS][NUM_COLS]) {
ppRootPointer = new(int*[NUM_COLS]);
for (int i = 0; i < NUM_COLS; i++) {
ppRootPointer[i] = new(int[NUM_ROWS]);
}
int counter = 1;
int i = 0, j = 0;
for (i = 0; i < NUM_COLS; i++) {
for (j = 0; j < NUM_ROWS; j++) {
ppRootPointer[i][j] = counter++;
}
}
ppRootPointer[i-1][j-1] = PIVOT;
}
void PrintBoard(int theBoard[NUM_ROWS][NUM_COLS]) {
cout << left;
for (int i = 0; i < NUM_COLS; i++) {
for (int j = 0; j < NUM_ROWS; j++) {
if (ppRootPointer[i][j] != PIVOT) {
cout << setw(3) << ppRootPointer[i][j];
}
else {
cout << setw(3) << (char)PIVOT;
}
}
cout << endl;
}
cout << endl << endl;
}
bool slideTile(int theBoard[NUM_ROWS][NUM_COLS], int slideDirection) {
int pivotRow=0;
int pivotCol=0;
bool slidebool;
//once I declare i and j before the loop they go up to 3 instead of 2
//which causes the loop to not work
int i = 0;
int j = 0;
for (i = 0; i < NUM_COLS; i++) {
for (j = 0; j < NUM_ROWS; j++) {
if (theBoard[i][j] == (char)PIVOT) {
pivotCol = i;
pivotRow = j;
break;
}
}
}
//These are to assign pivotRow and Col because they dont get assigned
//inside of the loop
pivotCol = i;
pivotRow = j;
cout << "please enter a number to slide the tile (1 = up, 2 = down, 3 =
left, 4 = right" << endl;
cin >> slideDirection;
if (slideDirection == SLIDE_UP) {
if (pivotRow + 1 > NUM_ROWS) {
slidebool = false;
}
else {
ppRootPointer[pivotRow + 1][pivotCol] = PIVOT;
ppRootPointer[pivotRow][pivotCol] = ppRootPointer[pivotRow + 1]
[pivotCol];
slidebool = true;
}
}
.I'm hoping for the user to be able to enter an integer 1-4 representing the slide for the tile. This would allow me to build the scramble board function and get closer to finishing the code. Thanks to anyone that reads this and tries to help!!

Shouldn't this recursive method end as soon as you get to the return?

I would like to know why my output is:
a-b-b-b-b-0
When I think it should just be a-1.
Shouldn't a recursive method end as soon as you get to a return? and why doesn't it here?
I only put the letters with '-' to clarify that the returns are being met but not stopping there.
#include <stdio.h>
#include <iomanip>
#include <iostream>
using namespace std;
void printv(int mask[], int elements[], int n)
{
int i;
printf("{ ");
for (i = 0; i < n; i++)
if (mask[i])
printf("%d ", elements[i]);
printf("}");
}
int next(int mask[], int size)
{
int i;
for (i = 0; (i < size) && mask[i]; i++)
mask[i] = 0;
if (i < size) {
mask[i] = 1;
return 1;
}
return 0;
}
void nSubsets(int mask[], int elements[], int size, int n)
{
int sum = 0;
int temp[10], count = 0;
for (int i = 0; i < 10; i++) //this MUST be here
temp[i] = 0;
for (int i = 0; i < size; i++)
{
if (mask[i])
{
count++;
for (int k = 0; k < 44; k++)
if (temp[k] == 0)
{
temp[k] = elements[i];
sum += elements[i];
break;
}
}
}
if (sum == n)
{
cout << "{ ";
for (int l = 0; l < count; l++)
cout << temp[l] << " ";
cout << "}";
}
}
int isEmptySet(int mask[], int elements[], int size, int n, int sizeRecursion)
{
int sum = 0;
int temp[10], count = 0;
for (int i = 0; i < 10; i++) //this MUST be here
temp[i] = 0;
for (int i = 0; i < size; i++)
{
if (mask[i])
{
count++;
for (int k = 0; k < 44; k++)
if (temp[k] == 0)
{
temp[k] = elements[i];
sum += elements[i];
break;
}
}
}
if (sum == n)
{
cout << "a-";
return 1;
}
sizeRecursion--;
if (sizeRecursion > 0)
{
next(mask, size);
isEmptySet(mask, elements, size, n, sizeRecursion);
}
cout << "b-";
return 0;
}
int main()
{
int n, size = 10;
int elements[size];
size = 6; n = 5;
elements[0] = 5;
elements[1] = 2;
elements[2] = 3;
elements[3] = 2;
elements[4] = 1;
elements[5] = 1;
int mask[10];
int i;
for (i = 0; i < size; ++i)
mask[i] = 0;
cout << "Subsets of elements: ";
printv(mask, elements, size); //this prints first subset
while (next(mask, size))
printv(mask, elements, size);
n = 3;
cout << "\nSubsets equal to " << n << "\n";
while (next(mask, size))
nSubsets(mask, elements, size, n);
cout << "\n" << isEmptySet(mask, elements, size, n, size);
return 0;
}
Shouldn't a recursive method end as soon as you get to a return? and why doesn't it here?
No, the way it works in general is that when a function call returns, it only returns for that function call, and then the immediate caller may continue execution. It doesn't matter whether the function is recursive or not, each function call is separate and each call needs to hit a return statement at some point (unless the return type is void).
When you have this code
...
if(sizeRecursion > 0)
{
next(mask,size);
isEmptySet(mask, elements, size, n,sizeRecursion);
}
cout<<"b-";
return 0;
}
What's going to happen is, as soon as the recursive call to isEmptySet returns, its going to go right to the cout << "b-"; line and then to return 0;. If you don't want that then you should put those in an else block, and maybe also modify the line that calls isEmptySet so that it returns the value returned from that call.