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).

1  
// finds lowest index where predicate turns true.
2  
// returns "to" when predicate is false on whole range.
3  
// Predicate operates on a range and returns true
4  
// iff any value in the range is contained in the set.
5  
static <A> int indexOfRangePredicate(int from default 0, int to, IF2<Int, Int, Bool> pred) {
6  
  // interval empty?
7  
  if (from >= to) ret to;
8  
  
9  
  // predicate false on whole range?
10  
  if (!pred.get(from, to)) ret to;
11  
  
12  
  while ping (to-from > 1) {
13  
    // predicate turns true somewhere in range. split in middle.
14  
    int mid = (from + to) >>> 1;
15  
    
16  
    // check lower half
17  
    if (pred.get(from, mid))
18  
      // predicate turns true in lower half. move there.
19  
      to = mid;
20  
    else
21  
      // lower half is clean, move to higher half
22  
      from = mid;
23  
  }
24  
25  
  // we've narrowed things down to at most one element, return index
26  
  ret from;
27  
}

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: 222 / 315
Version history: 14 change(s)
Referenced in: [show references]