Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to find the floor and ceiling of the value N in an unsorted slice with Go

1 Answer

0 votes
package main

import (
    "fmt"
    "math"
)

// findFloorAndCeil returns the floor and ceil of N in the given slice
func findFloorAndCeil(arr []int, N int) (int, int) {
    floorval := math.MinInt64 // Initialize to smallest possible value
    ceilval := math.MaxInt64  // Initialize to largest possible value

    for _, num := range arr {
        if num <= N && num > floorval {
            floorval = num // Update floorval if num is closer to N
        }
        if num >= N && num < ceilval {
            ceilval = num // Update ceilval if num is closer to N
        }
    }

    // If no valid floorval or ceilval is found, set them to a special value
    if floorval == math.MinInt64 {
        floorval = -1
    }
    if ceilval == math.MaxInt64 {
        ceilval = -1
    }

    return floorval, ceilval
}

func main() {
    arr := []int{4, 10, 8, 2, 6, 9, 1}
    N := 5

    floorval, ceilval := findFloorAndCeil(arr, N)

    fmt.Printf("floor: %v\n", map[bool]string{true: "None", false: fmt.Sprint(floorval)}[floorval == -1])
    fmt.Printf("ceil: %v\n", map[bool]string{true: "None", false: fmt.Sprint(ceilval)}[ceilval == -1])
}



/*
run:

floor: 4
ceil: 6

*/

 



answered Nov 8, 2025 by avibootz
...