1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
use std::fmt::{Debug, Display, Formatter};
use std::hash::Hash;

use crate::interval_limit::IntervalLimit;
use crate::LimitValue;

#[derive(Debug, Clone, Hash, Eq)]
pub struct Interval<T: Debug + Display + Clone + Hash + Eq + Ord + PartialEq + PartialOrd> {
  pub(crate) lower: IntervalLimit<T>,
  pub(crate) upper: IntervalLimit<T>,
}

impl<T: Debug + Display + Clone + Hash + Eq + Ord + PartialEq + PartialOrd> PartialEq
  for Interval<T>
{
  /// Verify the identity of this interval and the given interval `other`.
  ///
  /// It returns `true` if both intervals are empty, and `false` if only one of them is empty.
  /// If both are single-element intervals, the limits that are single elements are compared with each other, and `true` is returned if they match.
  /// If only one of them is a single-element interval, `false` is returned.
  ///
  /// - param
  ///   - other: an interval to be compared
  /// - return: `true` if they are identical, `false` if they are not
  fn eq(&self, other: &Self) -> bool {
    if self.is_empty() & other.is_empty() {
      true
    } else if self.is_empty() ^ other.is_empty() {
      false
    } else if self.is_single_element() & other.is_single_element() {
      self.as_lower_limit() == other.as_lower_limit()
    } else if self.is_single_element() ^ other.is_single_element() {
      false
    } else {
      self.upper == other.upper && self.lower == other.lower
    }
  }
}

impl<T: Debug + Display + Clone + Hash + Eq + Ord + PartialEq + PartialOrd> Interval<T> {
  pub fn and_more(lower: LimitValue<T>) -> Self {
    Self::closed(lower, LimitValue::<T>::Limitless)
  }

  pub fn closed(lower: LimitValue<T>, upper: LimitValue<T>) -> Self {
    Self::new_with(lower, true, upper, true)
  }

  pub fn more_than(lower: LimitValue<T>) -> Self {
    Self::open(lower, LimitValue::<T>::Limitless)
  }

  pub fn open(lower: LimitValue<T>, upper: LimitValue<T>) -> Self {
    Self::new_with(lower, false, upper, false)
  }

  pub fn over(
    lower: LimitValue<T>,
    lower_included: bool,
    upper: LimitValue<T>,
    upper_included: bool,
  ) -> Self {
    Self::new_with(lower, lower_included, upper, upper_included)
  }

  pub fn single_element(element: LimitValue<T>) -> Self {
    Self::closed(element.clone(), element)
  }

  pub fn under(upper: LimitValue<T>) -> Self {
    Self::open(LimitValue::<T>::Limitless, upper)
  }

  pub fn up_to(upper: LimitValue<T>) -> Self {
    Self::closed(LimitValue::<T>::Limitless, upper)
  }

  pub fn complement_relative_to(&self, other: &Interval<T>) -> Vec<Interval<T>> {
    let mut interval_sequence: Vec<Interval<T>> = vec![];
    if !self.intersects(other) {
      interval_sequence.push(other.clone());
      interval_sequence
    } else {
      if let Some(left) = self.left_complement_relative_to(other) {
        interval_sequence.push(left.clone());
      }
      if let Some(right) = self.right_complement_relative_to(other) {
        interval_sequence.push(right.clone());
      }
      interval_sequence
    }
  }

  /// Verify that this interval completely encloses the specified interval `other`.
  ///
  /// - params
  ///     - other: an `Interval`
  /// - return: `true` for full comprehension, `false` otherwise
  pub fn covers(&self, other: &Interval<T>) -> bool {
    let lower_pass = self.includes(other.as_lower_limit())
      || self.as_lower_limit() == other.as_lower_limit() && !other.includes_lower_limit();
    let upper_pass = self.includes(other.as_upper_limit())
      || self.as_upper_limit() == other.as_upper_limit() && !other.includes_upper_limit();
    lower_pass && upper_pass
  }

  /// Get the interval that lies between this interval and the given interval `other`.
  ///
  /// For example, the gap between [3, 5) and [10, 20) is [5, 19).
  /// If the two intervals have a common part, return an empty interval.
  ///
  /// - params
  ///     - other: an interval to be compared
  /// - return: gap interval
  pub fn gap(&self, other: &Interval<T>) -> Interval<T> {
    if self.intersects(other) {
      self.empty_of_same_type()
    } else {
      self.new_of_same_type(
        self.lesser_of_upper_limits(other).clone(),
        !self.lesser_of_upper_included_in_union(other),
        self.greater_of_lower_limits(other).clone(),
        !self.greater_of_lower_included_in_union(other),
      )
    }
  }

