Is any simple method to get the highest score from Redis sorted set? I found this way, may be there is better ways to make this(in ruby):
all_scores = Redis.zrange('foo', 0, -1, with_scores: true) # => [["item 1", 2.5], ["item 2", 3.4]]
all_scores.flatten.last # => 3.4
It seems not the best way.
you can use ZREVRANGE command.
ZREVRANGE foo 0 0 withscores
This will give you the highest score and it's value.
http://redis.io/commands/zrevrange
Related
So recently I've been trying new things in roblox scripting, and I have been working on this problem for days but I can't seem to find an answer. What I want to do is every 3 seconds, the script chooses a random string from the list and then changes the script's parent's Text property to it, but it doesn't seem to be working. Any ideas on this? Thanks.
Script:
local phrases = {"This should be changing!", "Have a nice time!", "Help used!", "Test", "Sample Text",}
while true do
script.Parent.Text = (phrases[Random:NextNumber])
wait(3)
end
calling NextNumber without any parameters returns a float between 0-1, a value like 0.333 or 0.5
https://developer.roblox.com/en-us/api-reference/datatype/Random
number Random:NextNumber ( )
Returns a pseudorandom number uniformly distributed over [0, 1).
You need a usable index from your list, somewhere between 1 and the length of your phrases list.
int Random:NextInteger ( int min, int max )
Returns a pseudorandom integer uniformly distributed over [min, max].
local phrases = {"This should be changing!", "Have a nice time!", "Help used!", "Test", "Sample Text",}
while true do
script.Parent.Text = phrases[ Random:NextInteger( 1, #phrases ) ]
wait(3)
end
I would like to sort an array of string based on my custom ordering. Problem is I dont know all the elements in array but Im sure that it has 3 strings (high/med/low). So I would like those 3 to be first 3 values . Rest at last
Eg:
Incoming arrays
array1 = ["high", "not impt" , "med" , "kind of impt" , "low" ]
array2 = ["low", "rand priority", "med", "high"]
Only high med and low are fixed, rest all keep changing or might not be present at all
required output
["high", "med", "low", rest.(order doesn't matter)]]
I know I can delete and merge, But it will be confusing in code as to why Im doing delete and merge. Any better way?
You can use sort_by method and implement something like this:
["high", "not impt" , "med" , "kind of impt" , "low" ].sort_by do |a|
["high", "med", "low"].index(a) || Float::INFINITY
end
index method returns 0, 1 and 2 for "high", "med" and "low" correspondingly and nil for other values. Thus, "high", "med" and "low" is going to be at the beginning and others at the end since every value is less than Float::INFINITY
I have a dict filled with Job types
A job has a name(string) and a score(int)
I managed to load the jobs into a Dict, and I want to sort them using the Sort method based on the jobs scores. However, when I sort the dict (call it jobs), it gives me a new vector of the sorted scores.
is there any way to sort the dict while preserving which job has its specific score?
jobs = Dict([(nurse, nurse.score), (construction, construction.score),
(programmer, programmer.score), (retail, retail.score)])
sort(collect(values(jobs)))
so if I have nurse with a score of 3, programmer with a score of 6, retail with a score of 0, and construction with a score of 4, I would want the output to be a dict (or something similar) that would contain:
programmer, 6
construction, 4
nurse, 3
retail, 0
or, even better, could I sort it by the values but get the output as a vector with just the jobs? then reference that vector later in my code?
this works in your specific case:
jobs = Dict("nurse"=>3, "construction"=>4, "programmer"=>6, "retail"=>0)
jobpairs = collect(jobs)
jobvalues = collect(values(jobs))
sind = sort(collect(values(jobs)), rev=true)
julia> sortedNames = [jobpairs[i] for i in indexin(sind, jobvalues)]
4-element Array{Any,1}:
"programmer"=>6
"construction"=>4
"nurse"=>3
"retail"=>0
if two keywords have the same value, we need do more work to deal with indices.
UPDATE:
as Matt suggested in the comment below, we should use sortperm rather than indexin which won't work if the dict has at least two keywords that have the same value.
jobs = Dict("nurse"=>3, "construction"=>4, "foo"=>3, "programmer"=>6, "retail"=>0)
jobpairs = collect(jobs)
jobvalues = collect(values(jobs))
sind = sortperm(collect(values(jobs)), rev=true)
julia> sortedNames = [jobpairs[i].first for i in sind]
5-element Array{Any,1}:
"programmer"
"construction"
"foo"
"nurse"
"retail"
Sorting algorithm with less code, but I don't know about the performance and you would not have a dict as result:
sort(collect(jobs),by=x->x[2],rev=true)
Currently I think the recommended way to do it is:
julia> using DataStructures
julia> jobs = Dict("nurse"=>3, "construction"=>4, "programmer"=>6, "retail"=>0)
Dict{String,Int64} with 4 entries:
"programmer" => 6
"retail" => 0
"construction" => 4
"nurse" => 3
julia> sort!(OrderedDict(jobs), byvalue=true, rev=true)
OrderedDict{String,Int64} with 4 entries:
"programmer" => 6
"construction" => 4
"nurse" => 3
"retail" => 0
In this way you get a dictionary as you wanted, but it is OrderedDict so it can be sorted as you see.
I'm looking to extract n random key-value pairs from a hash.
Hash[original_hash.to_a.sample(n)]
For Ruby 2.1,
original_hash.to_a.sample(n).to_h
I don't know of such method. Still you can do something like:
h[h.keys.sample]
If you need to sample more than one element the code will have to be a bit more complicated.
EDIT: to get key value pairs instead of only the value you can do something like:
keys_sample = h.keys.sample(n)
keys_sample.zip(keys_sample.map{|k| h[k])
Reading the top ranked answers, I'd go with it depends:
If you want to sample only one element from the hash, #Ivaylo Strandjev's solution only relies on hash lookup and Array#sample:
hsh[hsh.keys.sample]
To sample multiple hash elements, #sawa's answer leverages Array#to_h:
hsh.to_a.sample(n).to_h
Note that, as #cadlac mentions, hsh.to_a.sample.to_h won't work as expected. It will raise
TypeError: wrong element type String at 0 (expected array)
because Array#sample in this case returns just the element array, and not the array containing the element array.
A workaround is his solution, providing an n = 1 as an argument:
hsh.to_a.sample(1).to_h
PS: not looking for upvotes, only adding it as an explanation for people newer to Ruby.
If your sample has only one element, you could use this:
sample = h.keys.sample
h.select { |k,v| k == sample }
Or if your sample contains more than one element, use this:
n = 2
sample = h.keys.sample(n)
h.select { |k,v| sample.include?(k) }
One way to accomplish this:
rank_hash = {"Listen" => 1, "Download" => 60, "Share" => 150, "Purchase" => 700 }
rank_array = rank_hash.to_a
Than call this to get random array sample of the k/v pair:
rank_array[rand(0..3)]
or this to not hard-code the arrays length:
rank_array[rand(0..(rank_array.length) -1)]
Example:
["Download", 60]
I have an array with let's say, 500 elements. I know I can select the first 100 by doing .first(100), my question is how do I select elements from 100 to 200?
You can use ranges in the array subscript:
arr[100..200]
You can do it like this:
array[100..200] # returns the elements in range 100..200
# or
array[100,100] # returns 100 elements from position 100
More Information
dvcolgan’s answer is right, but it sounds like you might be trying to break your array into groups of 100. If that’s the case, there’s a convenient built-in method for that:
nums = (1..500).to_a
nums.each_slice(100) do |slice|
puts slice.size
end
# => 100, 100, 100, 100, 100
sample_array = (1..500).to_a
elements_100_to_200 = sample_array[100..200]
You can pass a range as index to an array and get a subarray with the queried elements from that subrange.
new_array = old_array.first(200) - old_array.first(100)