Hoare's partitioning scheme golang - algorithm

Quicksort with Hoare's partitioning
// Hoare's partitioning scheme
func PartitionHoare(arr []int, low, high int) int {
length := len(arr)
if length == 0 {
panic("Array size is 0")
}
pivot := arr[low]
i := low - 1
j := high + 1
for {
for {
j--
if arr[j] > pivot {
break
}
}
for {
i++
if arr[i] < pivot {
break
}
}
if i < j {
Swap(&arr, i, j)
} else {
return j
}
}
}
// Sort
func SortHoare(arr []int, low, high int) {
if low < high {
p := PartitionHoare(arr, low, high)
SortHoare(arr, low, p)
SortHoare(arr, p+1, high)
}
}
// Swap i <--> j
func Swap(arr *[]int, i, j int) {
(*arr)[i], (*arr)[j] = (*arr)[j], (*arr)[i]
}
Trying to implement Quicksort using Hoare's partitioning but can't figure out what am I doing wrong. It is stuck in an infinite loop, always runs out of memory
fatal error: runtime: out of memory

You should use non strict inequalities while looking for position of i and j to do the swap. So instead of
if arr[j] > pivot {
break
}
you should have
if arr[j] >= pivot {
break
}
And the same for i. Instead of
if arr[i] < pivot {
break
}
use
if arr[i] <= pivot {
break
}
Also I'm not sure if it's intentional or not, but currently your algorithm sorts in descending order. If you want to sort in ascending order swap the comparitions between i and j. So:
if arr[j] <= pivot {
break
}
and
if arr[i] >= pivot {
break
}

Related

Climbing The Leaderboard Hackerrank Solutions in Golang

Clue :
An arcade game player wants to climb to the top of the leaderboard and track their ranking. The game uses Dense Ranking, so its leaderboard works like this:
The player with the highest score is ranked number 1 on the leaderboard.
Players who have equal scores receive the same ranking number, and the next player(s) receive the immediately following ranking number.
This is my code solution for climbing the leaderboard, 8/12 test case is passed. but 4 case is timeout. any solution for boosting the performance of my code?
func contains(s []int32, e int32) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func remove(slice []int32, s int) []int32 {
return append(slice[:s], slice[s+1:]...)
}
func climbingLeaderboard(ranked []int32, player []int32) []int32 {
// Write your code here
for i := 0; i < len(ranked); i++ {
if contains(ranked[i+1:], ranked[i]) {
ranked = remove(ranked, i)
i--
}
}
sort.Slice(ranked, func(i, j int) bool { return ranked[i] < ranked[j] })
var result = make([]int32, len(player))
if len(ranked) == 1 {
for i := 0; i < len(player); i++ {
if player[i] > ranked[0] {
result[i] = 1
} else if player[0] == ranked[0] {
result[i] = 1
} else if player[0] < ranked[0] {
result[i] = 2
}
}
} else {
for i := 0; i < len(player); i++ {
l := len(ranked)
l32 := int32(l)
p := player[i]
var temp int32
for j := 1; j < l; j++ {
if p > ranked[j] {
temp = 1
} else if p > ranked[j-1] && p < ranked[j] {
temp = l32 - int32(j) + 1
break
} else if p == ranked[j-1] {
temp = l32 - int32(j) + 1
break
} else if p < ranked[j-1] {
temp = l32 + 1
break
}
}
result[i] = temp
temp = 0
}
}
return result
}
Your code to dedupe ranked is very inefficient.
func contains(s []int32, e int32) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func remove(slice []int32, s int) []int32 {
return append(slice[:s], slice[s+1:]...)
}
for i := 0; i < len(ranked); i++ {
if contains(ranked[i+1:], ranked[i]) {
ranked = remove(ranked, i)
i--
}
}
sort.Slice(ranked, func(i, j int) bool { return ranked[i] < ranked[j] })
Your code to search for player game ranks is not efficient.
Efficiency is not just what you do, it's also how many times you do it.
Your code is too complicated.
Here is some simple code that solves the challenge without triggering a timeout.
import (
"sort"
)
func climbingLeaderboard(ranked []int32, player []int32) []int32 {
ranks := ranked[:1]
last := ranks[0]
for _, score := range ranked[1:] {
if score != last {
ranks = append(ranks, score)
}
last = score
}
climb := make([]int32, 0, len(player))
for _, score := range player {
rank := sort.Search(
len(ranks),
func(i int) bool { return ranks[i] <= score },
)
climb = append(climb, int32(rank+1))
}
return climb
}