  /// Verify whether this interval is a single-element interval or not.
  ///
  /// A single-element interval has both upper and lower limits, and also indicates that these limits are equal and not an open interval.
  /// For example, `3 <= x < 3`, `3 <= x <= 3`, and `3 <= x <= 3`.
  ///
  /// - return: `true` if it's a single element interval, `false` otherwise
  pub fn is_single_element(&self) -> bool {
    if !self.has_upper_limit() {
      false
    } else if !self.has_lower_limit() {
      false
    } else {
      self.as_upper_limit() == self.as_lower_limit() && !self.is_empty()
    }
  }

  pub fn empty_of_same_type(&self) -> Interval<T> {
    self.new_of_same_type(
      self.as_lower_limit().clone(),
      false,
      self.as_lower_limit().clone(),
      false,
    )
  }

  pub fn new_of_same_type(
    &self,
    lower: LimitValue<T>,
    lower_closed: bool,
    upper: LimitValue<T>,
    upper_closed: bool,
  ) -> Interval<T> {
    Self::new_with(lower, lower_closed, upper, upper_closed)
  }

  /// Verify whether or not the specified value `value` is included in this interval.
  ///
  /// - params
  ///     - value: an interval value
  /// - return: `true` if included, `false` otherwise
  pub fn includes(&self, value: &LimitValue<T>) -> bool {
    !self.is_below(value) && !self.is_above(value)
  }

  /// Verify that the specified value `value` does not exceed the upper limit of this interval.
  ///
  /// - params
  ///     - value: an interval value
  /// - return: `true` if not exceeded, `false` otherwise
  pub fn is_below(&self, value: &LimitValue<T>) -> bool {
    if !self.has_upper_limit() {
      false
    } else {
      *self.as_upper_limit() < *value
        || *self.as_upper_limit() == *value && !self.includes_upper_limit()
    }
  }

  /// Verify that the specified value `value` does not exceed the lower limit of this interval.
  ///
  /// - params
  ///     - value: an interval value
  /// - return: `true` if not exceeded, `false` otherwise
  pub fn is_above(&self, value: &LimitValue<T>) -> bool {
    if !self.has_lower_limit() {
      false
    } else {
      *self.as_lower_limit() > *value
        || *self.as_lower_limit() == *value && !self.includes_lower_limit()
    }
  }

  /// Verify whether this interval is an open interval or not.
  ///
  /// - return: `true` if it's an open interval, `false` otherwise (including half-open interval)
  pub fn is_open(&self) -> bool {
    !self.includes_lower_limit() && !self.includes_upper_limit()
  }

  /// Verify whether this interval is a closed interval or not.
  ///
  /// - return: `true` if it's a closed interval, `false` otherwise (including half-open interval)
  pub fn is_closed(&self) -> bool {
    self.includes_upper_limit() && self.includes_lower_limit()
  }

  /// Verify whether this interval is empty or not.
  ///
  /// The interval is empty means that the upper and lower limits are the same value and the interval is open.
  /// For example, a state like `3 < x < 3`.
  ///
  /// - return: `true` if it's empty, `false` otherwise.
  pub fn is_empty(&self) -> bool {
    match (self.as_upper_limit(), self.as_lower_limit()) {
      (&LimitValue::Limitless, &LimitValue::Limitless) => false,
      _ => self.is_open() && self.as_upper_limit() == self.as_lower_limit(),
    }
  }

  pub fn new(lower: IntervalLimit<T>, upper: IntervalLimit<T>) -> Interval<T> {
    Self::check_lower_is_less_than_or_equal_upper(&lower, &upper);
    let mut l = lower.clone();
    let mut u = upper.clone();
    if !upper.is_infinity()
      && !lower.is_infinity()
      && upper.as_value() == lower.as_value()
      && (lower.is_open() ^ upper.is_open())
    {
      if lower.is_open() {
        l = IntervalLimit::lower(true, lower.as_value().clone());
      }
      if upper.is_open() {
        u = IntervalLimit::upper(true, upper.as_value().clone());
      }
    }
    Self { lower: l, upper: u }
  }

