/**
* Generate a random color in RGBA format: rgba(R, G, B, A)
* This program demonstrates how numbers and bits are used
* to produce valid 8‑bit channel values plus a floating‑point alpha.
*/
/**
* Create a random 8‑bit integer (0–255).
* Math.random() gives a floating‑point number in [0, 1),
* so multiplying by 256 (2^8) gives a range of 8 bits.
*/
function randomChannel() {
// 8 bits → values from 0 to 255
return Math.floor(Math.random() * 256);
}
/**
* Create a random alpha value in [0, 1].
* Rounded to two decimal places for readability.
*/
function randomAlpha() {
// Floating‑point alpha
return Number(Math.random().toFixed(2));
}
/**
* Produce a random RGBA color by combining the channels.
*/
function generateRandomRGBA() {
const r = randomChannel(); // Red channel (8 bits)
const g = randomChannel(); // Green channel (8 bits)
const b = randomChannel(); // Blue channel (8 bits)
const a = randomAlpha(); // Alpha channel (0–1)
// Construct the CSS RGBA string
const rgba = `rgba(${r}, ${g}, ${b}, ${a})`;
return { r, g, b, a, rgba };
}
// Run the program
const result = generateRandomRGBA();
console.log("Red (8 bits):", result.r);
console.log("Green (8 bits):", result.g);
console.log("Blue (8 bits):", result.b);
console.log("Alpha:", result.a);
console.log("RGBA color:", result.rgba);
/*
run:
Red (8 bits): 21
Green (8 bits): 109
Blue (8 bits): 245
Alpha: 0.41
RGBA color: rgba(21, 109, 245, 0.41)
*/