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,961 questions

51,903 answers

573 users

How to find the floor and ceiling of the value N in an unsorted array with TypeScript

1 Answer

0 votes
function findFloorAndCeil(arr: number[], N: number): [number, number] {
  let floorval: number = Number.MIN_SAFE_INTEGER; // Initialize to smallest possible value
  let ceilval: number = Number.MAX_SAFE_INTEGER;  // Initialize to largest possible value

  for (const num of 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 === Number.MIN_SAFE_INTEGER) {
    floorval = -1;
  }
  if (ceilval === Number.MAX_SAFE_INTEGER) {
    ceilval = -1;
  }

  return [floorval, ceilval];
}

const arr: number[] = [4, 10, 8, 2, 6, 9, 1];
const N: number = 5;

const [floorval, ceilval] = findFloorAndCeil(arr, N);

console.log("floor:", floorval === -1 ? "None" : floorval);
console.log("ceil:", ceilval === -1 ? "None" : ceilval);



/*
run:

"floor:",  4 
"ceil:",  6 

*/


 



answered Nov 8, 2025 by avibootz
...