Generate all the strings of length n drawn from 0 ... k-1

This problem is from the book Data Structure and Algorithms Made Easy by Narasimha Karumanchi chapter Recursion and Backtracking. The algorithm which is given in the book is as follows:
Let us assume we keep current k-ary string in an array A[0...n-1]. Call function k-string(n, k)
void k-string(int n, int k) {
// process all k-ary strings of length m
if(n < 1)
printf("%s", A); // Assume array A is a global variable
else {
for(int j=0; j<k; j++){
A[n-1] = j;
k-string(n-1, k);
}
}
}
I couldn't understand the algorithm. Like why did they assigned an integer j to a string element?
package main
import "fmt"
func printResult(A []int, n int) {
var i int
for ; i < n; i++ {
// Function to print the output
fmt.Print(A[i])
}
fmt.Printf("\n")
}
// Function to generate all k-ary strings
func generateK_aryStrings(n int, A []int, i int, k int) {
if i == n {
printResult(A, n)
return
}
for j := 0; j < k; j++ {
// assign j at ith position and try for all other permutations for remaining positions
A[i] = j
generateK_aryStrings(n, A, i+1, k)
}
}
func main() {
var n int = 4
A := make([]int, n)
// Print all binary strings
generateK_aryStrings(n, A, 0, 3)
return
}

Writing next Permutation in Go using closure, what is wrong with my code

I have written a function "iterPermutation" which uses closure. I want to return array and boolean from the closure which I could not do. So tried only array but it still gives an error
cannot use func literal (type func() []int) as type []int in return
argument
I want to use iterPermutation like
a := []int{0,1,2,3,4}
nextPermutation, exists := iterPermutation(a)
for exists {
nextPermutation()
}
func iterPermutation(a []int) []int {
return func() []int {
i := len(a) - 2
for i >= 0 && a[i+1] <= a[i] {
i--
}
if i < 0 {
return a
}
j := len(a) - 1
for j >= 0 && a[j] <= a[i] {
j--
}
a[i], a[j] = a[j], a[i]
for k, l := i, len(a)-1; k < l; k, l = k+1, l-1 {
a[k], a[l] = a[l], a[k]
}
return a
}
}
Golang spec for Return statements described:
The return value or values may be explicitly listed in the "return"
statement. Each expression must be single-valued and assignable to the
corresponding element of the function's result type.
The function called for permutation should contains two values in return one for the array and another for the boolean. Since you are assigning two variables from the function return:
a := []int{0,1,2,3,4}
nextPermutation, exists := iterPermutation(a) // it should return two values one for nextPermutation which is an array and other is exists which might be a boolean value.
for exists {
nextPermutation()
}
For below error:
"cannot use func literal (type func() []int) as type []int in return
argument"
you are returning func() literal enclosed inside the closure function of permutation along with boolean value, so change the return type as:
package main
func main(){
a := []int{0,1,2,3,4}
nextPermutation, _ := iterPermutation(a)
nextPermutation()
}
func iterPermutation(a []int) ((func() []int), bool) { // return both values
return func() []int {
i := len(a) - 2
for i >= 0 && a[i+1] <= a[i] {
i--
}
if i < 0 {
return a
}
j := len(a) - 1
for j >= 0 && a[j] <= a[i] {
j--
}
a[i], a[j] = a[j], a[i]
for k, l := i, len(a)-1; k < l; k, l = k+1, l-1 {
a[k], a[l] = a[l], a[k]
}
return a
}, true // add boolean value to return from the function.
}
Working answer on Playground
I'm going to ignore the "permutation" logic inside your closure and focus on couple of concepts that you need to be aware of so it would work like you've planned to with your code. Correct me if I'm wrong, but you want to get array of item from your closure until exists is false, right?
First of all, to have nextPermutation, exists := iterPermutation(a) compile properly, iterPermutation needs to return two values like so:
func iterPermutation(a []int) (func() []int, bool) {
exists := true
return func() []int {
//rest of your code
if i < 0 {
exists = false
return a
}
//rest of your code
}, exists
}
Next problem you face is the fact that, with the above approach, you will have with the exists value. Since you are returning a value for exists, any change to exists will not be propagated beyond the scope of iterPermutation. You can fix this problem by returning a pointer. This is one way of implementing it:
a := []int{0,1,2,3,4}
nextPermutation, check := iterPermutation(a)
while check.Exists {
nextPermutation()
}
type Check struct {
Exists bool
}
func iterPermutation(a []int) (func() []int, *Check) {
check:= &Check{
Exists: true,
}
return func() []int {
i := len(a) - 2
for i >= 0 && a[i+1] <= a[i] {
i--
}
if i < 0 {
check.Exists = false //this is put here as an example
return a
}
j := len(a) - 1
for j >= 0 && a[j] <= a[i] {
j--
}
a[i], a[j] = a[j], a[i]
for k, l := i, len(a)-1; k < l; k, l = k+1, l-1 {
a[k], a[l] = a[l], a[k]
}
return a
}, check
}
When you return a pointer of Check type, any change to it in the iterPermutation or in your closure is visible outside of these as well, since you are accessing a memory reference.

