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

55,671 answers

573 users

How to generate a random color in RGB format with TypeScript

2 Answers

0 votes
function generateRandomRGBColor(): void {
  const red: number = Math.floor(Math.random() * 256);
  const green: number = Math.floor(Math.random() * 256);
  const blue: number = Math.floor(Math.random() * 256);

  console.log(`Random RGB Color: rgb(${red}, ${green}, ${blue})`);
}

generateRandomRGBColor();



/*
run:

Random RGB Color: rgb(108, 213, 8)

*/

 



answered Oct 9, 2025 by avibootz
edited 1 day ago by avibootz
0 votes
/**
 * Generate a random color in RGB format: rgb(R, G, B)
 * This program demonstrates how numbers and bits are used
 * to produce valid 8‑bit channel values.
 */

/**
 * Create a random 8‑bit integer (0–255).
 * Math.random() returns a floating‑point number in [0, 1),
 * so multiplying by 256 (2^8) gives a full byte of color data.
 */
function randomChannel(): number {
  // 8 bits → values from 0 to 255
  return Math.floor(Math.random() * 256);
}

/**
 * Produce a random RGB color by combining the channels.
 */
function generateRandomRGB(): {
  r: number;
  g: number;
  b: number;
  rgb: string;
} {
  const r: number = randomChannel(); // Red channel (8 bits)
  const g: number = randomChannel(); // Green channel (8 bits)
  const b: number = randomChannel(); // Blue channel (8 bits)

  // Construct the CSS-style RGB string
  const rgb: string = `rgb(${r}, ${g}, ${b})`;

  return { r, g, b, rgb };
}

// Run the program
const result: { r: number; g: number; b: number; rgb: string } = generateRandomRGB();

console.log("Red (8 bits):", result.r);
console.log("Green (8 bits):", result.g);
console.log("Blue (8 bits):", result.b);
console.log("RGB color:", result.rgb);



/*
run:

Red (8 bits): 248
Green (8 bits): 73
Blue (8 bits): 100
RGB color: rgb(248, 73, 100)

*/

 



answered 1 day ago by avibootz
...