I want to make a program for solving a 3*3 sudoku puzzle. I have made a program but it is only working for 50% problems and for the rest it gives 60% right solution. I do not know how to solve it in a finite number of steps for every possible problem. The technique I have used is that I am searching every individual element of array and check which no does not exist in the same row and column and then I put it in that unit and move to the next. But this is not the solution for every problem. The next thing that come to mind was that we should have to write each and every possible number for a unit and then proceed. But how will we decide that which number we should finally put in the unit. I just want that how to write a solution that will work for every problem. I hope you got the point.
The code I have written is
#include<iostream>
using namespace std;
int rowsearch(int l[9][9],int row,int num) // function to search a particular number from a row of array
{
int counter=0;
for (int c=0 ; c<9 ; c++)
{
if (l[row][c]==num)
counter=counter+1;
}
if (counter>0)
return 1;
else
return 0;
}
int colsearch(int l[9][9],int col,int num) // function to search a number from a column of an array
{
int counter=0;
for (int c=0 ; c<9 ; c++)
{
if (l[c][col]==num)
counter=counter+1;
}
if (counter>0)
return 1;
else
return 0;
}
int rowcolnotexist(int x[9][9],int row , int col) // to find a nuber which does not exists int a row and column
{
for (int c=1 ; c<=9 ; c++)
{
if ( rowsearch(x,row,c)!=1 && colsearch(x,col,c)!=1)
return c;
}
return 0;
}
int main()
{
int l[9][9]={};
// input of the list
for (int i=0 ; i<9 ; i++)
for (int j=0 ; j<9 ; j++)
{
cout<<"Enter "<<i+1<<"*"<<j+1<<"entry of the list(For not entering a number enter 0).";
cin>>l[i][j];
}
// operations
for (int i=0 ; i<9 ; i++)
{
for (int j=0 ; j<9 ; j++)
if (l[i][j]==0)
l[i][j]=rowcolnotexist(l,i,j);
}
// printing list
for (int i=0 ; i<9 ; i++)
{
for (int j=0 ; j<9 ; j++)
{
cout<<l[i][j];
if ((j+1)%3==0)
cout<<" ";
else
cout<<" ";
}
if ((i+1)%3==0)
cout<<"\n\n\n";
else
cout<<"\n\n";
}
return 0;
}
I'd recommend the same algorithm I use when solving them myself ;-)
Choose an arbitrary square and list all the valid values for it, based on what is present in all the other rows (there's probably a way to make a more efficient decision about which square to start with).
Then move on to a related empty square (there's probably a way to make a more efficient decision about which square to check next) and store all its possible values.
Rinse and repeat until you find a square that has only one valid value.
Then unzip.
This should sounds like a recursive problem, by now. (note: almost anything that can be done recursively can be done conventionally, but the idea is the same).
So, store up a list of partially solved squares, and when you get to a square that's been solved completely, go back through your list in reverse order re-evaluating your partial solutions with the new data (namely, the one you WERE able to solve).
Rinse and repeat for full body and volume.
Related
The question is to find the largest subarray with contiguous
elements. For example if the given array is a[ ]={7,1,3,2} then
it's subarray would be {1,3,2} because the difference of maximum
element and the minimum element is equal to the difference of the
indexes of the first and the last element of the subarray and the
subarray contains all the numbers between 1 and 3.
Here's a code that I have written for this problem but the thing is that in the main function somehow the function call line longestConsecutiveNumsSubarray(); is not actually calling the function. I checked this in python tutor and it says that the whole program finished executing in only 1 step which should not be the case. So, can someone tell me what is wrong with my code.
3.Code:
#include<iostream>
using namespace std;
const int Nmax= 100005;
int a[Nmax],n;
int longestConsecutiveNumsSubarray()
{
int ans = 1;
for(int left = 0; left<(n-1) ; left++)
{
int Min, Max;
Min=a[left];
Max=a[left];
for(int right = left+1 ; right<n ; right++)
{
Min = min(Min , a[right]);
Max = max(Max , a[right]);
if(Min-Max == right-left)
ans = max(ans , Min-Max+1);
}
}
return ans;
}
int main()
{
cin>>n;
for(int i=1 ; i<=n ; i++)
cin>>a[i];
cout<< longestConsecutiveNumsSubarray();
return 0;
}
PS: I don't know why I had to indent my code with 4 spaces to get my code into the code block. I clicked on the code button and then I pasted the whole code but somehow all the tabs and spaces that were originally in my code disappeared.
I've got a bit of a conundrum. I'm currently trying to create a user-defined function to sort a column (in ascending order) of a 2D int array I created and populated in the main function. I feel like I'm close, but for some reason the final output is incorrect, it provides a number for the final value that isn't even in the array. Judging from the value provided and the extra few seconds it takes to compile, I'm assuming I've messed up my bounds/ gone beyond them at some point within the code, but I've been fighting this thing for hours to no avail and I feel fresh (and likely more experienced) eyes would be-be of some use. I'm still in my "Intro to" class for programming, so ripping me a new one for obvious errors is encouraged as my final is this Thursday and any and all pointers/tips are appreciated. Cheers!
#include <iostream>
using namespace std;
void sort2D(int arr[3][5], int rows, int columns) //the problem child
{
int userCol;
cout<<"Please enter the number of the column you'd like to sort: "<<endl;
cin>>userCol; //ask for appropriate column
for (int row_index=0; row_index<rows; row_index++) //start with first row and continue for all values in code
{
int temp;
if ((arr[row_index][userCol-1]<arr[row_index+1][userCol-1]))//if first value of selected column is less than next value
{
temp = arr[row_index+1][userCol-1];//create copy of second value
arr[row_index+1][userCol-1]=arr[row_index][userCol-1]; //replace second value with first value
arr[row_index][userCol-1]=temp;//set first equal to second's original value
}
}
for(int i=0; i<rows; i++)//print that shiz
{
for(int j=0; j<columns; j++)
{
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
}
int main()
{
const int rows = 3;
const int columns = 5;
int arr[rows][columns];
for (int row_index=0; row_index<rows; row_index++)
{
for (int column_index=0; column_index<columns; column_index++)
{
arr[row_index][column_index] = (50+rand()%51);
cout << arr[row_index][column_index]<<" ";
}
cout << endl;
}
findMaxandIndex(arr, rows, columns);//i left my code for this out because it's working and isn't utilized in the problem code
cout << endl;
sort2D(arr, rows, columns);
return 0;
Your sort function is very close to bubble sort, one of the simplest sorting algorithms to understand and implement. With a little modification, your code will work :
void sort2D(int arr[3][5], int rows, int columns) //the problem child
{
//input userCol ...
//sorting start here ...
bool found = true; //we can quit the loop if the array is already sorted.
for (int bubble = 0; bubble < rows-1 && found ; bubble++)
{
found = false;
for (int row_index=0; row_index < rows - bubble - 1; row_index++)
{
int temp;
if ((arr[row_index][userCol-1] < arr[row_index+1][userCol-1]))//if first value of selected column is less than next value
{
//swap two elements.
temp = arr[row_index+1][userCol-1];//create copy of second value
arr[row_index+1][userCol-1]=arr[row_index][userCol-1]; //replace second value with first value
arr[row_index][userCol-1]=temp;//set first equal to second's original value
found = true; //we found something, continue to sort.
}
}
}
//print out the result ...
}
As you start in C++, an advice is to use C++ facilities if possible : std::vector for your array and std::qsort for sorting elements.
Issue 1: The int arr[3][5]; you declared in sort2D() is NOT the same as the int arr[rows][columns]; you declared in main().
lesson : check (or web search) on "pass by reference" & "pass by value" . For simplicity, I recommend pass by value.
Issue 2: The sort only compare 2 values and only run for 1 pass.. so {2,1,4,3} may get sorted to {1,2,3,4} but {1,4,3,2} will only get to {1,3,2,4} with 1 pass. #ZDF comment is helpful for this part.
Issue 3: at this line.. temp = arr[row_index+1][userCol-1]; when row_index is 2, this will refer to a location that is not in the arr[][] array. arr are only defined for row = 0,1,2 .. not 3 (when row_index is 2, row_index+1 is 3). This may answer :
it provides a number for the final value that isn't even in the array.
Solution.. hurm. I suggest you have a look and try.. and share where you stuck at. you may also test the sort2D in the main function before doing it as separate function. IMHO, you can start by 1st looking for the sorting algorithm that works (with sample data).. Then work on making it work in this project. ( :
p/s: I don't see my post as an answer.. more like a correction guide.
I was attempting the following exercise, but got stuck in the process.
Write a full program that reads in an arbitrary sequence of integers
from the standard input, and writes them to the standard output in
sorted order and with all duplicates removed. You may assume the
input contains at most 100 integers .
I have a hard time understanding arrays and attempted to figure out what it is that I need to do. I have some code written down, but I have a strong feeling I'm nowhere near completing it. I'm not asking for someone to complete it for me, I just want some guidance on how to get going, or a push in the right direction. Any help is greatly appreciated.
#include <iostream>
using namespace std;
int main()
{
//I believe this is a start.
int numbers [100];
//declaring a counter
int i;
//making a for loop to count the integers from 1 to 100
for (i=0; i<100; i++)
{cin>>numbers[i];}
//This is the point where I got lost
if (i<100)
cout<<numbers[i]<<""<<endl;
}
In order to sort some int number, you have several way that you can try some of which you want.
One way is when you read data in first loop, put data in right position in array in this way that use another loop and shift new data until arrive to smaller number. Then put new data in front of that. If you find equal number you can ignore new data and use break and get new data.
for (i=0; i<100; i++)
{
int temp ;
cin>> temp;
int j;
for(j = i; j>= 0 ; j--)
{
if(j != 0 && number[j-1]== temp)
break ;
if(j != 0 && number[j-1] > temp)
{
number[j] = number[j-1] ;
}
else
{
number[j] = temp ;
break;
}
}
}
I think this way is best, but you have other way like:
sort all number using an algorithm like bubble sort or Quick sort then with a loop delete all duplicate numbers.
int temp[100] ;
int k = 0 ;
temp[0] = number[0] ;
for(int i = 1 ; i < 100 ; i++)
{
if(temp[k] != number[i])
{
k++;
temp[k] = number[i] ;
}
}
#include<iostream>
#include<conio.h>
#include<math.h>
#include<vector>
#include<iterator>
#include<string>
using namespace std;
int main() {
int k=0;
string s;
cout<<"string ";
getline(cin,s); //taking in a string from the user
float n=s.size(); //storing size of string
int f=floor((sqrt(n))); //floor of square root of input string
int c=ceil((sqrt(n))); //ceiling
int m=f*c; //storing product of f and c
vector< vector<string> > vec(n<=m?f:++f, vector<string>(c)); //makes a 2d vector
//depending on user's
//string length
for(int i=0;n<=m?i<f:i<++f;i++) //looping acc to user's input and assigning
{
for(int j=0;j<c;j++) //string to a matrix
{
if(k<s.size())
{
vec[i][j]=s[k];
k++;
}
}
}
for(int j=0;j<c;j++) //printing the vector
{
{
for(int i=0;n<=m?i<f:i<++f;i++)
cout<<vec[i][j];
}cout<<" ";
}
getch();
}
It's not working for n>m as for a string of length 8 characters it makes a vector of 2*3 thus failing to enclose the whole string in the matrix and which is why I am using ternary so as to make a vector of bigger size when it encounters cases like these.
.So what am I doing wrong?
I'll just write the whole question.
One classic method for composing secret messages is called a square code. The spaces are removed from the english text and the characters are written into a square (or rectangle). The width and height of the rectangle have the constraint,
floor(sqrt(word)) <= width, height <= ceil(sqrt(word))
The coded message is obtained by reading down the columns going left to right. For example, the message above is coded as:
imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau
Sample Input:
chillout
Sample Output:
clu hlt io
This won't fix your entire problem, but I still feel it is important. You seem to misunderstand how the ternary works. Let's observe one of its uses here:
for (int i = 0; n <= m ? i < f : i < ++f; i++) {}
// ^^^^^^^^^^^^^^^^^^^^^^^^ <--- not the intended outcome
This will not work because the returned side of the ternary does not "stick" itself in-place. In other words, neither i < f nor i < ++f will be put directly into the for-loop. Instead, it'll give you a value.
To see what it's really doing, you'll first need to understand that the ternary is just another way to do an if-else. The ternary above, put into if-else form, looks like this:
if (n <= m)
i < f; // left side of the ":"
else
i < ++f; // right side of the ":"
Let's break it down further:
i < f
This is doing a less-than comparison of i and f. So, depending on the individual values, you'll receive either a 0 (false) or a 1 (true).
So, in your for-loop, this will occur:
for (int i = 0; 1; i++) {}
// ^ <--- if comparison returns true
for (int i = 0; 0; i++) {}
// ^ <--- if comparison returns false
So, for your example, you'll need to find the value of f before the loop. You can use a ternary for that part, but only if you understand it. Otherwise, use another method to find f (the intended numerical value). Once you find it, then you can put i < f into the for-loop.
I have an assignment in which i have to create a console program in c++ that draws Hexagons in a given style. The problem i am having is; my For loops are never entered and i can't figure out why. here's the snippet of code I'm having trouble with.
void display()
{
int counter=0;//var that keeps track of the layer that is being drawn
for(int i=0;i>=size;i++)//spaces before first layer of hexagon
{
cout<<" ";
}
for (int k=0; k>size;k++)//top layer of hexagon
{
cout<<"_";
}
cout<<endl;//ends the first layer
for (counter; counter>=size-1;counter++)//outer loop for the top half that controls the size
{
for( int j=0;j>(size-counter);j++)//adds spaces before the shape
{
cout<<" ";
}
cout<<"/";
for( int p=0; p>(size+(counter*2));p++)//loop for the hexagon fill
{
cout<<fill;
}
cout<<"\\"<<endl;
}
for(counter;counter==0;counter--); //loop for bottom half of the hexagon
{
for( int j=0;j>(size-counter);j++)//adds spaces before the shape
{
cout<<" ";
}
cout<<"\\";
for( int p=0; p>(size+(counter*2));p++)//loop for the hexagon fill
{
cout<<fill;
}
cout<<"/"<<endl;
}
cout<<"\\";
for(int r=0; r>=size;r++){cout<<"_";}
cout<<"/"<<endl;
}
the 'Size' and 'fill' are selceted earlier in the program during my main()
I'm probably missing something very simple but I've been struggling with this for a while. Any help would be greatly appricated!
Your loops use > and start at 0. It seems you want < instead. For example
for(int i=0;i<size;i++)//spaces before first layer of hexagon
{
cout<<" ";
}
I am not sure what is the content of your size variable but it looks like you have got your loop conditions wrong:
for(int i=0;i>=size;i++)
probably should be:
for(int i=0;i<size;i++)
The same goes for other loops.
Assuming your size is a postive number, it works as per your condition.
Change the > conditojs to < in your conditions.
In your conditions, invert the > to <
< means inferior, you want to do a
for i = 0; if i < size; i++
You do
for i = 0 ; if i > size ; i ++
if size is superior to i (0) the loop will never trigger
Aren't all of your < and > reversed? Because
(int k=0; k>size;k++)
makes no sense to me.
for loops in C++ are while loops, not until loops.
C++ has only while loops (with the meaning of as long as):
for (int i=0; i<10; ++i)
....
int i=0;
while (i<10) {
....
++i;
}