Golang Binary search

I'm practicing an interview algorithm, now coding it in Go. The purpose is to practice basic interview algorithms, and my skills in Go. I'm trying to perform a Binary search of an array of numbers.
package main
import "fmt"
func main() {
searchField := []int{2, 5, 8, 12, 16, 23, 38, 56, 72, 91}
searchNumber := 23
fmt.Println("Running Program")
fmt.Println("Searching list of numbers: ", searchField)
fmt.Println("Searching for number: ", searchNumber)
numFound := false
//searchCount not working. Belongs in second returned field
result, _ := binarySearch2(searchField, len(searchField), searchNumber, numFound)
fmt.Println("Found! Your number is found in position: ", result)
//fmt.Println("Your search required ", searchCount, " cycles with the Binary method.")
}
func binarySearch2(a []int, field int, search int, numFound bool) (result int, searchCount int) {
//searchCount removed for now.
searchCount, i := 0, 0
for !numFound {
searchCount++
mid := i + (field-i)/2
if search == a[mid] {
numFound = true
result = mid
return result, searchCount
} else if search > a[mid] {
field++
//i = mid + 1 causes a stack overflow
return binarySearch2(a, field, search, numFound)
}
field = mid
return binarySearch2(a, field, search, numFound)
}
return result, searchCount
}
The main problems I'm coming across are:
1) When the number is higher in the list than my mid search, am I truly continuing a binary search, or has it turned to a sequential? How can I fix that? The other option I've placed has been commented out because it causes a stack overflow.
2) I wanted to add a step count to see how many steps it takes to finish the search. Something to use with other search methods as well. If I print out the search count as is, it always reads one. Is that because I need to return it (and therefore call for it in the header) in the method?
I understand Go has methods that streamline this process. I'm trying to increase my knowledge and coding skills. I appreciate your input.
You're not doing a binary search properly. First off, your for loop is useless, since each branch in the conditional tree has a return statement in it, so it can never run more than one iteration. It looks like you started to code it iteratively, then swapped to a recursive setup, but only kinda halfway converted it.
The idea of a binary search is that you have a high and low index and search the midway point between them. You're not doing that, you're just incrementing the field variable and trying again (which will cause you to search each index twice until you find the item or segfault by running past the end of the list). In Go, though, you don't need to keep track of the high and low indexes, as you can simply subslice the search field as appropriate.
Here's a more elegant recursive version:
func binarySearch(a []int, search int) (result int, searchCount int) {
mid := len(a) / 2
switch {
case len(a) == 0:
result = -1 // not found
case a[mid] > search:
result, searchCount = binarySearch(a[:mid], search)
case a[mid] < search:
result, searchCount = binarySearch(a[mid+1:], search)
if result >= 0 { // if anything but the -1 "not found" result
result += mid + 1
}
default: // a[mid] == search
result = mid // found
}
searchCount++
return
}
https://play.golang.org/p/UyZ3-14VGB9
func BinarySearch(a []int, x int) int {
r := -1 // not found
start := 0
end := len(a) - 1
for start <= end {
mid := (start + end) / 2
if a[mid] == x {
r = mid // found
break
} else if a[mid] < x {
start = mid + 1
} else if a[mid] > x {
end = mid - 1
}
}
return r
}
Off-topic, but might help others looking for a simple binary search who could land here.
There's a generic binary search module on github since the standard library doesn't offer this common functionality: https://github.com/bbp-brieuc/binarysearch
func BinarySearch(array []int, target int) int {
startIndex := 0
endIndex := len(array) - 1
midIndex := len(array) / 2
for startIndex <= endIndex {
value := array[midIndex]
if value == target {
return midIndex
}
if value > target {
endIndex = midIndex - 1
midIndex = (startIndex + endIndex) / 2
continue
}
startIndex = midIndex + 1
midIndex = (startIndex + endIndex) / 2
}
return -1
}
generic type version ! (go 1.18)
Time Complexity : log2(n)+1
package main
import "golang.org/x/exp/constraints"
func BinarySearch[T constraints.Ordered](a []T, x T) int {
start, mid, end := 0, 0, len(a)-1
for start <= end {
mid = (start + end) >> 1
switch {
case a[mid] > x:
end = mid - 1
case a[mid] < x:
start = mid + 1
default:
return mid
}
}
return -1
}
full version with iteration counter at playground.
func search(nums []int, target, lo, hi int) int {
if(lo > hi) {
return -1
}
mid := lo + (hi -lo) /2
if(nums[mid]< target){
return search2(nums, target,mid+1, hi)
}
if (nums[mid]> target){
return search2(nums, target,lo, mid -1)
}
return mid
}
https://www.youtube.com/watch?v=kNkeJ3ZtgJA

