Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions Backtracking/NQueens.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
class NQueens {
constructor(size) {
if (size < 0) {
throw RangeError('Invalid board size')
if (size <= 0) {
throw RangeError('Board size must be a positive integer')
}

this.board = new Array(size).fill('.').map(() => new Array(size).fill('.'))
this.size = size
this.solutionCount = 0
Expand Down Expand Up @@ -40,7 +41,7 @@ class NQueens {
solve(col = 0) {
if (col >= this.size) {
this.solutionCount++
return true
return
}

for (let i = 0; i < this.size; i++) {
Expand All @@ -50,8 +51,6 @@ class NQueens {
this.removeQueen(i, col)
}
}

return false
}

printBoard(output = (value) => console.log(value)) {
Expand Down
22 changes: 12 additions & 10 deletions Search/BinarySearch.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,44 +8,46 @@
*/

function binarySearchRecursive(arr, x, low = 0, high = arr.length - 1) {
if (!Array.isArray(arr) || arr.length === 0) {
return -1
}

const mid = Math.floor(low + (high - low) / 2)

if (high >= low) {
if (arr[mid] === x) {
// item found => return its index
return mid
}

if (x < arr[mid]) {
// arr[mid] is an upper bound for x, so if x is in arr => low <= x < mid
return binarySearchRecursive(arr, x, low, mid - 1)
} else {
// arr[mid] is a lower bound for x, so if x is in arr => mid < x <= high
return binarySearchRecursive(arr, x, mid + 1, high)
}
} else {
// if low > high => we have searched the whole array without finding the item
return -1
}

return -1
}

function binarySearchIterative(arr, x, low = 0, high = arr.length - 1) {
if (!Array.isArray(arr) || arr.length === 0) {
return -1
}

while (high >= low) {
const mid = Math.floor(low + (high - low) / 2)

if (arr[mid] === x) {
// item found => return its index
return mid
}

if (x < arr[mid]) {
// arr[mid] is an upper bound for x, so if x is in arr => low <= x < mid
high = mid - 1
} else {
// arr[mid] is a lower bound for x, so if x is in arr => mid < x <= high
low = mid + 1
}
}
// if low > high => we have searched the whole array without finding the item

return -1
}

Expand Down