The user is supposed to input a number between 0 and 81, and it should generate a sudoku board with that many (valid) numbers filled in (Even if the sudoku board may not be solvable).
It works fine for small numbers of n, but if it has to backtrack, it gets stuck oscillating between ~42 and ~56.
In this program, it's important to note that n is the number that the user has specified, nOn is the number the function is on.
the array named positions[] contains the numbers 0-80 in a randomized order (compliments of the shuffle function) and is designed to represent the randomized order in which to fill the grid.
bool Sudoku::generateSudoku(int n, int nOn)
{
int xpos = positions[nOn] / 9;
int ypos = positions[nOn] % 9;
int queryCount = 0;
char query = rand()%9 + '1';
bool success = false;
if (nOn >= n)
{
return true;
}
else
{
while (queryCount < 9 && !success)
{
if (isValid(xpos, ypos, query, 0))
{
sudoku[xpos][ypos][0] = query;
success = generateSudoku(n, nOn + 1);
}
if (query == '9')
{
query = '1';
}
else
{
query++;
}
queryCount++;
}
if (!success)
{
sudoku[xpos][ypos][0] = '*';
return false;
}
else
{
return true;
}
}
}
I've gone over it several times with 2 of my friends and I can't find why it's getting choked up. Any help would be appreciated!
edit: I've added a similar function that I know works for comparison. This one starts in the upper left hand corner and recursively backtracks when it runs into invalid solutions. it's able to solve any (solvable) puzzle in a matter of seconds
int Sudoku::solveSudoku(int x, int y)
{
bool success = false;
char query = '1';
int counter = 0;
if (x == 8 && y == 9)
{
return 1;
}
else if (y == 9)
{
y = 0;
x++;
}
if (sudoku[x][y][0] != '*')
{
sudoku[x][y][1] = sudoku[x][y][0];
success = solveSudoku(x, y + 1);
}
else
{
while (query <= '9' && !success)
{
if (isValid(x, y, query, 1))
{
sudoku[x][y][1] = query;
success = solveSudoku(x, y + 1);
}
else
{
query++;
}
}
}
if (success)
{
return 1;
}
else
{
sudoku[x][y][1] = sudoku[x][y][0];
return false;
}
}
Related
The goal of this program is for the knight to move around the chest board and only touching each spot once.
Each spot is initialized and set to zero by default.
As the knight moves, each spot the knight touches should correspond with the number of moves taken to reach that point.
However, I am having quite a few problems
1) My Knight is moving around the board and going either out of bound of the multidimensional chess board array or manipulates the movement arrays (horizontal[] and vertical[])
2) The conditions of my boolean functions MoveOnBoard && MoveHasNotBeenMade are that if the next possible move is between the exisiting rows and columns also if the spot being moved to has a value of 0(meaning it has yet to be moved to). However, both of these conditions
seem to be ignored.
How would I go about fixing this?
Thank you in advance!
Here's the code below
using namespace std;
#include <iostream>
#include <array>
void DefinedMoveSet();
void RenderBoard();
void MoveKnight(int& moveChoice, int& numberOfMovesMade);
void PossibleMoves();
bool MoveOnBoard(int& moveChoice);
bool MoveHasNotBeenMade(int& moveChoice);
// Two single dimenisional arrays to store move positions for the Knight
// Arrays have yet to be assigned values
int vertical[8], horizontal[8];
int currentRow = 4, currentColumn = 3;
// Initializing an array with the dimension 8 * 8
int chestBoard[8][8] = { 0 };
int main()
{
DefinedMoveSet();
PossibleMoves();
RenderBoard();
cin.ignore();
return 0;
}
void RenderBoard()
{
// The outer loop goes through each row until it reaches 8
for (int boardRow = 0; boardRow < 8; boardRow++)
{
// The inner loop takes in the specific row
for (int boardColumn = 0; boardColumn < 8; boardColumn++)
{
// Then iterates through the columns of that row until it reaches 8
// Each index is seperated by a tab escape key shortcut
cout << chestBoard[boardRow][boardColumn] << "\t";
}
// Back to the inner array a new line is printed for the next row
cout << "\n";
}
}
void DefinedMoveSet()
{
// Values for the horizontal array at each index
horizontal[0] = 2;
horizontal[1] = 1;
horizontal[2] = -1;
horizontal[3] = -2;
horizontal[4] = -2;
horizontal[5] = -1;
horizontal[6] = 1;
horizontal[7] = 2;
// Values for the vertical array at each index
vertical[0] = -1;
vertical[1] = -2;
vertical[2] = -2;
vertical[3] = -1;
vertical[4] = 1;
vertical[5] = 2;
vertical[6] = 2;
vertical[7] = 1;
}
bool MoveOnBoard(int& moveChoice)
{
int futureRow = currentRow + vertical[moveChoice];
int futureColumn = currentColumn + horizontal[moveChoice];
if ((0 < futureRow) && (0 < futureColumn) && (futureRow < 8) && (futureColumn < 8))
return true;
}
bool MoveHasNotBeenMade(int& moveChoice)
{
int futureRow = currentRow + vertical[moveChoice];
int futureColumn = currentColumn + horizontal[moveChoice];
if (chestBoard[futureRow][futureColumn] == 0)
return true;
}
void PossibleMoves()
{
bool movesStillExist = true;
int numberOfMovesMade = 1;
while (numberOfMovesMade < 65 && movesStillExist)
{
for (int i = 0; i < 8; i++)
{
if (i == 8)
movesStillExist = false;
if (MoveOnBoard(i) && MoveHasNotBeenMade(i))
{
numberOfMovesMade++;
MoveKnight(i, numberOfMovesMade);
}
}
}
}
void MoveKnight(int &moveChoice, int &numberOfMovesMade)
{
// Takes in the int moveNumber as a parameter
// MoveNumber(or case) must be between 0 and 7
// if there is not a case for the value then the knight will not move
//chestBoard[currentRow][currentColumn] = numberOfMovesMade;
currentRow += vertical[moveChoice];
currentColumn += horizontal[moveChoice];
chestBoard[currentRow][currentColumn] = numberOfMovesMade;
}
in MoveOnBoardand and in MoveHasNotBeenMade instead of
if(...)
return true;
should be
if(...)
return true;
return false;
if condtion == false, function returning not void reach end without return statement.
With the advice from the comments I received, I was able to fix the index issues as well as the return value of the boolean functions.
My main problem was that I was not breaking out of the previous loop after moving.
Easily solved by this if statement
if (MoveOnBoard(i) && MoveHasNotBeenMade(i))
{
MoveKnight(i);
break;
}
I was trying to achieve this by telling the compiler
if (i == 8)
movesStillExist = false;
As pointed out by #Aziuth this condition will never be met because a move at that index does not exist.
So instead for my purposes I changed that condition to be
if (i == 7)
movesStillExist = false;
Also for the index issues my logic was a little off
if (((0 <= futureRow) && (0 <= futureColumn)) && ((futureRow < 8) && (futureColumn < 8)))
return true; // if the future row and column are in bounds then return true
return false; // else the default is false
Also, my code is not idealistic for c++.
Having so many global variables and not enough commenting.
Please understand that the use of single and multidimensional arrays are required due to this being a challenge for my c++ course.
bool MoveOnBoard(int& moveChoice)
{
int futureRow = currentRow + vertical[moveChoice];
int futureColumn = currentColumn + horizontal[moveChoice];
if (((0 <= futureRow) && (0 <= futureColumn)) && ((futureRow < 8) && (futureColumn < 8)))
return true;
return false;
}
bool MoveHasNotBeenMade(int& moveChoice)
{
int futureRow = currentRow + vertical[moveChoice];
int futureColumn = currentColumn + horizontal[moveChoice];
if (chestBoard[futureRow][futureColumn] == 0)
return true;
return false;
}
void PossibleMoves()
{
bool movesStillExist = true;
while (numberOfMovesMade < 65 && movesStillExist)
{
for (int i = 0; i < 8; i++)
{
if (MoveOnBoard(i) && MoveHasNotBeenMade(i))
{
MoveKnight(i);
break;
}
if (i == 7)
movesStillExist = false;
}
}
}
void MoveKnight(int &moveChoice)
{
// Takes in the int moveNumber as a parameter
// MoveNumber(or case) must be between 0 and 7
// if there is not a case for the value then the knight will not move
chestBoard[currentRow][currentColumn] = numberOfMovesMade;
numberOfMovesMade++;
currentRow += vertical[moveChoice];
currentColumn += horizontal[moveChoice];
chestBoard[currentRow][currentColumn] = numberOfMovesMade;
}
I am trying to make this go through the array in a spiral order. When it finds 2, it should replace it with 0 and the next number in the spiral order should become 2. So, if my array is
000
200
000
is should become
000
020
000
The variable ok tells me if I found that number 2 and simply modifies the next number to 2. Note that it doesn't loop through it. When It reaches the center of the array, it stops and doesn't go backwards or starts over.
Any ideas why it doesn't work? It simply doesn't modify my array at all.
#include<iostream>
using namespace std;
#define ROWS 3
#define COLS 3
int main()
{
int arr[ROWS][COLS] = {{2,0,0},
{0,0,0},
{0,0,0}};
// Four direction counters of current movement
// Horizontal right, vertical bottom, horizontal left and vertical top respectively
int hr, vb, hl, vt, ok=0;
// levl indicates current depth of our imaginary rectangle into array. Starting value is zero
// since we are looping on the boundaries and ending value is the inner most rectangle
int levl;
for (levl=0; levl < COLS - levl; levl++)
{
for(hr=levl; hr < COLS-levl; hr++) // go right
{
if (ok==1)
{
arr[levl][hr] == 2;
ok = 2;
}
if ( (arr[levl][hr] == 2) && (ok == 0) )
{
arr[levl][hr] == 0;
ok = 1;
}
}
for(vb=levl+1; vb < COLS-levl; vb++) // go down
{
if (ok == 1)
{
arr[vb][hr-1] == 2;
ok = 2;
}
if ( (arr[vb][hr-1] == 2) && (ok == 0) )
{
arr[vb][hr-1] == 0;
ok = 1;
}
}
for(hl=vb-1; hl-1 >= levl; hl--) // go left
{
if ( ok == 1)
{
arr[vb-1][hl-1] == 2;
ok = 2;
}
if ( (arr[vb-1][hl-1] == 2) && (ok == 0) )
{
arr[vb-1][hl-1] == 0;
ok = 1;
}
}
for(vt=vb-1; vt-1 > levl; vt--) // go up
{
if (ok == 1)
{
arr[vt-1][hl] == 2;
ok = 2;
}
if ( (arr[vt-1][hl] == 2) && (ok==0) )
{
arr[vt-1][hl] == 0;
ok = 1;
}
}
}
cout << endl;
for(int t = 0;t < 3;t++)
{
for(int u = 0;u < 3;u++)
cout<<arr[t][u]<<" ";
cout<<endl;
}
int a;
cin>>a;
return 0;
}
The reason that your array is not being modified is because you are using "==" instead of "=". So
if ((arr[levl][hr] == 2)&&(ok==0))
{
arr[levl][hr] == 0;
ok=1;
}
should be
if ((arr[levl][hr] == 2)&&(ok==0))
{
arr[levl][hr] = 0;
ok=1;
}
== Is a comparison operator and = assigns the value. Check your code very carefully and make it more readable for you could be able to find easy mistakes like that :).
I'm designing and programming an elevator-like robot for a high school project. Could I possibly do anything to make this any simpler? Or better? I have attached a picture of my design that I made in AutoCAD Inventor with labels.
For those not familiar with RobotC or VEX (it is VERY similar to C and C++): the limit switches (limit1, limit2, ...) and bump switches (floor1, floor2, ...) are analog buttons and return a value of 0 if not pressed and 1 if pressed. The motor (mainMotor) rotates the gear which causes the mechanism to travel upwards on the slide. When the shaft sticking out the motor mechanism moves up and down, it presses limit switches and causes it to return a value of 1.
int callup [3];
int calldown [3];
int floorat[3];
int main ()
{
if (SensorValue[limit1] == 1)
{
floorat[0] = 1;
}
else
{
floorat[0] = 0;
}
if (SensorValue[limit2] == 1)
{
floorat[1] = 1;
}
else
{
floorat[1] = 0;
}
if (SensorValue[limit3] == 1)
{
floorat[2] = 1;
}
else
{
floorat[2] = 0;
}
if (SensorValue[floor1] == 1)
{
calldown[0] = 1;
SensorValue[LED1] = 1;
}
if (SensorValue[floor2] == 1 && floorat[2] == 1)
{
calldown[1] = 1;
SensorValue[LED2] = 1;
}
if (SensorValue[floor2] == 1 && floorat[0] == 1)
{
callup[1] = 1;
SensorValue[LED2] = 1;
}
if (SensorValue[floor3])
{
callup[2] = 1;
SensorValue[LED3] = 1;
}
motors ();
}
void motors ()
{
if (callup[2] == 1 && floorat[2] == 1)
{
int x = 1;
while (x < 3)
{
SensorValue[LED3] = 1;
wait(0.5);
SensorValue[LED3] = 0;
wait(0.5);
}
callup[2] = 0;
main ();
}
else if (callup[1] == 1 && floorat[1] == 1)
{
int x = 1;
while (x < 3)
{
SensorValue[LED2] = 1;
wait(0.5);
SensorValue[LED2] = 0;
wait(0.5);
}
callup[1] = 0;
main ();
}
else if (callup[0] == 1 && floorat[0] == 1)
{
int x = 1;
while (x < 3)
{
SensorValue[LED1] = 1;
wait(0.5);
SensorValue[LED1] = 0;
wait(0.5);
}
callup[0] = 0;
main ();
}
if (callup[2] == 1 && floorat[1] == 1 && calldown[0] == 0 || callup[2] == 1 && floorat[0] == 1 && callup[1] == 0)
{
startMotor(mainMotor, 60);
untilTouch(limit3);
stopMotor(mainMotor);
callup[2] = 0;
wait(1);
main ();
}
if (callup[1] == 1 && floorat[0] == 1)
{
startMotor(mainMotor, 60);
untilTouch(limit2);
stopMotor(mainMotor);
callup[1] = 0;
wait(1);
main();
}
if (calldown[1] == 1 && floorat[2] == 1)
{
startMotor(mainMotor, -60);
untilTouch(limit2);
stopMotor(mainMotor);
calldown[1] = 0;
wait(1);
main();
}
if (calldown[0] == 1 && floorat[2] == 1 && calldown[1] == 0 || calldown[0] == 1 && floorat[1] == 1)
{
startMotor(mainMotor, -60);
untilTouch(limit1);
stopMotor(mainMotor);
calldown[0] = 0;
wait(1);
main();
}
}
Although it shouldn't be a concern for this question, the 60 in the startMotor command is the speed of the motor, just to make it clearer.
Feel free to ask any more questions.
Let's define what are the states of an elevator at a given moment:
An elevator can go up, down, or be idle.
The elevator is at a given floor and go from one floor to the other when it trigger a switch:
Now, if we translate this into some pseudo code (which should be easily translated to RobotC) :
enum elevator_status = { idle, down, up };
int currentfloor; //1, 2, 3
switch(elevator_status)
{
case idle:
//we check if a button is pressed and possibly go up or down
if(SensorValue(floor1))
{
if(currentfloor > 1)
elevator_status = down;
}
else if(SensorValue(floor2))
{
if(currentfloor > 2)
elevator_status = down;
else if(currentfloor < 2)
elevator_status = up;
}
else if(SensorValue(floor3))
{
if(currentfloor < 3)
elevator_status = up;
}
break;
case up:
case down:
//we check if we trigger a floor switch and stop the elevator
if(SensorValue(limit1))
{
currentfloor = 1;
elevator_status = idle;
}
else if(SensorValue(limit2))
{
currentfloor = 2;
elevator_status = idle;
}
else if(SensorValue(limit3))
{
currentfloor = 3;
elevator_status = idle;
}
break;
}
//we set the speed of the motor
if(elevator_status == up)
{
set_motorstate(cw);
)
else if(elevator_status == down)
{
set_motorstate(ccw);
}
else if(elevator_status == idle)
{
set_motorstate(idle);
}
Note : in this code the elevator will only take care of new up and down floor calls when the elevator is idle. It does not store up and down call while it is moving and go there later. I do not know if it was a requirement for you.
I'm not familiar with RobotC or VEX, however I've noticed a certain amount of replicated operations that could be made into their own functions.
The following code snippets I would make into separate functions. So in the large function called motors you have the following set of operations:
int x = 1;
while (x < 3)
{
SensorValue[LED3] = 1;
wait(0.5);
SensorValue[LED3] = 0;
wait(0.5);
}
callup[2] = 0;
main ();
This is repeated with slightly different values.
Here I'd write a function like the following:
void adjust_sensors( size_t led, size_t level )
{
int x = 1;
while (x < 3)
{
SensorValue[led] = 1;
wait(0.5);
SensorValue[led] = 0;
wait(0.5);
}
callup[level] = 0;
main ();
}
You can do the same for the following code as well:
startMotor(mainMotor, 60);
untilTouch(limit3);
stopMotor(mainMotor);
callup[2] = 0;
wait(1);
main ();
Also it seems like the while loop will never end because the value of x never changes.
You also have a typo at the top when you declare:
int callown [2];
I presume you meant:
int calldown [2];
Would be good to add some comments to your code as well for clarity.
Hope this helps.
I could be way off, because I'm just a student with questions of my own but it looks like you may have made a mistake in your array sizes. For instance, when you declared:
int floorat[2];
This made the array size 2. Then you refer to 3 element locations in this array [0, 1, 2]. Also, can't you just use a regular integer, and assign it values 1, 2, or 3?
I would recommend redefining these varaibles as:
int callup;
int calldown;
int floorat;
Then you can avoid extra lines of code and simplify the if/else clauses to:
if (SensorValue[limit1] == 1)
{
floorat = 1;
}
if (SensorValue[limit2] == 1)
{
floorat = 2;
}
if (SensorValue[limit3] == 1)
{
floorat = 3;
}
I work with Arduino with Eclipse. I want to read a double from a configuration file. I have made these functions:
void Settings::readDouble(char buff, String data, bool flag, double dataToStore) {
data = "";
int intPart = 0;
int probablyFloatPart = 0;
while(buff != '\n') {
if(isdigit(buff)) {
data.concat(buff);
Serial.println(data);
}
else if (buff == '.') {
char charBuf[data.length()+1];
data.toCharArray(charBuf,data.length()+1);
// Convert chars to int
intPart = atoi(charBuf);
Serial.println(intPart);
data="";
flag = false;
}
buff = theSettings.read();
};
// Convert string to array of chars
char charBuf[data.length()+1];
data.toCharArray(charBuf,data.length()+1);
// Convert chars to integer
probablyFloatPart = atoi(charBuf);
Serial.println(probablyFloatPart);
if (!flag) {
dataToStore = intPart + (probablyFloatPart/pow(10, data.length()));
}
else {
dataToStore = probablyFloatPart;
}
flag = true;
//Serial.println(dataToStore, 5);
}
From serial.printing I noticed that if the number I want to read has more than four digits on either int or decimal part it gives an error. Basically, I can not tranform a string with more than four bytes to an int. How can I do this?
You will need to use long to store values over 32767 (or in an unsigned, over 65535).
I'll be back with a simpler piece of code - I think your code is more complex than it needs to be.
This code uses no standard functions except isdigit, and just walks through the number. No limitiation on the size of the number (obviosusly, if you go over the limit for a double, then it will fail). Error handling may need a bit of improvement. I have given it some mild testing...
double str_to_double(const char *data, size_t len)
{
double d = 0.0;
bool neg = false;
int index = 0;
if (data[index] == '-')
{
index++;
neg = true;
}
while(data[index] != '.' && index < len)
{
if (isdigit(data[index]))
{
d = d * 10 + (data[index] - '0');
index ++;
}
else
{
// Handle "bad input" ...
return -1;
}
}
if (data[index] == '.')
{
index ++;
double div = 10.0;
while(index < len)
{
if (isdigit(data[index]))
{
d += (data[index] - '0') / div;
div *= 10;
index++;
}
else
{
// Handle bad input
return -1;
}
}
}
// Flip sign if need be.
if (neg)
{
d = -d;
}
return d;
}
I would try to save the result in a float. The code below is what I would try.
float result = 0;
float scale = 10;
bool pastDecPoint = false;
while(buff != '\n') {
if(isdigit(buff){
if(pastDecPoint)
{
result = result + (buff / scale);
scale = scale * 10;
}
else
{
result = (result * 10.0) + atoi(buff);
}
} else if (buff == '.') {
pastDecPoint = true;
}
buff = theSettings.read();
};
Serial.println(result);
}
I also want to see what petersson comes back with. Which is very similar to Petersson
Is there any predefined function in c++ to check whether the number is square of any number and same for the cube..
No, but it's easy to write one:
bool is_perfect_square(int n) {
if (n < 0)
return false;
int root(round(sqrt(n)));
return n == root * root;
}
bool is_perfect_cube(int n) {
int root(round(cbrt(n)));
return n == root * root * root;
}
sqrt(x), or in general, pow(x, 1./2) or pow(x, 1./3)
For example:
int n = 9;
int a = (int) sqrt((double) n);
if(a * a == n || (a+1) * (a+1) == n) // in case of an off-by-one float error
cout << "It's a square!\n";
Edit: or in general:
bool is_nth_power(int a, int n) {
if(n <= 0)
return false;
if(a < 0 && n % 2 == 0)
return false;
a = abs(a);
int b = pow(a, 1. / n);
return pow((double) b, n) == a || pow((double) (b+1), n) == a;
}
No, there are no standard c or c++ functions to check whether an integer is a perfect square or a perfect cube.
If you want it to be fast and avoid using the float/double routines mentioned in most of the answers, then code a binary search using only integers. If you can find an n with n^2 < m < (n+1)^2, then m is not a perfect square. If m is a perfect square, then you'll find an n with n^2=m. The problem is discussed here
Try this:
#include<math.h>
int isperfect(long n)
{
double xp=sqrt((double)n);
if(n==(xp*xp))
return 1;
else
return 0;
}
The most efficient answer could be this
int x=sqrt(num)
if(sqrt(num)>x){
Then its not a square root}
else{it is a perfect square}
This method works because of the fact that x is an int and it will drop down the decimal part to store only the integer part. If a number is perfect square of an integer, its square root will be an integer and hence x and sqrt(x) will be equal.
For identifying squares i tried this algorithm in java. With little syntax difference you can do it in c++ too.
The logic is, the difference between every two consecutive perfect squares goes on increasing by 2. Diff(1,4)=3 , Diff(4,9)=5 , Diff(9,16)= 7 , Diff(16,25)= 9..... goes on.
We can use this phenomenon to identify the perfect squares.
Java code is,
boolean isSquare(int num){
int initdiff = 3;
int squarenum = 1;
boolean flag = false;
boolean square = false;
while(flag != true){
if(squarenum == num){
flag = true;
square = true;
}else{
square = false;
}
if(squarenum > num){
flag = true;
}
squarenum = squarenum + initdiff;
initdiff = initdiff + 2;
}
return square;
}
To make the identification of squares faster we can use another phenomenon, the recursive sum of digits of perfect squares is always 1,4,7 or 9.
So a much faster code can be...
int recursiveSum(int num){
int sum = 0;
while(num != 0){
sum = sum + num%10;
num = num/10;
}
if(sum/10 != 0){
return recursiveSum(sum);
}
else{
return sum;
}
}
boolean isSquare(int num){
int initdiff = 3;
int squarenum = 1;
boolean flag = false;
boolean square = false;
while(flag != true){
if(squarenum == num){
flag = true;
square = true;
}else{
square = false;
}
if(squarenum > num){
flag = true;
}
squarenum = squarenum + initdiff;
initdiff = initdiff + 2;
}
return square;
}
boolean isCompleteSquare(int a){
// System.out.println(recursiveSum(a));
if(recursiveSum(a)==1 || recursiveSum(a)==4 || recursiveSum(a)==7 || recursiveSum(a)==9){
if(isSquare(a)){
return true;
}else{
return false;
}
}else{
return false;
}
}
For perfect square you can also do:
if(sqrt(n)==floor(sqrt(n)))
return true;
else
return false;
For perfect cube you can:
if(cbrt(n)==floor(cbrt(n)))
return true;
else
return false;
Hope this helps.
We could use the builtin truc function -
#include <math.h>
// For perfect square
bool is_perfect_sq(double n) {
double r = sqrt(n);
return !(r - trunc(r));
}
// For perfect cube
bool is_perfect_cube(double n) {
double r = cbrt(n);
return !(r - trunc(r));
}
bool isSquare(int n) {
return floor(sqrt(n)) == ceil(sqrt(n));
}
bool isQube(int n) {
return floor(cbrt(n)) == ceil(cbrt(n));
}