  pub fn new_with(
    lower: LimitValue<T>,
    is_lower_closed: bool,
    upper: LimitValue<T>,
    is_upper_closed: bool,
  ) -> Interval<T> {
    Self::new(
      IntervalLimit::lower(is_lower_closed, lower),
      IntervalLimit::upper(is_upper_closed, upper),
    )
  }

  /// Return the product set (common part) of this interval and the given interval `other`.
  ///
  /// If the common part does not exist, it returns an empty interval.
  ///
  /// - params
  ///     - other: an interval to be compared
  pub fn intersect(&self, other: &Interval<T>) -> Interval<T> {
    let intersect_lower_bound = self.greater_of_lower_limits(other);
    let intersect_upper_bound = self.lesser_of_upper_limits(other);
    if *intersect_lower_bound > *intersect_upper_bound {
      self.empty_of_same_type()
    } else {
      self.new_of_same_type(
        intersect_lower_bound.clone(),
        self.greater_of_lower_included_in_intersection(other),
        intersect_upper_bound.clone(),
        self.lesser_of_upper_included_in_intersection(other),
      )
    }
  }

  /// Verify if there is a common part between this interval and the given interval `other`.
  ///
  /// - params
  ///     - other: a target interval
  /// - return: `true` if the common part exists, `false` otherwise
  pub fn intersects(&self, other: &Interval<T>) -> bool {
    if self.equal_both_limitless(self.as_upper_limit(), other.as_upper_limit()) {
      true
    } else if self.equal_both_limitless(self.as_lower_limit(), self.as_lower_limit()) {
      true
    } else {
      let g = self.greater_of_lower_limits(other);
      let l = self.lesser_of_upper_limits(other);
      if g < l {
        true
      } else if g > l {
        false
      } else {
        self.greater_of_lower_included_in_intersection(other)
          && self.lesser_of_upper_included_in_intersection(other)
      }
    }
  }

  pub fn as_upper_limit(&self) -> &LimitValue<T> {
    self.upper.as_value()
  }
  pub fn as_lower_limit(&self) -> &LimitValue<T> {
    self.lower.as_value()
  }

  /// Get whether there is an upper limit or not.
  ///
  /// Warning: This method is generally used for the purpose of displaying this value and for interaction with classes that are highly coupled to this class.
  /// Careless use of this method will unnecessarily increase the coupling between this class and the client-side class.
  ///
  /// If you want to use this value for calculations,
  /// - find another appropriate method or add a new method to this class.
  /// - find another suitable method or consider adding a new method to this class.
  ///
  ///
  /// - return: `true` if upper limit is present, `false` otherwise
  pub fn has_upper_limit(&self) -> bool {
    matches!(self.as_upper_limit(), LimitValue::Limit(_))
  }

  /// Get whether there is an lower limit or not.
  ///
  /// Warning: This method is generally used for the purpose of displaying this value and for interaction with classes that are highly coupled to this class.
  /// Careless use of this method will unnecessarily increase the coupling between this class and the client-side class.
  ///
  /// If you want to use this value for calculations,
  /// - find another appropriate method or add a new method to this class.
  /// - find another suitable method or consider adding a new method to this class.
  ///
  ///
  /// - return: `true` if lower limit is present, `false` otherwise
  pub fn has_lower_limit(&self) -> bool {
    matches!(self.as_lower_limit(), LimitValue::Limit(_))
  }

  /// Get whether the upper limit is closed or not.
  ///
  /// Warning: This method is generally used for the purpose of displaying this value and for interaction with classes that are highly coupled to this class.
  /// Careless use of this method will unnecessarily increase the coupling between this class and the client-side class.
  ///
  /// If you want to use this value for calculations,
  /// - find another appropriate method or add a new method to this class.
  /// - find another suitable method or consider adding a new method to this class.
  ///
  /// - return: true` if the upper limit is closed, `false` otherwise
  pub fn includes_upper_limit(&self) -> bool {
    self.upper.is_closed()
  }

  pub fn includes_lower_limit(&self) -> bool {
    self.lower.is_closed()
  }

