Home > Blockchain >  Is there anyway to make the return text of a boolean function not show in the terminal
Is there anyway to make the return text of a boolean function not show in the terminal

Time:12-08

Im doing a project for school where I have to use binary search to figure out if a specific number is present in a string of numbers. I am new to coding and am trying to figure out a way to have "true" not show up in the terminal. Is there a way to do this or do I have to remove the boolean function. I know I cannot remove the "return true" from the code because it stops it from working but I want the output to just be the code I am printing not the "true"

func BinarySearch(target int, input []int) bool {

    first := 0
    last := len(input) - 1

    for first <= last{

        median := (first   last) / 2

        if input[median] < target {
            first = median   1
        }else{
            last = median - 1
        }

    }

    if first == len(input) || input[first] != target {
        fmt.Println("The searched integer", target, "was not found")
    } else {
        fmt.Println("The searched integer", target, "was found")
    }

    return true

}

I have input the text I want to print but do not know what to do about the return

CodePudding user response:

You can just do that by removing the bool after the params of the function, because basically you were telling that the function must return a boolean, while you were going to use it as a void. Dont forget also to pre-sort your input prior to passing it to your function. Best of luck

func BinarySearch(target int, input []int) {

    first := 0
    last := len(input) - 1

    for first <= last{

        median := (first   last) / 2

        if input[median] < target {
            first = median   1
        }else{
            last = median - 1
        }

    }

    if first == len(input) || input[first] != target {
        fmt.Println("The searched integer", target, "was not found")
    } else {
        fmt.Println("The searched integer", target, "was found")
    }
}

CodePudding user response:

I would probably do something like this:

https://goplay.tools/snippet/vBgmo4ASUh5

package main

import (
    "fmt"
)

func main() {
    orderedList := []int{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25}

    for i := 0; i < 27; i   {
        var slug string
        if found := BinarySearch(i, orderedList); !found {
            slug = "not "
        }
        fmt.Printf("%d is %s in the list\n", i, slug)
    }
}

func BinarySearch(target int, values []int) (found bool) {
    lo := 0
    hi := len(values)

    for hi > lo {
        mid := lo   (hi-lo)/2

        if values[mid] < target {
            lo = mid   1
        } else {
            hi = mid
        }

    }

    found = lo < len(values) && target == values[lo]
    return found
}
  •  Tags:  
  • go
  • Related