Palindrome - Is it possible to make my code faster

I have an ASCII-only string which is either already a palindrome, or else can be made a palindrome by removing one character. I need to determine whether it's already a palindrome, and if not, I need to find the index of the character that would need to be removed. For example, if the string is 'aaba', then it can be made into the palindrome 'aba' by removing the first character, so I need to return 0.
I have working code, but I am wondering if it is possible to make it faster, because I need to work with many long strings.
Here is my code:
package main
import (
"fmt"
)
func Palindrome(s string) bool {
var l int = len(s)
for i := 0; i < l / 2; i++ {
if s[i] != s[l - 1 - i] {
return false;
}
}
return true
}
func RemoveChar(s string, idx int) string {
return s[0:idx-1] + s[idx:len(s)]
}
func findIdx(s string) int {
if Palindrome(s) {
return -1
}
for i := 0; i < len(s); i++ {
if Palindrome(RemoveChar(s, i + 1)) {
return i
}
}
return -2
}
func main() {
var s string = "aabaab"
fmt.Println(findIdx(s))
}
This should be very slightly more efficient than ruakh's solution. You shouldn't have to use isPalindrome() to check that s[i + 1:len(s) - i] is a palindrome because it's quicker to check that s[i:len(s) - i - 1] is not a palindrome. In the solution below, in most cases j won't get very far at all before the function returns.
func findIdx(s string) int {
var n int = len(s)
for i := 0; i < n / 2; i++ {
if s[i] != s[n - i - 1] {
for j := 0; ;j++ {
if s[i + j] != s[n - 2 - i - j] {
return i;
}
if s[i + j + 1] != s[n - 1 - i - j] {
return n - 1 - i;
}
}
}
}
return -1
}
Here is a much more efficient approach:
func findIdx(s string) int {
for i := 0; i < len(s) / 2; i++ {
if s[i] != s[len(s) - i - 1] {
if isPalindrome(s[i+1:len(s)-i]) {
return i
} else {
return len(s) - i - 1
}
}
}
return -1
}
It just proceeds from the ends of the string until it finds a pair of bytes that should match, if the string were a palindrome, but that do not. It then knows that it will return the index of one of these two bytes, so it only needs to perform one "is this a palindrome?" check; and it doesn't need to use the RemoveChar function, since the "is this a palindrome?" check only needs to consider the middle portion of the string (that hasn't already been examined).

Resources