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

27
LINES

< > BotCompany Repo | #1030516 // lastIndexOfRangePredicate_IIntIntPred - faster version of lastIndexOfRangePredicate

JavaX fragment (include)

// finds highest index where predicate is true.
// returns from-1 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 lastIndexOfRangePredicate_IIntIntPred(int from default 0, int to, IIntIntPred pred) {
  // interval empty?
  if (from >= to) ret from-1;
  
  // predicate false on whole range?
  if (!pred.get(from, to)) ret from-1;
  
  while ping (to-from > 1) {
    // predicate is true somewhere in range. split in middle.
    int mid = (from + to) >>> 1;
    
    // check higher half
    if (pred.get(mid, to))
      // predicate is true in higher half. move there.
      from = mid;
    else
      // higher half is clean, move to lower half
      to = mid;
  }

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

Author comment

Began life as a copy of #1030507

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #1030516
Snippet name: lastIndexOfRangePredicate_IIntIntPred - faster version of lastIndexOfRangePredicate
Eternal ID of this version: #1030516/3
Text MD5: 3aea6ec3a2c85226d1e53f7273b8d14c
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-01-05 22:20:14
Source code size: 879 bytes / 27 lines
Pitched / IR pitched: No / No
Views / Downloads: 127 / 157
Version history: 2 change(s)
Referenced in: [show references]