I managed to make the program works but the problem is the between Row 3 Column 2 and Row 3 Column 3. Whenever i input two duplicate numbers in row 3 column 2 and row 3 column 3, it accepts those two.
If i input 1 there, it loops back. My only problem is the number 8. Why's that?
Here's my code:
Scanner input = new Scanner(System.in);
int magic_square[][]=new int[3][3];
int counter = 0;
int valid = 0;
int duplicate = 0;
int sum_row[] = new int[3];
int sum_col[] = new int[3];
int rowcolcheck =0;
int rowcheck=0;
System.out.println("Enter the Magic Number: ");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
valid = 0;
do{
duplicate = 0;
System.out.print("Row "+(i+1)+" Column "+(j+1)+": ");
magic_square[i][j] = input.nextInt();
if(magic_square[i][j]<0||magic_square[i][j]>9){
System.out.println("Invalid input range! Please try again!");
valid = 1;
continue;
}
valid = 0;
for(int a=0;a<3;a++){
for(int b=0;b<3;b++){
if(a==i&&b==j)
{
continue;
}
if(magic_square[i][j]==magic_square[a][b]){
duplicate = 1;
System.out.println("Duplicate Number! Please try again!");
continue;
}
if(duplicate==1){
valid = 1;
}
}
}
}while(valid!=0);
}
}
I fixed it!
valid = 0;
for(int a=0;a<3;a++){
for(int b=0;b<3;b++){
if(a==i&&b==j)
{
continue;
}
if(magic_square[i][j]==magic_square[a][b]){
valid = 1; // i change this. it was duplicate = 1.
//now it's valid = 1.
System.out.println("Duplicate Number! Please try again!");
continue;
}
//i removed this conditon and the integer duplicate =
// 0 and it works like a charm!
//if(duplicate==1){
// valid = 1;
//}
}
}
Related
Look at this code, In my VS code or some online compilers it gives favorable output, but when I'm submitting this on HackerRank or this online compiler I'm getting wrong output but only when I provide input as: 1 1 1 100...and I'm not able to spot the Error?..I'm providing question for reference.
/*There will be two arrays of integers. Determine all integers that satisfy
the following two conditions:
The elements of the first array are all factors of the integer being
considered
The integer being considered is a factor of all elements of the second array
These numbers are referred to as being between the two arrays. Determine how
many such numbers exist.
*/
#include <iostream>
int main()
{
int count1, count2;
int num1[20], num2[20];
std::cin >> count1 >> count2;
for (int i = 0; i < count1; i++)
{
std::cin >> num1[i];
}
for (int i = 0; i < count2; i++)
{
std::cin >> num2[i];
}
int occurence_firstarray = 0, occurence_secondarray = 0, totalvalid_occurence = 0;
for (int i = num1[count1 - 1]; i < num2[1]; i++)
{
occurence_firstarray = 0;
occurence_secondarray = 0;
for (int j = 0; j < count1; j++)
{
if (i % num1[j] == 0)
{
occurence_firstarray++;
}
}
if (occurence_firstarray == count1)
{
for (int p = 0; p < count2; p++)
{
if (num2[p] % i == 0)
{
occurence_secondarray++;
}
}
}
if (occurence_secondarray == count2)
{
totalvalid_occurence++;
}
}
std::cout << totalvalid_occurence;
return (0);
}
Considering your inputs: 1 1 1 100,
What are you doing in this code is You are pointing on index beyond your second array's size limit i < num2[1], this is why you are getting wrong outputs.
Do some changes as, i <= num2[0];
have problem with filling array from Serial.
So basically, first asking for lenght of array, then should input from keyborad all elements. Problem is that it's not waiting to enter values into Serial and just fill with 0. If will type values right away, it will put them into array.
My question is how to force wait from Arduino till i will input values.
Thank You!
boolean fill = false;
int sum = 0;
int lengthOfArray;
void setup()
{
Serial.begin(9600);
Serial.print("Set lenght of array : ");
}
void loop()
{
if(fill == false)
{
if(Serial.available() > 0)
{
lengthOfArray = Serial.parseInt();
Serial.println(lengthOfArray);
int tab[lengthOfArray];
for(int i = 0; i < lengthOfArray; i++)
{
delay(10);
Serial.print("Tab[" + String(i) + "] : ");
tab[i] = Serial.parseInt();
Serial.println(tab[i]);
sum += tab[i];
}
fill = true;
Serial.println("Sum = " + String(sum));
}
}
}
If I understood your problem correctly, you're willing to print all the values at once, not for every value that you type.
You may maintain separate for-loops for reading and then printing
for(int i = 0; i < lengthOfArray; i++)
{
delay(10);
Serial.print("Tab[" + String(i) + "] : ");
tab[i] = Serial.parseInt();
sum += tab[i];
}
fill = true;
for(int i = 0; i < lengthOfArray; i++)
Serial.println(tab[i]);
Serial.println("Sum = " + String(sum));
So i am doing a graph coloring problem in which i input number of test cases for which the code has to run. Here's the code:
#include <bits/stdc++.h>
using namespace std;
int main() {
int test,num,i,j,k,l,sum,num1,num2,count,col;
cin>>test;
for(i=0;i<test;i++){
sum = 0;
cin>>num;
int arr[num][num];
for(j=0;j<num;j++){
for(k=0;k<num;k++){
arr[j][k] = 0;
}
}
for(l=0;l<num-1;l++){
cin>>num1>>num2;
arr[num1-1][num2-1] = 1;
arr[num2-1][num1-1] = 1;
}
int* colVert = new int[num];
for(j=0;j<num;j++){
colVert[j] = 0;
}
for(j=0;j<num;j++){
count = 0;
l=0;
if(j == 0){
colVert[j] = 1;
}
else{
for(k=0;k<num;k++){
if(arr[j][k] == 1){
count++;
}
}
int colSeq[count];
for(k=0;k<num;k++){
if(arr[j][k] == 1){
colSeq[l] = colVert[k];
l++;
}
}
sort(colSeq, colSeq+count);
/*for(k=0;k<count;k++){
cout<<colSeq[k];
}*/
for(k=0;k<count;k++){
if(colSeq[k] != k+1){
col = k;
break;
}
else{
col = colSeq[k] + 1;
}
}
colVert[j] = col;
}
}
for(i=0;i<num;i++){
sum = sum + colVert[i];
}
cout<<sum<<endl;
}
return 0;
}
So the problem is the code only runs for the first test case and then program ends. I think the problem is with the way i have declared colVert array. So how to do it correctly so that it runs for every case?
Guys the issue was resolved. The problem was not in the way how colVert array was declared but a really silly mistake:
for(i=0;i<num;i++){
sum = sum + colVert[i];
}
I used 'i' variable in a loop inside a loop which is also using 'i' as its counter. Simply using any other counter variable fixed the problem.
To simplify it, I need to read numbers from a file and store them in a 2D array. I then must check to make sure that the there were enough numbers in the file to fill the array.
the first two numbers in the file are the ones that declare how many rows and columns there should be for the array.
The part I am struggling with is that the numbers in the file can also include a 0 in them.
I was using this method to test if an element was empty
double numbers[MAX_ROW][MAX_COL];
for(int i = 0; i <= row; i++) {
for(int n = 0; n <= col; n++) {
if(!numbers[i][n]){
cout << "Error: There is not enough data found file :(...." << endl;
cout << "The Program will now exit....." << endl;
return 0;
}
}
}
But then I realized that the program would exit if the file contained the number 0. Which is something that I don't want to happen.
I also tried to using a pointer and testing for NULL but that gave me a warning about (comparison between NULL and non-pointer) and it would still do the same thing, if there was a 0 in the file it would just exit.
double (*ptrNumbers)[MAX_COL] = numbers;
for(int i = 0; i <= row; i++) {
for(int n = 0; n <= col; n++) {
if(ptrNumbers[i][n] == NULL){
cout << "Error: There is not enough data found file :(...." << endl;
cout << "The Program will now exit....." << endl;
return 0;
}
}
}
Example files:
This one works fine
3 3
1 3 4
3 2 4
3 5 2
This will not works because of the zero in the file
3 3
1 3 4
3 0 4
3 5 2
This is the type of error i would like to test for.
It says there are 3 rows and 3 columns but there aren't numbers to fill the rest of the array. Therefore they will be initialized to 0 which as you can conclude will also cause the same problem.
3 3
1 3 4
3 2 4
3
Anyone have any idea how I can test for "empty" elements but not elements containing 0s?? Or am I just doing something wrong?
Thanks in advance for any help :)
After I altered my program from the previous recommendations.
I set up a bool function to return a false statement if there was not enough numbers in the file. However even if the file had the correct amount of numbers the file would still execute the if statement and return a false value. Is my syntax wrong in some way?
for(int i = 0; i <= row; i++) {
for(int n = 0; n <= col; n++) {
if(!(inFile >> numbers[i][n])) {
return false;
}
else {
inFile >> numArray[i][n];
}
}
}
return true;
You have to catch error while reading the contents of the file.
std::ifstream ifile("The input file");
ifile >> row >> col;
for(int i = 0; i <= row; i++) {
for(int n = 0; n <= col; n++) {
if( ! (ifile >> ptrNumbers[i][n]))
{
// Problem reading the number.
cout << "Error: There is not enough data found file :(...." << endl;
cout << "The Program will now exit....." << endl;
}
}
}
Update
The updated function is faulty.
for(int i = 0; i <= row; i++) {
for(int n = 0; n <= col; n++) {
if(!(inFile >> numbers[i][n])) {
return false;
}
else {
// You are now reading into the same element
// of the array again.
inFile >> numArray[i][n];
}
}
}
return true;
You don't need the else part in that function.
for(int i = 0; i <= row; i++) {
for(int n = 0; n <= col; n++) {
if(!(inFile >> numbers[i][n])) {
return false;
}
}
}
return true;
I'm trying to solve the problem of the magic square in C ++ using Backtracking and recursion in C ++. Specifically for a 4x4 array.
An example of 4x4 magic square solution is as follows, in which each row, column and diagonal add 34:
The change that I have is this: The user enters some values that will start the algorithm.
My algorithm is this:
here you can appreciate better the image.
I have a notion of how the algorithm should work to solve the problem of the magic square with backtracking and recursion, but I've had problems.
One of them is:
Achievement not make my algorithm "ignore" the values that the user already entered.
My code in C++ is in this link in Github. And here is the code :
#include <iostream>
using namespace std;
int sudoku[4][4];
int row = 0;
int column = 0;
bool isFull(int s[4][4]){
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
if(s[4][4] == 0){
return false;
}
}
}
return true;
}
void printMatrix(int s[4][4]){
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
cout << sudoku[i][j] << " ";
}
cout << endl;
}
}
bool isAssigned(int row, int column){
if(row == 1 && column == 0 ||
row == 0 && column == 2 ||
row == 1 && column == 2){
return true;
} else return false;
}
bool verify(int s[4][4], int row, int column){
bool flag = false;
int sumrow = 0, sumcolumn = 0, sumDiagonal = 0, sumDiagonal2 = 0;
int value = 3;
for(int i = 0; i < 4; i++){
sumrow = sumrow + s[row][i];
sumcolumn = sumcolumn + s[i][column];
sumDiagonal = sumDiagonal + s[i][i];
sumDiagonal2 = sumDiagonal2 + s[i][value];
value--;
}
if(sumrow <= 34 && sumcolumn <= 34 && sumDiagonal2 <= 34 && sumDiagonal2 <= 34){
return true;
} else return false;
}
bool backtracking(int s[4][4], int row, int column){
if(isFull(s) == true){ //verify if there are no zeros in the matrix
printMatrix(sudoku);
cout<<"Solution find ";
}
else {
if(isAssigned(row, column) == false){ // verify if the cell is already assigned
for(int i = 1; i <= 16; i++){
s[row][column] = i; // assigned value
if(verify(s, row, column) == true){ // verify that the sum of the column, row and diagonal not greater 34
if(column == 4) {
row++;
column=0;
}
backtracking(s, row, column + 1); // recursion
printMatrix(s); // Print the matrix to see progress
cout<<endl;
} else { // the sum value exceeds 34
s[row][column] = 0;
return false;
}
}
}
}
}
int main(){
sudoku[1][0] = 5;
sudoku[0][2] = 15;
sudoku[1][2] = 10;
backtracking(sudoku, row, column);
return 0;
}
My algorithm is mainly the following:
Obviously some features in this case, but if you see my code you will realize what I try to do.
Perhaps my solution method does not work or is not good.
The reason for this publication is, I need help to improve or Need help to solve the code did. Here is my main function and output I get to run:
bool backtracking(int s[4][4], int row, int column){
if(isFull(s) == true){ //verify if there are no zeros in the matrix
printMatrix(sudoku);
cout<<"Solution find ";
}
else {
if(isAssigned(row, column) == false){ // verify if the cell is already assigned
for(int i = 1; i <= 16; i++){
s[row][column] = i; // assigned value
if(verify(s, row, column) == true){ // verify that the sum of the column, row and diagonal not greater 34
if(column == 4) {
row++;
column=0;
}
backtracking(s, row, column + 1); // recursion
printMatrix(s); // Print the matrix to see progress
cout<<endl;
} else { // the sum value exceeds 34
s[row][column] = 0;
return false;
}
}
}
}
}
output:
3 16 15 0
5 0 10 0
0 0 0 0
0 0 0 0
as I said before, I have problems when I find a value that the user was already assigned.
It is the first time working with backtracking, that is why I find it a bit difficult. Thanks for all.
Well, yes,
Had to do something similar lately, some places to get this "fixed"
Start with a bitmap (1-16) for the numbers already assigned in the grid. ie. those the user entered are already marked as being "used".
Only assign numbers to the grid that haven't been marked in that bitmap. If you use non-recursive methods, need to use a stack to know which have been tested to "unset" when backtracking. If using recursive methods (only 16 deep recursion ;) ) pass the bitmap and the already placed square as copies, not references ;)