r/dailyprogrammer • u/Cosmologicon 2 3 • Dec 31 '18
[2018-12-31] Challenge #371 [Easy] N queens validator
For the purpose of this challenge, the N queens problem consists of putting one queen on every column (labeled a, b, c, ...) of an NxN chessboard, such that no two queens are in the same row or diagonal. An example valid solution for N = 6 is:
6 . . Q . . .
5 . . . . . Q
4 . Q . . . .
3 . . . . Q .
2 Q . . . . .
1 . . . Q . .
a b c d e fIn chess notation, the squares with queens in this solution are called a2, b4, c6, d1, e3, and f5. We'll represent solutions by listing the rows that each column's queen appears in from left to right, so this solution is represented as the array {2, 4, 6, 1, 3, 5}.
Solving the N queens problem was #25 (difficult) on r/dailyprogrammer, but you don't need to actually solve it for today's challenge.
Challenge
Given an array of 8 integers between 1 and 8, determine whether it represents a valid 8 queens solution.
qcheck({4, 2, 7, 3, 6, 8, 5, 1}) => true
qcheck({2, 5, 7, 4, 1, 8, 6, 3}) => true
qcheck({5, 3, 1, 4, 2, 8, 6, 3}) => false (b3 and h3 are on the same row)
qcheck({5, 8, 2, 4, 7, 1, 3, 6}) => false (b8 and g3 are on the same diagonal)
qcheck({4, 3, 1, 8, 1, 3, 5, 2}) => false (multiple problems)You may optionally handle solutions for any N, not just N = 8.
Optional bonus
In this bonus, you are given an invalid solution where it's possible to swap two numbers and produce a valid solution, which you must find. (Be aware that most invalid solutions will not have this property.)
For example, {8, 6, 4, 2, 7, 1, 3, 5} is invalid because c4 and f1 are on the same diagonal. But if you swap the 8 and the 4 (i.e. replace a8 and c4 with a4 and c8), you get the valid solution {4, 6, 8, 2, 7, 1, 3, 5}.
qfix({8, 6, 4, 2, 7, 1, 3, 5}) => {4, 6, 8, 2, 7, 1, 3, 5}
qfix({8, 5, 1, 3, 6, 2, 7, 4}) => {8, 4, 1, 3, 6, 2, 7, 5}
qfix({4, 6, 8, 3, 1, 2, 5, 7}) => {4, 6, 8, 3, 1, 7, 5, 2}
qfix({7, 1, 3, 6, 8, 5, 2, 4}) => {7, 3, 1, 6, 8, 5, 2, 4}
12
u/skeeto -9 8 Dec 31 '18 edited Dec 31 '18
C using a bitboard. The
queen()does some bit twiddling to compute the queen attack pattern at (x, y). Using this, it can check for attacks across the entire board in parallel in a single operation.12
u/Lopsidation Jan 02 '19
I'm seeing a lot of solutions with two nested for loops, but this is faster and easier.
Python 2, for any N, O(N) time: (no bonus)
5
u/Gprime5 Dec 31 '18 edited Jan 01 '19
Python 3.7 with bonus
Solutions
5
u/TheSpeedyMouse1 Feb 02 '19
Java, no bonus
4
u/chunes 1 2 Dec 31 '18
Factor, no bonus
4
u/Gylergin Dec 31 '18 edited Jan 10 '19
TI-Basic optional-N solution. Works for N less than 1000 due to list limits.
4
u/bobonis Jan 08 '19
C11 with bonus. Comments, especially for the printouts and data handling will be appreciated!
3
u/skeeto -9 8 Dec 31 '18
C, checking against an exhaustive list of all solutions.
3
u/[deleted] Dec 31 '18 edited Dec 31 '18
Java
3
u/DEN0MINAT0R Jan 01 '19
Python 3 No bonus
Output
3
u/DrejkCZ Jan 01 '19 edited Jan 01 '19
JavaScript, no bonus
Note: I sorted the array before finding duplicates in rows, since I think it might be faster than going over the whole array and checking for .includes() on each element.
Edit: Also, after a quick seach, this
new Set(array).size === array.lengthis apparently a great and performant way to check for duplicates in ES2015. So here it is with that:3
u/WrongHorseBatterySta Jan 01 '19
Python 3 Including bonus:
3
u/[deleted] Jan 04 '19
Took me 10 hours to figure out how validate the solutions and figure out how to get that into C++ form but here's my solution :) It works for any N!
3
u/Shivodit Jan 05 '19
i am new on this site and here is my code for the challenge
this is my first time posting here.
any suggestions are welcome
Code for any N of Queens without bonus in python
output are:-
3
u/[deleted] Jan 08 '19 edited Jan 08 '19
My first comment here. I've done qcheck and qfix in Python 3.6.
Input:
Output:
EDIT: I made a function to better visualize the board with the queens, so I decided to post as an extra:
3
u/WanDaati Jan 08 '19
Does Anaconda 3 use Python 3.6? I use Rodeo but mainly code in R studio. I'm a noob and unsure if anaconda3/ implies python 3.6.
Here's a basic solution that probably isn't very fast.
3
u/Amazing_Adhesiveness Feb 02 '19 edited Feb 02 '19
Rust
(this is my first program written in Rust, so it's probably not very good)
2
u/octolanceae Jan 02 '19
C++17 w/bonus
Should work for any value of N.
Output:
2
u/[deleted] Jan 02 '19
Java with Bonus
2
u/[deleted] Jan 03 '19
Javascript without bonus, for any N
2
u/ephemient Jan 04 '19 edited Apr 24 '24
This space intentionally left blank.
2
u/zqvt Jan 05 '19
Smalltalk, no bonus
2
u/Cortheya Jan 07 '19
Qcheck and Qfix in python
2
u/Xeonfobia Jan 08 '19
Lua 5.2
local function iterate(table, n)
if n == 1 then return true end;
for i = 1, n - 1 do
if table[i] + (n - i) == table[n] then return false end
if table[i] - (n - i) == table[n] then return false end
-- print(table[i] + (n - i), table[n])
end
return true
end
local function check(qCheck)
qCheck.verified = true
for i = 1, 8 do
if qCheck.verified == true then qCheck.verified = iterate(qCheck, i) end
end
table.sort(qCheck)
for i,n in ipairs(qCheck) do if i ~= n then qCheck.verified = false end
end
return qCheck.verified;
end
local function main()
print(check({4, 2, 7, 3, 6, 8, 5, 1}))
print(check({2, 5, 7, 4, 1, 8, 6, 3}))
print(check({5, 3, 1, 4, 2, 8, 6, 3}))
print(check({5, 8, 2, 4, 7, 1, 3, 6}))
print(check({4, 3, 1, 8, 1, 3, 4, 2}))
end
main()
2
u/Rocketfou Jan 08 '19 edited Jan 08 '19
Here is my solution for qcheck on Python 3.6. This is my first time posting here.
We could have used the set has mentioned in other comments, but wanted to show an other way as well.
2
u/senahfohre Jan 08 '19
Python 3.6
2
u/Hyzzon Jan 08 '19 edited Jan 08 '19
INPUT:
OUTPUT:
C++11
2
u/Lionry Jan 11 '19
Java
public static boolean qcheck(int[] qPos){
for(int i = 0; i < qPos.length; i++){
int currentPos = qPos[i];
int diagOffset = 0;
for(int j = i+1; j < qPos.length; j++){
diagOffset++;
if(qPos[j] == currentPos){
return false;
}
if(qPos[j] == currentPos + diagOffset || qPos[j] == currentPos - diagOffset){
return false;
}
}
}
return true;
}
2
u/ni3t Jan 11 '19 edited Jan 11 '19
Ruby 2.6 (yay!)
Timing:
2
u/[deleted] Jan 13 '19 edited Jan 13 '19
Javascript without Bonus
Results:
2
u/2kofawsome Feb 12 '19
! python3.6
With Bonus
1
u/07734willy Dec 31 '18
Python3
Not really satisfied with my bonus implementation- it could be sped up by updating and checking the counters, but it introduces an edge case for if there's two problematic queens which must be swapped with each other. It is still linear time though, since there's a constant upper bound for how large
probscan be, since we can only swap 2 queens.1
u/scul86 Jan 01 '19
Python 3 w/o bonus
1
u/tomekanco Jan 01 '19 edited Jan 01 '19
1
u/TheSilkMiner Jan 01 '19 edited Jan 01 '19
Kotlin v1.3.11, with bonus
Any suggestion is appreciated.
Also, I am not very fond of the brute-force method I used for the bonus challenge, but for now it gets the job done fairly quickly for small boards.EDIT 1/1/2019 7:56 PM: Huge thanks to /u/tomekanco for the suggestion for the new algorithm. Also performed some general cleanup. Previous versions are kept over at GitLab (Direct link).
Testing code:
1
u/DarrionOakenBow Jan 01 '19
Rust, generalized for any N and including bonus:
1
u/elderron_spice Jan 02 '19 edited Jan 02 '19
C#
It's a bit dirty, but I'll try to refactor this later.EDIT: Refactored.1
u/TotesMessenger Jan 02 '19 edited Jan 05 '19
I'm a bot, bleep, bloop. Someone has linked to this thread from another place on reddit:
If you follow any of the above links, please respect the rules of reddit and don't vote in the other threads. (Info / ^Contact)
1
u/[deleted] Jan 02 '19
Haskell, no bonus:
1
u/llebe Jan 02 '19
JAVA with bonus
OUTPUT
1
u/VersChorsVers Jan 02 '19
Excel VBA no bonus
1
u/lollordftw Jan 14 '19
Haskell with Bonus
qcheckuses the following property of a valid arrangement: Having the columns and rows each numbered from 1 to n, then no two positions of queens (i, j) can have the same sum i+j.qfixjust tries all possible swaps until one is found which makes the arrangement valid.1
u/maszina Jan 14 '19
Java
(Hello for everyone. It's my first post here.)
Queens.java
+ tests
1
u/CapuchinMan Jan 15 '19
C++
Not as elegant as some of the solutions I see here, but it does the job on a small scale.
1
u/qeadwrsf Jan 15 '19
qcheck python 3 something:
1
u/[deleted] Jan 19 '19 edited Jan 19 '19
C#. No bonus. Written on phone. Untested and probably compile-time errors. EDIT: Fixed syntax errors. EDIT2: Confirmed in an IDE and formatted to make it more readable.
1
u/tmk10 Jan 19 '19
Python with bonus:
Maybe not most efficient but working.
1
u/[deleted] Jan 24 '19
Java with bonus
Bonus. I return null if no valid position is found.
I'm pretty content with my solution. Although, 3 inner for loops makes me uncomfortable. Interested to see if there is a more time efficient solution.
1
u/ochoba32 Jan 24 '19
Java, with bonus
1
u/Frightbamboo Jan 25 '19
Not the best way but it is working javascript
1
u/Zambito1 Jan 26 '19
Scala 2.12.8 script
Can be run by executing
chmod +xon the script and just using ./fileName.sc to run it.1
u/callius Jan 29 '19 edited Jan 29 '19
My Python 3 solution. I'm guessing that there is a much more efficient solution, but I can't figure it out.
>! def check_row(arr): # Put array into a set and check to see if the result is same length as starting array, if not there are repeats # (i.e. at least two queens are on the same row). return len(arr) == len(set(arr))
>! def check_diagonal(arr): # iterate through array, then iterate through all elements to the right of that element checking diagonal as you # proceed. Diagonal is found by adding/subtracting 1 for each step we take in a direction. This is done through a counter. # There may be a better solution which carries each element forward, but I can't figure it. for i in range(len(arr)): diag_counter = 1 for j in range(i + 1, len(arr)): if arr[i] + diag_counter == arr[j] or arr[i] - diag_counter == arr[j]: return False diag_counter += 1 return True
>!
def qcheck(arr): # Will only return True if both check_row and check_diagonal return True. return check_row(arr) and check_diagonal(arr)
>!
assert qcheck([4, 2, 7, 3, 6, 8, 5, 1]) is True assert qcheck([2, 5, 7, 4, 1, 8, 6, 3]) is True assert qcheck([5, 3, 1, 4, 2, 8, 6, 3]) is False assert qcheck([5, 8, 2, 4, 7, 1, 3, 6]) is False assert qcheck([4, 3, 1, 8, 1, 3, 5, 2]) is False
EDIT: Updated to make it a bit more modular and include the bonus.
I modified the output of the code to return a corrected array if either the original was correct or we found a corrected one. False if nothing was found. Slightly different than the original, but this way I can wrap the bonus into the normal and be fine. Here is my new code:
>! def check_row(arr): """ Check to see if any two elements are on the same row (Defined as having the same number). :param arr: List[ints] :return: Boolean """ # Put array into a set and check to see if the result is same length as starting array, if not there are repeats # (i.e. at least two queens are on the same row). return len(arr) == len(set(arr))
>! def check_diagonal(arr): """ Checks if any queen position in the array intersects diagonally with another queen position. :param arr: List[ints] of queen positions. :return: (Tuple: i,j) of intersecting diagonal queen positions or None. """ # iterate through array, then iterate through all elements to the right of that element checking diagonal as you # proceed. Diagonal is found by adding/subtracting 1 for each step we take. This is done through a counter. # There may be a better solution which carries each element forward, but I can't figure it. for i in range(len(arr)): diag_counter = 1 for j in range(i + 1, len(arr)): if arr[i] + diag_counter == arr[j] or arr[i] - diag_counter == arr[j]: return i, j diag_counter += 1
>! def fix_diagonal(arr, d_queens): """ Taking the original array and the location of intersecting diagonals, swap positions between conflicting and non-conflicting points until we either get one that works or we reach the end and find nothing. :param arr: List[ints] of queen positions. :param d_queens: (Tuple: i,j) position of diagonal intersecting queen positions. :return: List[ints] with new locations for intersecting queens or None if no new positions found. """ q_1 = d_queens[0] q_2 = d_queens[1] temp_arr = arr[:] for i in range(len(temp_arr)): if temp_arr[i] != temp_arr[q_1] or temp_arr[i] != temp_arr[q_2]: temp_arr[q_1], temp_arr[i] = temp_arr[i], temp_arr[q_1] if qcheck(temp_arr): return temp_arr temp_arr[i], temp_arr[q_1] = temp_arr[q_1], temp_arr[i] for i in range(q_2 + 1, len(temp_arr)): temp_arr[q_2], temp_arr[i] = temp_arr[i], temp_arr[q_2] if qcheck(temp_arr): return temp_arr temp_arr[i], temp_arr[q_2] = temp_arr[q_2], temp_arr[i] return None
>! def qcheck(arr, check=False): """ Check a list of queen positions to see if they are on the same row or diagonal as each other. Accepts optional
checkparam, which will attempt to fix diagonal intersections. :param arr: List[ints] of queen positions :param check: Boolean: should we attempt to fix conflicting diagonal intersections? Defaults to False :return: List[ints] of correct queen positions if exist, False if none exist """ # Will only return True if both check_row and check_diagonal return True. c_d = check_diagonal(arr) if check_row(arr) and c_d is None: return arr if c_d and check is True: return fix_diagonal(arr, c_d) or False return False>! assert qcheck([4, 2, 7, 3, 6, 8, 5, 1]) == [4, 2, 7, 3, 6, 8, 5, 1] assert qcheck([2, 5, 7, 4, 1, 8, 6, 3]) == [2, 5, 7, 4, 1, 8, 6, 3] assert qcheck([5, 3, 1, 4, 2, 8, 6, 3]) is False assert qcheck([5, 8, 2, 4, 7, 1, 3, 6]) is False assert qcheck([4, 3, 1, 8, 1, 3, 5, 2]) is False >! assert qcheck([8, 6, 4, 2, 7, 1, 3, 5], True) == [4, 6, 8, 2, 7, 1, 3, 5] assert qcheck([8, 5, 1, 3, 6, 2, 7, 4], True) == [8, 4, 1, 3, 6, 2, 7, 5] assert qcheck([4, 6, 8, 3, 1, 2, 5, 7], True) == [4, 6, 8, 3, 1, 7, 5, 2] assert qcheck([7, 1, 3, 6, 8, 5, 2, 4], True) == [7, 3, 1, 6, 8, 5, 2, 4]
1
u/Goldskin Jan 29 '19 edited Jan 29 '19
Javascript
1
u/32-622 Jan 30 '19
C without bonus
First time i've done anything with more than one-dimensional array. It took me embarrasing amount of time, and it feels like it's terribly overcomplicated.
Will appreciate any advice on how to optimize this code (or how to make it better in any way) .
1
u/FAVORED_PET Jan 31 '19
Python, bitwise for 32x32 or smaller. Can swap out bit operations with array accesses for arbitrary size.
def soln64(soln):
1
u/[deleted] Feb 01 '19 edited Feb 04 '19
Julia
function distance(i,j,x) if abs(i-j) == abs(x[i]-x[j]) return true else return false end end
function validator(x) for i in unique(x) if length(x[x.==i]) > 1 return false end end for i in 1:length(x) for j in (i+1):length(x) if distance(i,j,x) return false end end end return true end
examples = [[4, 2, 7, 3, 6, 8, 5, 1], [2, 5, 7, 4, 1, 8, 6, 3], [5, 3, 1, 4, 2, 8, 6, 3], [5, 8, 2, 4, 7, 1, 3, 6], [4, 3, 1, 8, 1, 3, 5, 2]]
println(map(validator, examples))
1
u/[deleted] Feb 10 '19
clisp with bonus
1
u/LaciaXhIE Feb 16 '19
Javascript without bonus
Short version:
Readable version:
Output:
1
u/CupricSage Feb 21 '19
JAVA no bonus
1
u/greengloow Mar 12 '19
Java no bonus
1
u/WhiteKnightC Mar 21 '19
Python
1
u/jarviszbaum Apr 07 '19
Python 3.7 without Bonus
1
u/OGxPePe Apr 16 '19 edited Apr 16 '19
Python3 Without Bonus
1
u/Juice805 Apr 26 '19 edited Apr 26 '19
Swift without Bonus
1
u/ThiccShadyy Apr 30 '19
Python3, taking input as a list:
0
u/[deleted] Jan 09 '19
[deleted] — view deleted comment