-
-
Save NicolaM94/79d625ecef07cb26a7a8d9bcdb6143fd to your computer and use it in GitHub Desktop.
Binary search implementation for DCP 24 problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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