n-queens | private repo , originally a project from Hack Reactor | Frontend Framework library
kandi X-RAY | n-queens Summary
kandi X-RAY | n-queens Summary
This is a copy of the work I did on a private repo, originally a project from Hack Reactor's curriculum. This project was worked on with a pair; it's representative of the kind of problems that I've tackled, but not of my solo work.
Support
Quality
Security
License
Reuse
Top functions reviewed by kandi - BETA
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample of n-queens
n-queens Key Features
n-queens Examples and Code Snippets
Community Discussions
Trending Discussions on n-queens
QUESTION
I'm arduously struggling my way through the N-queens problem in SICP (the book; I spent a few days on it -- last question here: Solving Eight-queens in scheme). Here is what I have for the helper functions:
...ANSWER
Answered 2021-Jun-12 at 09:35When you are doing the SICP problems, it would be most beneficial if you strive to adhere to the spirit of the question. You can determine the spirit from the context: the topics covered till the point you are in the book, any helper code given, the terminology used etc. Specifically, avoid using parts of the scheme language that have not yet been introduced; the focus is not on whether you can solve the problem, it is on how you solve it. If you have been provided helper code, try to use it to the extent you can.
SICP has a way of building complexity; it does not introduce a concept unless it has presented enough motivation and justification for it. The underlying theme of the book is simplification through abstraction, and in this particular section you are introduced to various higher order procedures -- abstractions like accumulate, map, filter, flatmap which operate on sequences/lists, to make your code more structured, compact and ultimately easier to reason about.
As illustrated in the opening of this section, you could very well avoid the use of such higher programming constructs and still have programs that run fine, but their (liberal) use results in more structured, readable, top-down style code. It draws parallels from the design of signal processing systems, and shows how we can take inspiration from it to add structure to our code: using procedures like map, filter etc. compartmentalize our code's logic, not only making it look more hygienic but also more comprehensible.
If you prematurely use techniques which don't come until later in the book, you will be missing out on many key learnings which the authors intend for you from the present section. You need to shed the urge to think in an imperative way. Using set! is not a good way to do things in scheme, until it is. SICP forces you down a 'difficult' path by making you think in a functional manner for a reason -- it is for making your thinking (and code) elegant and 'clean'.
Just imagine how much more difficult it would be to reason about code which generates a tree recursive process, wherein each (child) function call is mutating the parameters of the function. Also, as I mentioned in the comments, assignment places additional burden upon the programmers (and on those who read their code) by making the order of the expressions have a bearing on the results of the computation, so it is harder to verify that the code does what is intended.
Edit: I just wanted to add a couple of points which I feel would add a bit more insight:
- Your code using set! is not wrong (or even very inelegant), it is just that in doing so, you are being very explicit in telling what you are doing. Iteration also reduces the elegance a bit in addition to being bottom up -- it is generally harder to think bottom up.
- I feel that teaching to do things recursively where possible is one of the aims of the book. You will find that recursion is a crucial technique, the use of which is inevitable throughout the book. For instance, in chapter 4, you will be writing evaluators (interpreters) where the authors evaluate the expressions recursively. Even much earlier, in section 2.3, there is the symbolic differentiation problem which is also an exercise in recursive evaluation of expressions. So even though you solved the problem imperatively (using set!, begin) and bottom-up iteration the first time, it is not the right way, as far as the problem statement is concerned.
Having said all this, here is my code for this problem (for all the structure and readability imparted by FP, comments are still indispensable):
QUESTION
I am a 16 years old guy and recently I was solving n-queens problem but my code is giving different answers.Basically my code's intention is to put a queen on a specific row and then mark the left diagonals as well as right diagonals and columns marked as danger.And then placing other queens on the other positions where is no danger.Please explain briefly what is the problem in my code.
...ANSWER
Answered 2021-May-23 at 13:33Without digging into too deep you have a fundamental problem:
You mark all further fields reachable from current one with your current recursion depth and reset all of these unconditionally to -1. So you clear out the marks yet incomplete previous recursions, too.
Without digging too deep into the code I noticed that you do not mark the columns.
However, introducing that, you will risk illegally overwriting marks set in previous columns:
QUESTION
I'm working on parallelizing the n-queens problem using OpenMP, but my sequential program is just as fast. I've been trying to use num_threads
, but I don't think I am doing it correctly.
Can someone look at my code and tell me what I am doing wrong or give me some pointers? Thank you.
Here is my parallel program:
...ANSWER
Answered 2021-Apr-18 at 11:05More than 95% of the execution time of your program is spent in printing strings in the console and this operation is put in a critical section so that only one thread can do it at a time. The overhead of the IO operations and the critical section grows with the number of threads used. Consequently, the sequential execution time is better than the parallel one.
Actually, to be more precise, it is not the printing that is slow, but the synchronization with the console caused by std::endl
which implicitly performs a std::flush
, and the string formatting. Thus, to fix that, you can prepare a thread-local string in parallel (std::ostringstream
is good for that). The local string can then be appended to a big global one and its content can be printed in the main thread sequentially (to prevent any additional overhead caused by parallel IOs) and outside the timed section.
Besides this, you have 11 tasks and you create 30 threads for that in your code while you probably have less than 30 cores (or even 30 hardware threads). Creating too many threads is costly (mainly due to thread-preemption/scheduling). Moreover, specifying the number of threads in the program is generally a bad practice. Please use the portable environment variable OMP_NUM_THREADS
for that.
Here is the code tacking into account the above remarks:
QUESTION
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
https://leetcode.com/problems/n-queens-ii/
My solution:
...ANSWER
Answered 2021-Jan-07 at 11:09Ok, one thing I missed was that each row must have a queen. Very important observation. gen method has to be modified like this:
QUESTION
Background Information: I solved the N-Queens problem with the C# algorithm below, which returns the total number of solutions given the board of size n x n. It works, but I do not understand why this would be O(n!) time complexity, or if it is a different time complexity. I am also unsure of the space used in the recursion stack (but am aware of the extra space used in the boolean jagged array). I cannot seem to wrap my mind around understanding the time and space complexity of such solutions. Having this understanding would be especially useful during technical interviews, for complexity analysis without the ability to run code.
Preliminary Investigation: I have read several SO posts where the author directly asks the community to provide the time and space complexity of their algorithms. Rather than doing the same and asking for the quick and easy answers, I would like to understand how to calculate the time and space complexity of backtracking algorithms so that I can do so moving forward.
I have also read in numerous locations within and outside of SO that generally, recursive backtracking algorithms are O(n!) time complexity since at each of the n iterations, you look at one less item: n, then n - 1, then n - 2, ... 1. However, I have not found any explanation as to why this is the case. I also have not found any explanation for the space complexity of such algorithms.
Question: Can someone please explain the step-by-step problem-solving approach to identify time and space complexities of recursive backtracking algorithms such as these?
...ANSWER
Answered 2021-Jan-07 at 15:51First of all, it's definitely not true that recursive backtracking algorithms are all in O(n!)
: of course it depends on the algorithm, and it could well be worse. Having said that, the general approach is to write down a recurrence relation for the time complexity T(n)
, and then try to solve it or at least characterize its asymptotic behaviour.
Are we interested in the worst-case, best-case or average-case? What are the input parameters?
In this example, let us assume we want to analyze the worst-case behaviour, and the relevant input parameter is n
in the Solve
method.
In recursive algorithms, it is useful (though not always possible) to find a parameter that starts off with the value of the input parameter and then decreases with every recursive call until it reaches the base case.
In this example, we can define k = n - row
. So with every recursive call, k
is decremented starting from n
down to 0.
No we look at the code, strip it down to just the relevant bits and annotate it with complexities.
We can boil your example down to the following:
QUESTION
I have been playing around with a simple n-queens model in MiniZinc:
...ANSWER
Answered 2020-Jun-28 at 01:41Those values depend of the search strategy, some times you cannot avoid a leaf node because it hasn't been pruned, that means, nothing before it told the solver that that node was going to be a failure, modeling it in a different way can prevent some failures, and can also prevent suboptimal solutions in the case of optimization problems.
These are the first three nodes that got evaluated on the search tree of the default search strategy of minizinc, I labeled them in the image of the Search Tree in the order they got evaluated, and the 4 and 5 to show the arrival to a feasible solution.
In the the blue dots are nodes where there is still uncertainty, the red squares are failures, white dots are non evaluated nodes, large triangles are whole branches where the search only resulted in failures, the green diamond means a feasible solution, and orange diamonds mean non-best-but-feasible solution (only in optimization problems).
The explanation of each of the labeled nodes is
0: Root node: all variables are un assignedNothing has happened, these are all the decision variables and their full domains
queens = array1d(1..8, [[1..8], [1..8], [1..8], [1..8], [1..8], [1..8], [1..8], [1..8]]);
Then it picked the smallest value in the domain of the last variable and made the first split, the solver thought either queens[8] = 1
(left child of the root) or queens[8] = [2..8]
(right child of the root), it will first evaluate queens[8] = 1
and that bring the first node to existence,
queens = array1d(1..8, [[2..7], {2..6,8}, {2..5,7..8}, {2..4,6..8}, {2..3,5..8}, {2,4..8}, [3..8], 1]);
where the decision queens[8] = 1
already propagated to the other variables and removed values from its domains.
Then it again splits at queens[7]
, this is the left child node where queens[7] = 3
, the minimum value in the domain of that variable, and the propagation of that decision to the other variables.
queens = array1d(1..8, [{2,4..7}, {2,4..6}, {2,4..5,8}, {2,4,7..8}, {2,6..8}, [5..8], 3, 1]);
In hindsight (more like cheating by looking at the image of the Search Tree) we know that this whole branch of the search will result in failures, but we cannot know that while searching, because there is still uncertainty in some variables, to know that we would have to evaluate all of the possibilities, which are possibly feasible, that might happen or not, hopefully we will find a satisfying solution before that, but before carry on with the search, notice that already some some pruning got done in the form of nodes that won't exist, for example queens[4]
can only take the values 2,4,7,8
at this point, and we haven't made any decision on it, its just the solver eliminating values from the variable that it knows will certainly result in failures, if we where making a brute force search this variable would have the same domain as in the root node [1..8]
because we haven't made a decision on it yet, so we are making a smarter search by propagating the constraints.
Carrying on with the same strategy it makes a split for queens[6]
, this time the minimum value queens[6] = 5
, when propagating to the undecided variables, but there is no solution that satisfies all the constraints (here it gave the value 8 to two queens), so this is a dead end and must backtrack.
queens = array1d(1..8, [7, 2, 4, 8, 8, 5, 3, 1]);
---> Failure
So the very first three nodes of the search lead to a failure.
The search continues like that, since the choice for queens[6] = 5
caused a failure it goes to the next value queens[6] = [6..8]
, that search also results in the failures that are encircled in red in the image of the Search Tree.
As you can probably guess by now the search strategy is something like go in the order of the variables
and split the domain of the variables by picking the smallest value available and put the rest of the domain in another node
, this in minizinc search annotations are called input_order
and indomain_min
.
Now we fast forward the search to the node labeled 4.
4: Prelude to a solution: are we there yet?Here you can see that queens[8] = 1
(remains the same), queens[7] = 5
while in the node 2 it was queens[7] = 3
, that means that all the possibilities where queens[8] = 1
and queens[7] = [3..4]
where either evaluated or pruned, but all lead to failures.
queens = array1d(1..8, [{2,4,6..7}, {2..3,6}, {2..4,7}, {3..4,7}, {2,6}, 8, 5, 1]);
Then this node spited into queens[6] = 2
(left child) which lead to more failures and queens[6] = 6
(right child)
queens[2] = 6
propagated, and the result satisfied all the constraints, so we have a solution and we stop the search.
queens = array1d(1..8, [4, 2, 7, 3, 6, 8, 5, 1]);
Arriving to the solution only required 47 nodes of the gigantic Whole Search Tree, the area inside the blue line is the search tree is the Search Tree where nodes labeled 0,1,2,3,4,5 are, it is gigantic even pruned for this relatively small instance of 8 decision variables of cardinality 8 with a global constraint which certainly reduces the span of the search tree by a lot since it communicates the domains of the variables between each other much more effectively than the constraint store of the solver. The whole search tree only has 723 nodes in total (nodes and leafs) where only 362 are leafs, while the brute force search could generate all the possible 8^8 leaf nodes directly (again, it might not, but it could), thats a search space of 16.777.216 possibilities (its like 8 octal digits since its 8 variables with cardinality of domain 8), it is a big saving when you compare it, of the 16.777.216 to the solver only 362 made some sense, and 92 where feasible, its less than 0.0001% of the combinations of the whole search space you would face by, for example, generating at random a solution by generating 8 random digits in the range [1..8] and evaluating its feasibility afterwards, talk about a needle in a haystack.
Pruning basically means to reduce the search space, anything better than the evaluation of ALL the combinations, even by removing one single possibility is considered a pruned search space. Since this was a satisfaction problem rather than an optimization one, the pruning is just to remove unfeasible values from the domain of the variables.
In the optimization problems there are two types of pruning, the satisfaction pruning like before, eliminating imposible solutions, and the pruning done by the bounds of the objective function, when the bounds of the objective function can be determined before all the variables reached a value and be it is determined to be "worst" than the current "best" value found so far (i.e. in a minimization optimization the smallest value the objective could take in a branch is larger than the smallest value found so far in a feasible solution) you can prune that branch, which surely contains feasible (but not as good) solutions as well as unfeasible solutions, and save some work, also you still have to prune or evaluate all the tree if you want to find the optimal solution and prove that it is optimal.
To explore search trees like the ones of the images you can run your code with the gecode-gist
solver in the minizinc IDE, or use minizinc --Solver gecode-gist
in the command line, upon double clicking on one of the nodes you will see the state of the decision variables just like the ones in this post.
And even further use solve :: int_search( pos, varChoise, valChoise, complete) satisfy;
to test this different search strategies
QUESTION
I was having a go at the standard N-Queens problem for an upcoming interview. I have tried to dry run my code and it seems to work fine. I can't spot the error in my code.
I am traversing it column by column, and using backtracking to recur back from an incorrect path. Can anyone help me with why this doesn't give me the desired output (details below)?
Here's the problem statement
...ANSWER
Answered 2020-Jun-23 at 19:54The bool flag
variable (used to check if placing a queen at (row, col)
would intersect with any existing queens in curr
) is currently being re-used across rows.
So, if you place the line bool flag=false;
just above for(int i=0; i, it should produce the correct output for your test case.
Other notes:
- It might be easier to create a separate function
bool does_intersect(const vector& cur, int row, int col)
to check the queen intersection condition so that the bool flag
variable isn't needed.
- The
if(col==0){
condition can be removed since it doesn't do anything that the else
part cannot already handle.
QUESTION
The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. I have solved this program earlier, but am trying to rework my code to mirror that which I used to fashion a sudoku solver. I cannot seem to find the logical error but when I run the code, nothing prints. My program is attached below and if anyone could find my error that would be very helpful!
...ANSWER
Answered 2020-Apr-08 at 06:47Try this
QUESTION
I recently discovered the guard
function associated with the Control.Monad
module (defined here) and it seemed to be a perfect function to solve a common programming challenge: the eight queens problem. I came up with this solution:
ANSWER
Answered 2020-Jan-12 at 11:22You can recurse while keeping around the list of already-placed queens:
QUESTION
While trying to solve the n-queens problem in c++. I came across this error where I would get the correct answer but when returning the array pointer, I end up getting garbage numbers instead of my answer. The weird part about this is that I use recursion to solve the problem and I only get garbage numbers when the recursion gets used (even though it correctly passes through the recursion). The array is completely correct before returning it.
...ANSWER
Answered 2019-Dec-11 at 22:54Your recursive calls don't return anything. With all warnings on, you should be seeing something about "not all control paths return a value". Change your recursive calls to
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install n-queens
Support
Reuse Trending Solutions
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesStay Updated
Subscribe to our newsletter for trending solutions and developer bootcamps
Share this Page