Skip to content

Instantly share code, notes, and snippets.

@NicolaM94
Last active November 12, 2023 17:25
Show Gist options
  • Save NicolaM94/79d625ecef07cb26a7a8d9bcdb6143fd to your computer and use it in GitHub Desktop.
Save NicolaM94/79d625ecef07cb26a7a8d9bcdb6143fd to your computer and use it in GitHub Desktop.
Binary search implementation for DCP 24 problem
package main
import (
"fmt"
"math/rand"
"time"
)
func binarySearch(overArray []int, bottom, top, breakFloor int) int {
for bottom <= top {
middlePoint := bottom + (top-bottom)/2
if middlePoint == breakFloor {
return middlePoint
}
if middlePoint < breakFloor {
bottom = middlePoint + 1
}
if middlePoint > breakFloor {
top = middlePoint - 1
}
}
return -1
}
func main() {
// Creating the building
var building []int
for c := 0; c < 100000; c++ {
building = append(building, c)
}
// Generating the random targetFloor
targetFloor := rand.New(rand.NewSource(time.Now().UnixNano())).Intn(len(building))
bsFloor := binarySearch(building, 0, len(building), targetFloor)
fmt.Println("Target floor found with binary search is ", bsFloor)
fmt.Println("Random target floor previously generated is ", targetFloor)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment