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

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,846 questions

55,675 answers

573 users

How to find the floor and ceiling of the value N in an unsorted list with Scala

1 Answer

0 votes
object FloorCeilFinder {

  // Finds the floor and ceiling of N in the given list
  def findFloorAndCeil(lst: List[Int], N: Int): (Int, Int) = {
    var floorval = Int.MinValue // Initialize to the smallest possible value
    var ceilval = Int.MaxValue  // Initialize to the largest possible value

    for (num <- lst) {
      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 == Int.MinValue) floorval = -1
    if (ceilval == Int.MaxValue) ceilval = -1

    (floorval, ceilval)
  }

  def main(args: Array[String]): Unit = {
    val lst = List(4, 10, 8, 2, 6, 9, 1)
    val N = 5

    val (floorval, ceilval) = findFloorAndCeil(lst, N)

    println("floor: " + (if (floorval == -1) "None" else floorval.toString))
    println("ceil: " + (if (ceilval == -1) "None" else ceilval.toString))
  }
}



/*
run:

floor: 4
ceil: 6

*/

 



answered Nov 8, 2025 by avibootz
edited Nov 8, 2025 by avibootz
...