当前位置:网站首页>d包含区间

d包含区间

2022-08-11 11:27:00 fqbqrr

alias ir = inclusiveRange;
auto inclusiveRange(T = int)(T f = T(0), T l = T(0), T s = T(1)) {
    
  if(!l) {
    
    l = f;
    f = 0;
  }
  return InclusiveRange!T(f, l, s);
}

struct InclusiveRange(T) {
    
  T front, last, step, term;

  this(T front, T last, T step) {
    
    this.front = front;
    this.last = last;
    this.step = step;
    this.term = last;
    if(this.diff % step)
    {
    
      const t = cast(int)(this.diff / step);
      this.term = cast(T)(t * step + this.front);
    }
  }

  auto save() {
     return this; }
  auto opSlice() {
     return this; }
  auto opDollar() {
     return this.length; }
  auto opSlice(T a, T b) in (b<=this.length)
  {
    
    return InclusiveRange!T(
      cast(T)(front + a * step),
      cast(T)(front + (b - 1) * step), step);
  }

  bool opBinaryRight(string op:"in")(T lhs)
  {
    
    foreach(r; this)
    {
    
      if(isClose(lhs, r, 1e-6))
      {
    
        return true;
      }
    }
    return false;
  }

  T sum()
  {
    
    const residueCheck = front ? 2 * front + diff
                               : diff;
    return cast(T)(length * residueCheck / 2);
  }

  auto diff() {
     return term - front; }
  auto length() {
     return cast(int)(diff / step + 1); }
  bool empty() {
     return front > last; }
  T back() {
     return last; }
  void popBack() {
     if(!empty) last -= step; }
  void popFront() {
     if(!empty) front += step; }
}

讲解在此

原网站

版权声明
本文为[fqbqrr]所创,转载请带上原文链接,感谢
https://fqbqrr.blog.csdn.net/article/details/126278142