How to select random two digits from anywhere in a number with TypeScript

1 Answer

0 votes
// Function to select random two distinct digits from a number
function getRandomTwoDigits(number: number): string {
  const numStr: string = number.toString();

  if (numStr.length < 2) {
    return "Error: number must have at least 2 digits";
  }

  // Generate two distinct random indices
  const i: number = Math.floor(Math.random() * numStr.length);
  let j: number;
  do {
    j = Math.floor(Math.random() * numStr.length);
  } while (j === i); // ensure different positions

  // Form the two-digit string
  return numStr[i] + numStr[j];
}

// Main
function main(): void {
  const num: number = 1234567;
  const randomTwo: string = getRandomTwoDigits(num);

  console.log("Random two digits:", randomTwo);
}

main();

 
 
       
/*
run:
       
"Random two digits:",  "65" 

*/
   

 



answered 6 days ago by avibootz
...