#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
ifstream f("damesah.in");
ofstream g("damesah.out");
int st[20], n,nrSol=0;
void afisare() {
for (int i = 1; i <= n; ++i) {
g << st[i] << " ";
}
g << "\n";
}
int valid(int k) {
for (int i = 1; i < k; ++i) {
if (st[k] == st[i] || abs(st[k]-st[i]) == abs(k-i))
return 0;
}
return 1;
}
void BK(int k) {
for (int i = 1; i <= n; ++i) {
st[k] = i;
if (valid(k)) {
if (k == n) {
++nrSol;
if(nrSol == 1)
afisare();
}
else
BK(k + 1);
}
}
}
int main()
{
f >> n;
BK(1);
g << nrSol << "\n";
return 0;
}
This is the code I have made to solve the N-Queen problem using backtracking , if you do not know the problem , here it is : The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. A queen is attacking another one if they are on the same column, row or on the same diagonal.
If we insert 4, the output will show only the first solution, then the number of solutions on the second row :
2 4 1 3
2
I want to optimise this algorithm using one more array which will store the row the diagonal and the column used by the queen so the complexity of the validation will be O(1), but I do not know how to implement it.
Related
ive got the below code to print a pattern (attached below). However i'd like to just use one loop
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
cout<<"*";
}
for(int j=1;j<=n-i;j++){
if(j%2!=0){
cout<<"_";
}else{
cout<<".";
}
}
cout<<endl;
}
for(int i=1;i<n;i++){
for(int j=1;j<=n-i;j++){
cout<<"*";
}
for(int j=1;j<=i;j++){
if(j%2==0){
cout<<".";
}else{
cout<<"_";
}
}
cout<<endl;
}
}
when n = 5, heres the output.
*_._.
**_._
***_.
****_
*****
****_
***_.
**_._
*_._.
how do i just make this into one single loop
Try this and see how it does what you want to understand the step you did not find on your own:
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n*2-1; i++) {
if (i <= n)
{
for (int j = 1; j <= i; j++) {
cout << "*";
}
for (int j = 1; j <= n - i; j++) {
if (j % 2 != 0) {
cout << "_";
}
else {
cout << ".";
}
}
cout << endl;
}
else
{
for (int j = 1; j <= n*2 - i; j++) {
cout << "*";
}
for (int j = 1; j <= i-n; j++) {
if (j % 2 == 0) {
cout << ".";
}
else {
cout << "_";
}
}
cout << endl;
}
}
}
I'd like to just use one loop.
I'll take it literally and show a starting point for a possible solution.
// Let's start by figuring out some dimensions.
int n;
std::cin >> n;
int height = 2 * n - 1;
int area = n * height;
// Now we'll print the "rectangle", one piece at a time.
for (int i = 0; i < area; ++i)
{ // ^^^^^^^^
// Extract the coordinates of the char to be printed.
int x = i % n;
int y = i / n;
// Assign a symbol, based on such coordinates.
if ( x <= y and x <= height - y - 1 )
{ // ^^^^^^ ^^^^^^^^^^^^^^^^^^^ Those are the diagonals.
std::cout << '*'; // This prints correctly the triangle on the left...
}
else
{
std::cout << '_'; // <--- But of course, something else should done here.
}
// End of row.
if ( x == n - 1 )
std::cout << '\n';
}
If you look at the pattern, then you can see a sort of "triangles". And this already gives a hint for the solution. Use a triangle function.
Please read about it here.
Then you will notice that always the "aboslute"-function, in C++ std::abs, is involved.
But first of all, it is easily visible that the number rows to print is always the width of a triangle * 2.
And the number of charcters in the pattern, can be calculated by applying the triangle function. Example for width 5:
Number of stars number of dashdot
Row width-abs(row-width) abs(row-width)
1 1 4
2 2 3
3 3 2
4 4 1
5 5 0
6 4 1
7 3 2
8 2 3
9 1 4
And this can be implemented easily now.
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std::string_literals;
int main() {
// Get the max width of the pattern and perform a short input validation
int maxWidth{};
if ((std::cin >> maxWidth) and (maxWidth > 0)) {
// The number of rows for the pattern is dependent on the width. It is a simple relation
const int numberOfRows = 2 * maxWidth;
// Show all rows
for (int row = 1; row < numberOfRows; ++row) {
// Use triangle formular to create star pattern
std::string starPattern(maxWidth - std::abs(row - maxWidth), '*');
// Create dashDot pattern
std::string ddp(std::abs(row - maxWidth), '\0');
std::generate(ddp.begin(), ddp.end(), [i = 0]() mutable { return i++ % 2 ? '.' : '_'; });
// Show output
std::cout << (starPattern+ddp) << '\n';
}
}
else std::cout << "\n*** Error: Invalid input\n\n";
}
Of course you can also create the whole pattern wit std::generate.
Maybe it is too complex for now.
And less understandable.
See:
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <vector>
int main() {
// Get the max width of the pattern and perform a short input validation
if (int width{}; (std::cin >> width) and (width > 0)) {
std::vector<std::string> row(2 * width - 1);
std::for_each(row.begin(), row.end(), [&, r = 1](std::string& s) mutable {
s = std::string(width - std::abs(r - width), '*');
std::string ddp(std::abs(r++ - width),'\0');
std::generate(ddp.begin(), ddp.end(), [&, i = 0]() mutable{ return i++ % 2 ? '.' : '_'; });
s += ddp; std::cout << s << '\n'; });
}
else std::cout << "\n*** Error: Invalid input\n\n";
}
I have to make an i by j rectangle using while loops....
so far this is as far I got.
#include <iostream>
using namespace std;
void stars(int, int);
int main()
{
int i, j;
cin >> i >> j;
stars(i, j);
return 0;
}
void stars(int i, int j)
{
while (j >= 0)
{
while (i >= 1)
{
cout << "*";
i = i - 1;
}
j = j - 1;
}
}
it shoots out one row of 'i' asterisks.
I (j-1) more rows....
There are 2 things wrong with your stars code:
You need to somehow go to the new line after your row of asterisks is complete
If you decrement i and never restore it to its original value after the 1st row no more asterisks will be printed
You could try something like this:
void stars(int i, int j)
{
while (j-- > 0)
{
int k = i;
while (k-- > 0)
cout << "*";
cout << endl;
}
}
I'm coding a recursive algorithm to take a user input N and make a N x N grid where the same number does not appear twice on either a row or a column. Almost everything's working, and duplicates don't appear in columns, but I'm having trouble getting rows working.
My code for checking duplicates in rows is the function noRowDuplicates. Duplicates are still appearing, and occasionally it'll throw a segmentation fault, but I'm not sure why.
Thanks in advance for the help!
// Author: Eric Benjamin
// This problem was solved using recursion. fill() is the recursive function.
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
void fillOptions();
void fill(int arrayPosition);
int inputNum;
int gridSize;
int *grid;
int allOptionsSize = 0;
int *allOptions;
int main() {
cout << "Please enter a number!" << endl;
cin >> inputNum;
gridSize = inputNum * inputNum;
grid = new int[gridSize];
allOptions = new int[inputNum];
for (int i = 0; i < inputNum; i++) {
allOptions[i] = i + 1;
allOptionsSize++;
}
srand((unsigned)time(0));
fill(0);
delete[] grid;
delete[] allOptions;
return 0;
}
bool noColumnDuplicates(int arrPosition, int valueToCheck) {
for (int i = 1; i < inputNum; i++) {
if (arrPosition - (inputNum * i) >= 0) {
if (grid[arrPosition - (inputNum * i)] == valueToCheck) {
return false;
}
}
}
return true;
}
bool noRowDuplicates(int arrPosition, int valueToCheck) {
int rowPosition = arrPosition % inputNum; // 0 to num - 1
if (rowPosition > 0) {
for (int p = 1; p < rowPosition; p++) {
if (grid[arrPosition - p] == valueToCheck) {
return false;
}
}
}
return true;
}
void fill(int arrayPosition) {
if (arrayPosition < gridSize) {
int randomPosition = rand() % allOptionsSize;
grid[arrayPosition] = allOptions[randomPosition];
if (noColumnDuplicates(arrayPosition, grid[arrayPosition])) {
if (noRowDuplicates(arrayPosition, grid[arrayPosition])) {
if (arrayPosition % inputNum == 0) {
cout << endl;
}
cout << grid[arrayPosition] << " ";
fill(arrayPosition + 1);
} else {
fill (arrayPosition);
}
} else {
fill(arrayPosition);
}
}
}
noRowDuplicates never tests the first element of a row, which makes sense when you are trying to fill the first element of a row, but not any other time.
Here I have this code that sorts a tournament structure like array in descending order. It sorts all but one number and always returns a -1 as the lowest integer it sorts, I have read through this code multiple times and I can't seem to figure out why it's not sorting properly, I'm not sure if it's just missing my eyes or if there is a small typo somewhere.
#include <iostream>
#include <cmath>
using namespace std;
int maxi(int i, int j)
{
if (i > j) return(i);
else return(j);
}
int mini(int i, int j)
{
if (i < j) return(i);
else return (j);
}
int buildtourn(int tourn[], int n)
{
int min1=0, a;
//Compute tournament structure
for (int i=2*n-2; i>1; i=i-2)
{
tourn[i/2] = maxi(tourn[i], tourn[i+1]);
a=mini(tourn[i], tourn[i+1]);
if (min1>a) min1=a;
}
return min1;
}
int getnext(int tourn[], int n, int low)
{
int i = 2;
//Part 1 - downward traversal
while (i <= 2*n-1)
{
if (tourn[i]>tourn[i+1])
{
tourn[i]=low;
i=2*i;
}
else
{
tourn[i+1]=low;
i=2*(i+1);
}
}
//Part 2 - upward traversal
for (i = i/2; i>1; i=i/2)
{
if (i%2==0) tourn[i/2]=maxi(tourn[i],tourn[i+1]); // go to the right of i
else tourn[i/2]=maxi(tourn[i], tourn[i-1]); // to the left of i
}
return 0;
}
int main()
{
int tourn[100], n, i, low;
//Read
cout << "Give n :" ;
cin >> n;
cout<< "Enter the integers to be sorted : " << endl;
for (i=n; i<=2*n-1; i++)
cin >> tourn[i];
//build tournament
low=buildtourn(tourn,n)-1;
//Sorting
cout << " Sorted items are : " << endl;
for(i=1; i<=n; i++)
{
cout << tourn[i] << '\t';
getnext(tourn,n,low);
}
cout << '\n';
return 0;
}
I believe the error lies solely in my function that builds the tournament structure but, i'm not quite sure if i'm looking in the wrong place.
int buildtourn(int tourn[], int n)
{
int min1=0, a;
//Compute tournament structure
for (int i=2*n-2; i>1; i=i-2)
{
tourn[i/2] = maxi(tourn[i], tourn[i+1]);
a=mini(tourn[i], tourn[i+1]);
if (min1>a) min1=a;
}
return min1;
}
Thank you in advance for any help and If I need to add anymore details to this problem please let me know in the comments.
EDIT: This is a link to view the output i am receiving.
http://imgur.com/a/KNDO8
EDIT 2: If i were to use the numbers 20 14 1 3 8 to be sorted, it would sort them as 20 8 1 3 -1
In mini maxi functions, replace < and > by <= and >=
I am trying to make a program that recieves numbers from the user, and then rearranges the from least to greatest. I am using vectors (which I just learned about), and it gives me a subscript out of range error. I am not able to find what part of the code gives me this error, so hopefully someone more knowledgeable on vector and c++ can find it:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void order(int a, int b);
void orderRev(int a, int b);
int main() {
vector<int> num;
bool going = true;
do {
cout << "\nEnter a number or type 'x' to order:" << endl;
string reply;
getline(cin, reply);
if (reply != "x") {
int a = atoi(reply.c_str());
num.push_back(a);
cout << "\nYou currently have " << num.size() << " numbers added." << endl;
}
else {
going = false;
}
} while (going);
for (int i = 0; i < num.size(); i++) {
order(num[i], num[i + 1]);
}
for (int i = num.size() - 1; i >= 0; i--) {
orderRev(num[i + 1], num[i]);
}
cout << "\nThe number you entered in order from least to greatest are: " << endl;
for (int i = 0; i < num.size(); i++) {
cout << num[i] << " ";
}
void order(int a, int b) {
if (a > b) {
int c = b;
b = a;
a = c;
}
}
void orderRev(int a, int b) {
if (a < b) {
int c = b;
b = a;
a = c;
}
}
Fix these lines to this:
// added the -1 as this will now go up to the 2nd to last element
// for `n`, and the last element for `n+1`
for (int i = 0; i < num.size() - 1; i++) {
order(num[i], num[i + 1]);
}
// changed the starting number to size -2 (for the same reasoning)
for (int i = num.size() - 2; i >= 0; i--) {
orderRev(num[i + 1], num[i]);
}
Why does this need to be this way? Think about how indices in C++ work. They are zero-indexed! That means that if you want both the element and the one in front of it, you must go up to the size of the vector minus 1. Hence, for a vector of 10 items (size 10), at i == 9 your code will work like this:
for (int i = 0; i < num.size(); i++) {
// i = 9
order(num[9], num[9+1]);// index 10 does not exist! Hence, you really need to go up to num.size() - 1!
}
Vectors index start with 0. index will be 0 to n-1 , if you use num[i + 1] it will exceed the vector size, if you don't check in loop condition.
Your code has more than one flaw. The output will be same as the input , hint: know the difference between pass by reference and pass by value and after that check some sorting algorithms.