From bdc96e8c5a185fe2374714cf84f16f6c42f6117a Mon Sep 17 00:00:00 2001 From: mittimithai Date: Tue, 13 Apr 2021 12:41:47 -0700 Subject: [PATCH] introduced Interval in random.ts (#91) This adds a new `Random.inInterval()` method and uses it. --- lib/random-colors.ts | 7 ++++--- lib/random.ts | 9 ++++++++- lib/util.ts | 5 ++++- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/lib/random-colors.ts b/lib/random-colors.ts index 72283c3..8defeee 100644 --- a/lib/random-colors.ts +++ b/lib/random-colors.ts @@ -27,14 +27,15 @@ function createRandomColor(rng: Random): string { //See if we can pull out a sample inside the LUV solid for (let i = 0; i < max_luv_samples; i++) { //bounds from https://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html#cvtcolor - let L = rng.inRange({ min: 0, max: 100, step: 0.1 }); - let u = rng.inRange({ min: -134, max: 220, step: 0.1 }); - let v = rng.inRange({ min: -140, max: 122, step: 0.1 }); + let L = rng.inInterval({ min: 0, max: 100 }); + let u = rng.inInterval({ min: -134, max: 220 }); + let v = rng.inInterval({ min: -140, max: 122 }); let rand_color = colorspaces.make_color("CIELUV", [L, u, v]); //console.log(`L:${L},u${u},v${v}`); if (rand_color.is_displayable() && !(L == 0.0 && (u != 0 || v != 0))) { rand_color_hex = rand_color.as("hex"); + //console.log(rand_color_hex); luv_sample_failed = false; break; } diff --git a/lib/random.ts b/lib/random.ts index a297149..3757e31 100644 --- a/lib/random.ts +++ b/lib/random.ts @@ -1,4 +1,4 @@ -import { inclusiveRange, NumericRange } from "./util"; +import { inclusiveRange, NumericInterval, NumericRange } from "./util"; export type RandomParameters = { modulus: number; @@ -58,6 +58,13 @@ export class Random { return this.choice(inclusiveRange(range)); } + /** + * Return a number in the interval, second argument is really supremum which return value is always less than + */ + inInterval({ min, max }: NumericInterval): number { + return this.next() * (max - min) + min; + } + /** * Return a random item from the given array. If the array is * empty, an exception is thrown. diff --git a/lib/util.ts b/lib/util.ts index fb27f8a..ae9c185 100644 --- a/lib/util.ts +++ b/lib/util.ts @@ -28,9 +28,12 @@ export function rad2deg(radians: number): number { return (radians * 180) / Math.PI; } -export type NumericRange = { +export type NumericInterval = { min: number; max: number; +}; + +export type NumericRange = NumericInterval & { step: number; };