|
| 1 | +module Algorithmable |
| 2 | + module Cups |
| 3 | + module NumberOfOccurrencesInArray |
| 4 | + include Algorithmable::Searches |
| 5 | + |
| 6 | + def linear_solve(collection, target) |
| 7 | + result = Hash.new 0 |
| 8 | + collection.each do |item| |
| 9 | + result[item] += 1 |
| 10 | + end |
| 11 | + result[target] |
| 12 | + end |
| 13 | + |
| 14 | + def logarithmic(collection, target) |
| 15 | + i = find_first_one collection, 0, collection.size - 1, target |
| 16 | + j = find_last_one collection, i, collection.size - 1, target |
| 17 | + j - i + 1 |
| 18 | + end |
| 19 | + |
| 20 | + def find_first_one(collection, low, high, target) |
| 21 | + # if(high >= low) |
| 22 | + # { |
| 23 | + # int mid = (low + high)/2; /*low + (high - low)/2;*/ |
| 24 | + # if( ( mid == 0 || x > arr[mid-1]) && arr[mid] == x) |
| 25 | + # return mid; |
| 26 | + # else if(x > arr[mid]) |
| 27 | + # return first(arr, (mid + 1), high, x, n); |
| 28 | + # else |
| 29 | + # return first(arr, low, (mid -1), x, n); |
| 30 | + # } |
| 31 | + # return -1 |
| 32 | + end |
| 33 | + |
| 34 | + def find_last_one(collection, low, high, target) |
| 35 | + # if(high >= low) |
| 36 | + # { |
| 37 | + # int mid = (low + high)/2; /*low + (high - low)/2;*/ |
| 38 | + # if( ( mid == n-1 || x < arr[mid+1]) && arr[mid] == x ) |
| 39 | + # return mid; |
| 40 | + # else if(x < arr[mid]) |
| 41 | + # return last(arr, low, (mid -1), x, n); |
| 42 | + # else |
| 43 | + # return last(arr, (mid + 1), high, x, n); |
| 44 | + # } |
| 45 | + # return -1; |
| 46 | + end |
| 47 | + end |
| 48 | + end |
| 49 | +end |
0 commit comments