  fn check_lower_is_less_than_or_equal_upper(lower: &IntervalLimit<T>, upper: &IntervalLimit<T>) {
    if !(lower.is_lower() && upper.is_upper() && lower <= upper) {
      panic!("{} is not before or equal to {}", lower, upper)
    }
  }

  fn equal_both_limitless(&self, me: &LimitValue<T>, your: &LimitValue<T>) -> bool {
    matches!((me, your), (&LimitValue::Limitless, &LimitValue::Limitless))
  }

  pub fn greater_of_lower_limits<'a>(&'a self, other: &'a Interval<T>) -> &'a LimitValue<T> {
    if *self.as_lower_limit() == LimitValue::Limitless {
      other.as_lower_limit()
    } else if *other.as_lower_limit() == LimitValue::Limitless {
      self.as_lower_limit()
    } else if self.as_lower_limit() >= other.as_lower_limit() {
      self.as_lower_limit()
    } else {
      other.as_lower_limit()
    }
  }

  pub fn lesser_of_upper_limits<'a>(&'a self, other: &'a Interval<T>) -> &'a LimitValue<T> {
    if *self.as_upper_limit() == LimitValue::Limitless {
      other.as_upper_limit()
    } else if *other.as_upper_limit() == LimitValue::Limitless {
      self.as_upper_limit()
    } else if self.as_upper_limit() <= other.as_upper_limit() {
      self.as_upper_limit()
    } else {
      other.as_upper_limit()
    }
  }

  pub fn greater_of_lower_included_in_intersection(&self, other: &Interval<T>) -> bool {
    let limit = self.greater_of_lower_limits(other);
    self.includes(&limit) && other.includes(&limit)
  }

  pub fn greater_of_lower_included_in_union(&self, other: &Interval<T>) -> bool {
    let limit = self.greater_of_lower_limits(other);
    self.includes(&limit) || other.includes(&limit)
  }

  pub fn lesser_of_upper_included_in_intersection(&self, other: &Interval<T>) -> bool {
    let limit = self.lesser_of_upper_limits(other);
    self.includes(&limit) && other.includes(&limit)
  }

  pub fn lesser_of_upper_included_in_union(&self, other: &Interval<T>) -> bool {
    let limit = self.lesser_of_upper_limits(other);
    self.includes(&limit) || other.includes(&limit)
  }

  /// この区間の下側補区間と与えた区間 `other` の共通部分を返す。
  ///
  /// other 比較対象の区間
  /// return この区間の下側の補区間と、与えた区間の共通部分。存在しない場合は `None`
  pub fn left_complement_relative_to(&self, other: &Interval<T>) -> Option<Interval<T>> {
    // この区間の下側限界値の方が小さいか等しい場合、下側の補区間に共通部分は無い
    if self.lower <= other.lower {
      None
    } else {
      Some(self.new_of_same_type(
        other.as_lower_limit().clone(),
        other.includes_lower_limit(),
        self.as_lower_limit().clone(),
        !self.includes_lower_limit(),
      ))
    }
  }

  pub fn right_complement_relative_to(&self, other: &Interval<T>) -> Option<Interval<T>> {
    // この区間の上側限界値の方が大きいか等しい場合、上側の補区間に共通部分は無い
    if self.upper >= other.upper {
      None
    } else {
      Some(self.new_of_same_type(
        self.as_upper_limit().clone(),
        !self.includes_upper_limit(),
        other.as_upper_limit().clone(),
        other.includes_upper_limit(),
      ))
    }
  }
}

impl<T: Debug + Display + Clone + Hash + Eq + Ord + PartialEq + PartialOrd> Display
  for Interval<T>
{
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    if self.is_empty() {
      write!(f, "{{}}")
    } else if self.is_single_element() {
      write!(f, "{{{}}}", self.as_lower_limit().to_string())
    } else {
      let mut str = String::new();
      if self.includes_lower_limit() {
        str.push('[');
      } else {
        str.push('(');
      }
      if self.has_lower_limit() {
        str.push_str(&self.as_lower_limit().to_string());
      } else {
        str.push_str(&"Infinity");
      }
      str.push_str(&", ");
      if self.has_upper_limit() {
        str.push_str(&self.as_upper_limit().to_string());
      } else {
        str.push_str(&"Infinity");
      }
      if self.includes_upper_limit() {
        str.push(']');
      } else {
        str.push(')');
      }
      write!(f, "{}", str)
    }
  }
}