Skip to content

Instantly share code, notes, and snippets.

@joshed-io
Last active December 18, 2015 17:09
Show Gist options
  • Save joshed-io/5816332 to your computer and use it in GitHub Desktop.
Save joshed-io/5816332 to your computer and use it in GitHub Desktop.

Revisions

  1. joshed-io revised this gist Jun 19, 2013. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions keen_io_zrank.rb
    Original file line number Diff line number Diff line change
    @@ -19,13 +19,13 @@
    ]

    # flatten the API response into a single hash
    # e.g. {"Apple"=>15, "Orange"=>10, "Grape"=>5}
    # e.g. {"Apple"=>15, "Orange"=>10, "Grape"=>5, "Pear"=>7}
    flat_hash = keen_result.inject({}) { |acc, entry|
    acc[entry["entry"]] = entry["result"]; acc
    }

    # create a 'set', sorted by the entry count
    # e.g. [["Grape", 5], ["Orange", 10], ["Apple", 15]]
    # e.g. [["Grape", 5], ["Pear", 7], ["Orange", 10], ["Apple", 15]]
    sorted_set = flat_hash.sort_by { |entry, count| count }

    # given an sorted array of pairs, find the index of the pair
  2. joshed-io created this gist Jun 19, 2013.
    42 changes: 42 additions & 0 deletions keen_io_zrank.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    # Example Keen IO API response for a count, grouped by an 'entry' field
    keen_result = [
    {
    "entry" => "Apple",
    "result" => 15
    },
    {
    "entry" => "Orange",
    "result" => 10
    },
    {
    "entry" => "Grape",
    "result" => 5
    },
    {
    "entry" => "Pear",
    "result" => 7
    }
    ]

    # flatten the API response into a single hash
    # e.g. {"Apple"=>15, "Orange"=>10, "Grape"=>5}
    flat_hash = keen_result.inject({}) { |acc, entry|
    acc[entry["entry"]] = entry["result"]; acc
    }

    # create a 'set', sorted by the entry count
    # e.g. [["Grape", 5], ["Orange", 10], ["Apple", 15]]
    sorted_set = flat_hash.sort_by { |entry, count| count }

    # given an sorted array of pairs, find the index of the pair
    # whose value matches the 'entry' param
    def zrank(entry, set)
    set.each_with_index { |pair, index|
    return index if entry == pair[0]
    }
    end

    puts "Apple: #{zrank("Apple", sorted_set)}" #=> 3
    puts "Orange: #{zrank("Orange", sorted_set)}" #=> 2
    puts "Grape: #{zrank("Grape", sorted_set)}" #=> 0
    puts "Pear: #{zrank("Pear", sorted_set)}" #=> 1