You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

92 lines
2.6 KiB

  1. /*
  2. This file is part of BioD.
  3. Copyright (C) 2012 Artem Tarasov <lomereiter@gmail.com>
  4. Permission is hereby granted, free of charge, to any person obtaining a
  5. copy of this software and associated documentation files (the "Software"),
  6. to deal in the Software without restriction, including without limitation
  7. the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. and/or sell copies of the Software, and to permit persons to whom the
  9. Software is furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  17. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  18. DEALINGS IN THE SOFTWARE.
  19. */
  20. module bio.bam.bai.utils.algo;
  21. import bio.bam.bai.chunk;
  22. import std.range;
  23. import std.algorithm;
  24. struct NonOverlappingChunks(R) {
  25. this(R r) {
  26. _range = r;
  27. popFront();
  28. }
  29. bool empty() @property {
  30. return _empty;
  31. }
  32. auto front() @property {
  33. return _front;
  34. }
  35. void popFront() {
  36. if (!_range.empty()) {
  37. _front = _range.front;
  38. tryToJoinWithNextChunks();
  39. } else {
  40. _empty = true;
  41. }
  42. }
  43. private:
  44. R _range;
  45. void tryToJoinWithNextChunks() {
  46. _range.popFront();
  47. while (!_range.empty()) {
  48. /// Get next element
  49. auto next = _range.front;
  50. /// It's presumed that chunks are sorted
  51. assert(next >= _front);
  52. /// Check if the chunk can be joined with the previous one
  53. if (_front.end >= next.beg) {
  54. /// update end of _front
  55. _front.end = max(_front.end, next.end);
  56. _range.popFront(); /// next is consumed
  57. } else {
  58. /// can't join
  59. break;
  60. }
  61. }
  62. }
  63. Chunk _front;
  64. bool _empty = false;
  65. }
  66. /// Params:
  67. /// r - range of chunks, sorted by leftmost coordinate
  68. /// Returns:
  69. /// range of non-overlapping chunks, covering the same subset
  70. /// as original chunks
  71. auto nonOverlappingChunks(R)(R r)
  72. if (is(ElementType!R == Chunk))
  73. {
  74. return NonOverlappingChunks!R(r);
  75. }