001package org.clafer.domain; 002 003import gnu.trove.TIntCollection; 004import gnu.trove.iterator.TIntIterator; 005import gnu.trove.set.TIntSet; 006import gnu.trove.set.hash.TIntHashSet; 007import java.util.Arrays; 008import java.util.PrimitiveIterator; 009import java.util.Spliterator; 010import java.util.Spliterators; 011import java.util.function.IntConsumer; 012import java.util.function.IntPredicate; 013import java.util.stream.IntStream; 014import java.util.stream.StreamSupport; 015import org.clafer.common.Util; 016import org.clafer.ir.IrException; 017 018/** 019 * Immutable domain over integers. Internally stored as a list of (low, high) 020 * disjoint pairs of regions. 021 * 022 * 023 * @author jimmy 024 */ 025public class Domain { 026 027 public static final Domain EmptyDomain = new Domain(); 028 029 protected final int[] bounds; 030 031 /** 032 * @param bounds sorted, unique, and immutable integers 033 */ 034 protected Domain(int... bounds) { 035 if (bounds.length % 2 == 1) { 036 throw new IllegalArgumentException(); 037 } 038 assert isStrictSorted(bounds); 039 this.bounds = bounds; 040 } 041 042 private static boolean isStrictSorted(int[] bounds) { 043 for (int i = 1; i < bounds.length; i++) { 044 if (bounds[i - 1] >= bounds[i]) { 045 return false; 046 } 047 } 048 return true; 049 } 050 051 public static Domain boundDomain(int low, int high) { 052 return new Domain(low, high + 1); 053 } 054 055 public static Domain constantDomain(int value) { 056 return boundDomain(value, value); 057 } 058 059 public static Domain enumDomain(int... values) { 060 if (values.length == 1) { 061 return constantDomain(values[0]); 062 } 063 return enumDomain(new TIntHashSet(values)); 064 } 065 066 public static Domain enumDomain(TIntSet values) { 067 int[] bounds = new int[2 * values.size()]; 068 int regions = 0; 069 int[] array = values.toArray(); 070 Arrays.sort(array); 071 int i = 0; 072 while (i < array.length) { 073 int prev = i; 074 do { 075 i++; 076 } while (i < array.length && array[i] == array[i - 1] + 1); 077 bounds[regions++] = array[prev]; 078 bounds[regions++] = array[i - 1] + 1; 079 } 080 if (regions < bounds.length) { 081 return new Domain(Arrays.copyOf(bounds, regions)); 082 } 083 return new Domain(bounds); 084 } 085 086 public static Domain enumDomain(IntStream values) { 087 PrimitiveIterator.OfInt iter = values.sorted().iterator(); 088 if (!iter.hasNext()) { 089 return EmptyDomain; 090 } 091 int[] bounds = new int[16]; 092 int regions = 0; 093 int start = iter.nextInt(); 094 int end = start; 095 while (iter.hasNext()) { 096 int i = iter.nextInt(); 097 if (i == end + 1) { 098 end = i; 099 } else { 100 if (regions == bounds.length) { 101 bounds = Arrays.copyOf(bounds, 2 * bounds.length); 102 } 103 bounds[regions++] = start; 104 bounds[regions++] = end + 1; 105 start = i; 106 end = start; 107 } 108 } 109 if (regions == bounds.length) { 110 bounds = Arrays.copyOf(bounds, 2 + bounds.length); 111 } 112 bounds[regions++] = start; 113 bounds[regions++] = end + 1; 114 if (regions < bounds.length) { 115 return new Domain(Arrays.copyOf(bounds, regions)); 116 } 117 return new Domain(bounds); 118 } 119 120 /** 121 * Checks if this domain is defined as a lower and upper bound. If the 122 * domain is bounded then it contains every value between its lower and 123 * upper bound. 124 * 125 * @return {@code true} if and only if this domain is a single contiguous 126 * region, {@code false} otherwise 127 */ 128 public boolean isBounded() { 129 return bounds.length <= 2; 130 } 131 132 /** 133 * Checks if a value is within this domain. 134 * 135 * @param value test this value 136 * @return {@code true} if and only if this domain contains the 137 * {@code value}, {@code false} otherwise 138 */ 139 public boolean contains(int value) { 140 return Util.ordinal(value, bounds) % 2 == 1; 141 } 142 143 public boolean containsAll(TIntCollection values) { 144 TIntIterator iter = values.iterator(); 145 while (iter.hasNext()) { 146 if (!contains(iter.next())) { 147 return false; 148 } 149 } 150 return true; 151 } 152 153 public boolean containsAll(int[] values) { 154 for (int value : values) { 155 if (!contains(value)) { 156 return false; 157 } 158 } 159 return true; 160 } 161 162 public boolean containsAll(int low, int high) { 163 int lowOrdinal = Util.ordinal(low, bounds); 164 if (lowOrdinal % 2 == 0) { 165 return false; 166 } 167 if (low == high) { 168 return true; 169 } 170 int highOrdinal = Util.ordinal(high, bounds); 171 return lowOrdinal == highOrdinal; 172 } 173 174 public boolean containsAny(TIntCollection values) { 175 TIntIterator iter = values.iterator(); 176 while (iter.hasNext()) { 177 if (contains(iter.next())) { 178 return true; 179 } 180 } 181 return false; 182 } 183 184 public boolean containsAny(int[] values) { 185 for (int value : values) { 186 if (contains(value)) { 187 return true; 188 } 189 } 190 return false; 191 } 192 193 public boolean containsAny(int low, int high) { 194 int lowOrdinal = Util.ordinal(low, bounds); 195 if (lowOrdinal % 2 == 1) { 196 return true; 197 } 198 int highOrdinal = Util.ordinal(high, bounds); 199 return lowOrdinal != highOrdinal; 200 } 201 202 /** 203 * Returns the smallest integer contained in this domain. Undefined if this 204 * domain is empty. 205 * 206 * @return the smallest integer contained in this domain 207 */ 208 public int getLowBound() { 209 if (bounds.length == 0) { 210 throw new IrException("Emtpy domain does not have a low bound."); 211 } 212 return bounds[0]; 213 } 214 215 /** 216 * Returns the largest integer contained in this domain. Undefined if this 217 * domain is empty. 218 * 219 * @return the largest integer contained in this domain 220 */ 221 public int getHighBound() { 222 if (bounds.length == 0) { 223 throw new IrException("Emtpy domain does not have a low bound."); 224 } 225 return bounds[bounds.length - 1] - 1; 226 } 227 228 /** 229 * Checks if this domain contains no values. 230 * 231 * @return {@code true} if and only if the size of this domain is zero, 232 * {@code false} otherwise 233 */ 234 public boolean isEmpty() { 235 return bounds.length == 0; 236 } 237 238 /** 239 * Checks if this domain contains a single value. 240 * 241 * @return {@code true} if and only if the size of this domain is one, 242 * {@code false} otherwise 243 */ 244 public boolean isConstant() { 245 return bounds.length == 2 && bounds[0] + 1 == bounds[1]; 246 } 247 248 /** 249 * Returns how many values are contained in this domain. 250 * 251 * @return the size of this domain 252 */ 253 public int size() { 254 int size = 0; 255 for (int i = 0; i < bounds.length; i += 2) { 256 size += bounds[i + 1] - bounds[i]; 257 } 258 return size; 259 } 260 261 /** 262 * Check if this domain is a (non-strict) subset of another domain. 263 * 264 * @param superset 265 * @return {@code true} if and only if this domain is a subset of 266 * {@code superset}, {@code false} otherwise 267 */ 268 public boolean isSubsetOf(Domain superset) { 269 if (this == superset) { 270 return true; 271 } 272 for (int i = 0; i < bounds.length; i += 2) { 273 if (!superset.containsAll(bounds[i], bounds[i + 1] - 1)) { 274 return false; 275 } 276 } 277 return true; 278 } 279 280 public boolean isSupersetOf(Domain subset) { 281 return subset.isSubsetOf(this); 282 } 283 284 /** 285 * Check if this domain intersects another domain. 286 * 287 * @param other 288 * @return {@code true} if and only if this domain is intersects 289 * {@code other}, {@code false} otherwise 290 */ 291 public boolean intersects(Domain other) { 292 if (this == other && !isEmpty()) { 293 return true; 294 } 295 for (int i = 0; i < bounds.length; i += 2) { 296 if (other.containsAny(bounds[i], bounds[i + 1] - 1)) { 297 return true; 298 } 299 } 300 return false; 301 } 302 303 private Domain insertOrRemove(boolean insertOrRemove, int value) { 304 int ordinal = Util.ordinal(value, bounds); 305 if (ordinal % 2 == (insertOrRemove ? 1 : 0)) { 306 return this; 307 } 308 if (ordinal > 0 && bounds[ordinal - 1] == value) { 309 if (ordinal < bounds.length && bounds[ordinal] == value + 1) { 310 // Merge the two regions. 311 int[] newBounds = new int[bounds.length - 2]; 312 System.arraycopy(bounds, 0, newBounds, 0, ordinal - 1); 313 System.arraycopy(bounds, ordinal + 1, newBounds, ordinal - 1, bounds.length - ordinal - 1); 314 return new Domain(newBounds); 315 } 316 int[] newBounds = bounds.clone(); 317 newBounds[ordinal - 1]++; 318 return new Domain(newBounds); 319 } else if (ordinal < bounds.length && bounds[ordinal] == value + 1) { 320 int[] newBounds = bounds.clone(); 321 newBounds[ordinal]--; 322 return new Domain(newBounds); 323 } else { 324 int[] newBounds = new int[bounds.length + 2]; 325 System.arraycopy(bounds, 0, newBounds, 0, ordinal); 326 newBounds[ordinal] = value; 327 newBounds[ordinal + 1] = value + 1; 328 System.arraycopy(bounds, ordinal, newBounds, ordinal + 2, bounds.length - ordinal); 329 return new Domain(newBounds); 330 } 331 } 332 333 /** 334 * Add an element into this domain. 335 * 336 * @param value 337 * @return {@code this.union({value})} 338 */ 339 public Domain insert(int value) { 340 return insertOrRemove(true, value); 341 } 342 343 /** 344 * Remove an element from this domain. 345 * 346 * @param value 347 * @return {@code this.difference({value})} 348 */ 349 public Domain remove(int value) { 350 return insertOrRemove(false, value); 351 } 352 353 /** 354 * Remove all elements from this domain where the predicate evaluates to 355 * {@code true}. 356 * 357 * @param predicate 358 * @return a subset of this domain where the predicate evaluates to 359 * {@code false}. 360 */ 361 public Domain removeAll(IntPredicate predicate) { 362 Domain remove = this; 363 for (int region = 0; region < bounds.length; region += 2) { 364 for (int i = bounds[region]; i < bounds[region + 1]; i++) { 365 if (predicate.test(i)) { 366 remove = remove.remove(i); 367 } 368 } 369 } 370 return remove; 371 } 372 373 /** 374 * Retains all elements from this domain where the predicate evaluates to 375 * {@code true}. 376 * 377 * @param predicate 378 * @return a subset of this domain where the predicate evaluates to 379 * {@code true}. 380 */ 381 public Domain retainAll(IntPredicate predicate) { 382 return removeAll(predicate.negate()); 383 } 384 385 /** 386 * Remove all elements less than the bound from this domain. 387 * 388 * @param low 389 * @return {@code this.intersection({low, low + 1, ...})} 390 */ 391 public Domain boundLow(int low) { 392 if (isEmpty() || low <= getLowBound()) { 393 return this; 394 } 395 int ordinal = Util.ordinal(low, bounds); 396 if (ordinal % 2 == 0) { 397 int[] newBounds = Arrays.copyOfRange(bounds, ordinal, bounds.length); 398 return new Domain(newBounds); 399 } 400 int[] newBounds = Arrays.copyOfRange(bounds, ordinal - 1, bounds.length); 401 newBounds[0] = low; 402 return new Domain(newBounds); 403 } 404 405 /** 406 * Remove all elements greater than the bound from this domain. 407 * 408 * @param high 409 * @return {@code this.intersection({high, high - 1, ...})} 410 */ 411 public Domain boundHigh(int high) { 412 if (isEmpty() || high >= getHighBound()) { 413 return this; 414 } 415 int ordinal = Util.ordinal(high, bounds); 416 if (ordinal % 2 == 0) { 417 int[] newBounds = Arrays.copyOfRange(bounds, 0, ordinal); 418 return new Domain(newBounds); 419 } 420 int[] newBounds = Arrays.copyOfRange(bounds, 0, ordinal + 1); 421 newBounds[ordinal] = high + 1; 422 return new Domain(newBounds); 423 } 424 425 /** 426 * Remove all elements less than the low bound or greater than the high 427 * bound from this domain. 428 * 429 * @param low 430 * @param high 431 * @return {@code this.intersection({low, low + 1, ..., high}) 432 */ 433 public Domain boundBetween(int low, int high) { 434 return boundLow(low).boundHigh(high); 435 } 436 437 public Domain minus() { 438 int[] newBounds = new int[bounds.length]; 439 for (int i = 0; i < newBounds.length; i++) { 440 newBounds[i] = -bounds[bounds.length - i - 1] + 1; 441 } 442 return new Domain(newBounds); 443 } 444 445 /** 446 * Subtract this domain with the other domain. 447 * 448 * @param other 449 * @return the difference of this domain with the other domain 450 */ 451 public Domain difference(Domain other) { 452 if (isEmpty() || !intersects(other)) { 453 return this; 454 } 455 int[] newBounds = new int[bounds.length + other.bounds.length]; 456 int length = 0; 457 int i = 0; 458 int j = 0; 459 460 int from = bounds[i]; 461 int to = bounds[i + 1]; 462 463 while (true) { 464 while (j < other.bounds.length 465 && from >= other.bounds[j + 1]) { 466 j += 2; 467 } 468 if (j == other.bounds.length 469 || to <= other.bounds[j]) { 470 newBounds[length++] = from; 471 newBounds[length++] = to; 472 from = to; 473 } else if (from < other.bounds[j] 474 && to > other.bounds[j]) { 475 newBounds[length++] = from; 476 newBounds[length++] = other.bounds[j]; 477 from = other.bounds[j + 1]; 478 } else { 479 from = other.bounds[j + 1]; 480 } 481 if (from >= to) { 482 i += 2; 483 if (i >= bounds.length) { 484 break; 485 } 486 from = bounds[i]; 487 to = bounds[i + 1]; 488 } 489 } 490 if (length == newBounds.length) { 491 return new Domain(newBounds); 492 } 493 return new Domain(Arrays.copyOf(newBounds, length)); 494 } 495 496 /** 497 * Intersect this domain with the other domain. 498 * 499 * @param other 500 * @return the intersection of this domain with the other domain 501 */ 502 public Domain intersection(Domain other) { 503 if (isSubsetOf(other)) { 504 return this; 505 } 506 if (other.isSubsetOf(this)) { 507 return other; 508 } 509 int[] newBounds = new int[bounds.length + other.bounds.length]; 510 int length = 0; 511 int i = 0; 512 int j = 0; 513 514 int from = bounds[i]; 515 int to = bounds[i + 1]; 516 517 while (true) { 518 while (j < other.bounds.length 519 && from >= other.bounds[j + 1]) { 520 j += 2; 521 } 522 if (j == other.bounds.length 523 || to <= other.bounds[j]) { 524 from = to; 525 } else if (from >= other.bounds[j] 526 && to <= other.bounds[j + 1]) { 527 newBounds[length++] = from; 528 newBounds[length++] = to; 529 from = to; 530 } else { 531 newBounds[length++] = Math.max(from, other.bounds[j]); 532 newBounds[length++] = Math.min(to, other.bounds[j + 1]); 533 from = newBounds[length - 1]; 534 } 535 if (from >= to) { 536 i += 2; 537 if (i >= bounds.length) { 538 break; 539 } 540 from = bounds[i]; 541 to = bounds[i + 1]; 542 } 543 } 544 if (length == newBounds.length) { 545 return new Domain(newBounds); 546 } 547 return new Domain(Arrays.copyOf(newBounds, length)); 548 } 549 550 private static int[] mergeRegions(int[] bounds) { 551 int length = 0; 552 int head = 0; 553 while (head < bounds.length) { 554 int from = bounds[head]; 555 int to = bounds[head + 1]; 556 while (head < bounds.length - 2 557 && to >= bounds[head + 2]) { 558 head += 2; 559 to = Math.max(to, bounds[head + 1]); 560 } 561 bounds[length++] = from; 562 bounds[length++] = to; 563 head += 2; 564 } 565 if (length == bounds.length) { 566 return bounds; 567 } 568 return Arrays.copyOf(bounds, length); 569 } 570 571 /** 572 * Union this domain with the other domain. 573 * 574 * @param other 575 * @return the union of this domain with the other domain 576 */ 577 public Domain union(Domain other) { 578 if (other.isSubsetOf(this)) { 579 return this; 580 } 581 if (isSubsetOf(other)) { 582 return other; 583 } 584 int[] newBounds = new int[bounds.length + other.bounds.length]; 585 int length = 0; 586 int j = 0; 587 588 for (int i = 0; i < bounds.length; i += 2) { 589 while (j < other.bounds.length 590 && bounds[i] >= other.bounds[j]) { 591 newBounds[length++] = other.bounds[j]; 592 newBounds[length++] = other.bounds[j + 1]; 593 j += 2; 594 } 595 newBounds[length++] = bounds[i]; 596 newBounds[length++] = bounds[i + 1]; 597 } 598 while (j < other.bounds.length) { 599 newBounds[length++] = other.bounds[j]; 600 newBounds[length++] = other.bounds[j + 1]; 601 j += 2; 602 } 603 return new Domain(mergeRegions(newBounds)); 604 } 605 606 /** 607 * Shift the elements in this domain. 608 * 609 * @param c 610 * @return the shifted domain 611 */ 612 public Domain offset(int c) { 613 if (c == 0) { 614 return this; 615 } 616 int[] newBounds = new int[bounds.length]; 617 for (int i = 0; i < newBounds.length; i++) { 618 newBounds[i] = bounds[i] + c; 619 } 620 return new Domain(newBounds); 621 } 622 623 public Domain add(Domain other) { 624 if (isEmpty()) { 625 return this; 626 } 627 if (other.isEmpty()) { 628 return other; 629 } 630 if (isConstant()) { 631 return other.offset(getLowBound()); 632 } 633 if (other.isConstant()) { 634 return offset(other.getLowBound()); 635 } 636 Domain sum = null; 637 for (int i = 0; i < bounds.length; i += 2) { 638 int[] newBounds = new int[other.bounds.length]; 639 for (int j = 0; j < other.bounds.length; j += 2) { 640 newBounds[j] = bounds[i] + other.bounds[j]; 641 newBounds[j + 1] = bounds[i + 1] + other.bounds[j + 1] - 1; 642 } 643 Domain domain = new Domain(mergeRegions(newBounds)); 644 sum = sum == null ? domain : sum.union(domain); 645 } 646 return sum; 647 } 648 649 /** 650 * Returns all the values contained in this domain. 651 * 652 * @return values contained in this domain 653 */ 654 public int[] getValues() { 655 int[] values = new int[size()]; 656 int size = 0; 657 for (int region = 0; region < bounds.length; region += 2) { 658 for (int i = bounds[region]; i < bounds[region + 1]; i++) { 659 values[size++] = i; 660 } 661 } 662 assert size == values.length; 663 return values; 664 } 665 666 /** 667 * Perform the action for every value in this domain in increasing order. 668 * 669 * @param action the action to perform 670 */ 671 public void forEach(IntConsumer action) { 672 for (int region = 0; region < bounds.length; region += 2) { 673 for (int i = bounds[region]; i < bounds[region + 1]; i++) { 674 action.accept(i); 675 } 676 } 677 } 678 679 /** 680 * Iterate over the domain in increasing order. 681 * 682 * @return an iterator over the values in this domain in increasing order 683 */ 684 public PrimitiveIterator.OfInt iterator() { 685 return new ForwardIterator(); 686 } 687 688 /** 689 * Iterate over the domain in the specified order. 690 * 691 * @param increasing increasing or decreasing order 692 * @return an iterator over the values in this domain in the order specified 693 */ 694 public PrimitiveIterator.OfInt iterator(boolean increasing) { 695 return increasing ? new ForwardIterator() : new ReverseIterator(); 696 } 697 698 public IntStream stream() { 699 Spliterator.OfInt spliterator = Spliterators.spliterator( 700 iterator(), size(), 701 Spliterator.DISTINCT | Spliterator.IMMUTABLE 702 | Spliterator.ORDERED | Spliterator.SORTED | Spliterator.SIZED); 703 return StreamSupport.intStream(spliterator, false); 704 } 705 706 @Override 707 public boolean equals(Object obj) { 708 if (obj instanceof Domain) { 709 Domain other = (Domain) obj; 710 return Arrays.equals(bounds, other.bounds); 711 } 712 return false; 713 } 714 715 @Override 716 public int hashCode() { 717 return Arrays.hashCode(bounds); 718 } 719 720 @Override 721 public String toString() { 722 StringBuilder result = new StringBuilder(); 723 result.append('{'); 724 for (int i = 0; i < bounds.length; i += 2) { 725 if (i > 0) { 726 result.append(", "); 727 } 728 if (bounds[i + 1] > bounds[i] + 2) { 729 result.append(bounds[i]); 730 result.append("..."); 731 result.append(bounds[i + 1] - 1); 732 } else { 733 for (int j = bounds[i]; j < bounds[i + 1]; j++) { 734 if (j > bounds[i]) { 735 result.append(", "); 736 } 737 result.append(j); 738 } 739 } 740 } 741 result.append('}'); 742 return result.toString(); 743 } 744 745 private class ForwardIterator implements PrimitiveIterator.OfInt { 746 747 int region = 0; 748 int i = 0; 749 750 @Override 751 public int nextInt() { 752 int next = bounds[region] + i; 753 if (next == bounds[region + 1] - 1) { 754 region += 2; 755 i = 0; 756 } else { 757 i++; 758 } 759 return next; 760 } 761 762 @Override 763 public boolean hasNext() { 764 return region < bounds.length; 765 } 766 767 @Override 768 public void remove() { 769 throw new UnsupportedOperationException(); 770 } 771 } 772 773 private class ReverseIterator implements PrimitiveIterator.OfInt { 774 775 int region = bounds.length - 2; 776 int i = 1; 777 778 @Override 779 public int nextInt() { 780 int next = bounds[region + 1] - i; 781 if (next == bounds[region]) { 782 region -= 2; 783 i = 1; 784 } else { 785 i++; 786 } 787 return next; 788 } 789 790 @Override 791 public boolean hasNext() { 792 return region >= 0; 793 } 794 795 @Override 796 public void remove() { 797 throw new UnsupportedOperationException(); 798 } 799 } 800}