Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

27
LINES

< > BotCompany Repo | #1030504 // indexOfRangePredicate

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (2723L/16K).

// finds lowest index where predicate turns true.
// returns "to" when predicate is false on whole range.
// Predicate operates on a range and returns true
// iff any value in the range is contained in the set.
static <A> int indexOfRangePredicate(int from default 0, int to, IF2<Int, Int, Bool> pred) {
  // interval empty?
  if (from >= to) ret to;
  
  // predicate false on whole range?
  if (!pred.get(from, to)) ret to;
  
  while ping (to-from > 1) {
    // predicate turns true somewhere in range. split in middle.
    int mid = (from + to) >>> 1;
    
    // check lower half
    if (pred.get(from, mid))
      // predicate turns true in lower half. move there.
      to = mid;
    else
      // lower half is clean, move to higher half
      from = mid;
  }

  // we've narrowed things down to at most one element, return index
  ret from;
}

Author comment

Began life as a copy of #1029232

download  show line numbers  debug dex  old transpilations   

Travelled to 4 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, vouqrxazstgt

No comments. add comment

Snippet ID: #1030504
Snippet name: indexOfRangePredicate
Eternal ID of this version: #1030504/15
Text MD5: d3d710b3f64f084feca11160b670f7d3
Transpilation MD5: c0696142e28a9d9e56f066aba623fbfa
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-01-03 22:34:40
Source code size: 877 bytes / 27 lines
Pitched / IR pitched: No / No
Views / Downloads: 143 / 217
Version history: 14 change(s)
Referenced in: [show references]