Path: csiph.com!news.mixmin.net!eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Tim Rentsch Newsgroups: comp.programming Subject: Re: A little puzzle. Date: Sun, 27 Nov 2022 19:23:21 -0800 Organization: A noiseless patient Spider Lines: 42 Message-ID: <86y1rv7oeu.fsf@linuxsc.com> References: <875yf8nijb.fsf@bsb.me.uk> <42d09790-8473-4d9a-bc3f-35ed25e84b54n@googlegroups.com> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: reader01.eternal-september.org; posting-host="8f857c192f6688ee1cdff50f6ccf3164"; logging-data="2007532"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+a5x8lgS24DmCrytv4HcWq56S8ocISiUY=" User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) Cancel-Lock: sha1:TtaJ7AlYAYU43RAsRvOaH6ngYys= sha1:5jlwVT82q8IKudNgniQNsGcZC4E= Xref: csiph.com comp.programming:15978 Julio Di Egidio writes: > On Monday, 21 November 2022 at 21:45:34 UTC+1, Ben Bacarisse wrote: > >> Consider any ordered measure that "wraps round" -- bearings in degrees, >> minutes in the hour, indeed hours in either the 12 or 24 hour clock. >> The problem is to determine if a given value is in the sub-range >> specified by a start and an en value. > > I don't think much better can be done of the obvious implementation: > > ```js > function inOpenModRange( > x: number, lo: number, hi: number, m: number > ): boolean { > let x_ = MOD(x, m); > let lo_ = MOD(lo, m); > let hi_ = MOD(hi, m); > return lo_ <= x_ && x_ < hi_; > } > ``` > > where MOD is modulo, not remainder. > > In terms of remainder (as in JS), MOD looks like this: > > ```js > function MOD(x: number, m: number): number { > if (x * m === 0) { return 0; } // allow for MOD(x, 0) > if (x > 0) { x = x % m; } > else { x = (m + x % m) % m; } > return x; > } > ``` This proposed function doesn't work. Consider a curfew that starts at 10 pm (2200) and goes until 5 am (0500). Is 3 am (0300) a curfew violation? The call to your function would be inOpenModRange( 0300, 2200, 0500, 2400 ); which yields false. But it should yield true.