Get the sum of all keys in ruby - ruby

How would I get the sum of keys if they have different values in ruby?
{"dog"=>1, "cat"=>3, "fish"=>5} = 9

The keys in your example are strings, the values are integers. If you want the sum of the integers you can do hash.values.sum:
{"dog"=>1, "cat"=>3, "fish"=>5}.values.sum
#=> 9

Related

Random Number in julia [duplicate]

This question already has an answer here:
Generating a random integer in range in Julia
(1 answer)
Closed 1 year ago.
I want to make a random number between 1 and 30
I read the document but i can't find a method for do it
for example we do it in php by
rand(1 , 30);
How can i handle it
It's explained in the docs https://docs.julialang.org/en/v1/stdlib/Random/#Base.rand
rand([rng=GLOBAL_RNG], [S], [dims...])
Pick a random element or array of random elements from the set of values specified by S; S can be
an indexable collection (for example 1:9 or ('x', "y", :z)),
an AbstractDict or AbstractSet object,
a string (considered as a collection of characters), or
a type: the set of values to pick from is then equivalent to typemin(S):typemax(S) for integers (this is not applicable to BigInt), to [0,1)[0, 1)[0,1) for floating point numbers and to [0,1)+i[0,1)[0, 1)+i[0, 1)[0,1)+i[0,1) for complex floating point numbers;
S defaults to Float64. When only one argument is passed besides the optional rng and is a Tuple, it is interpreted as a collection of values (S) and not as dims.
For your example it would be
rand(1:30)
You can pass ranges to the rand function to generate a number between two other numbers, included:
julia> rand(1:30)
24
julia> rand(1:30)
18

Role of the remainder operator to determine an index in an hash algorithm

I am studying the hash algorithm in a book and come across this line
the index is 3 + 2 + 17 % 10 = 22 % 10 = 2
I can understand that is referring that the index is 2, and the % is a remainder, but is too much esoteric to understand.
Here below the context where is explained where this index comes from, namely is an exercise of the book
Suppose you have these four hash functions that work with strings: A.
Return “1” for all input. B. Use the length of the string as the
index. C. Use the first character of the string as the index. So, all
strings starting with a are hashed together, and so on. D. Map every
letter to a prime number: a = 2, b = 3, c = 5, d = 7, e = 11, and so
on. For a string, the hash function is the sum of all the characters
modulo the size of the hash. For example, if your hash size is 10, and
the string is “bag”, the index is 3 + 2 + 17 % 10 = 22 % 10 = 2. For
each of the following examples, which hash functions would provide a
good distribution? Assume a hash table size of 10 slots.
5.5 A phonebook where the keys are names and values are phone numbers. The names are as follows: Esther, Ben, Bob, and Dan. Answer: Hash
functions C and D would give a good distribution.
Your example shows 4 hash-functions (A-D). Each of the functions return a value used to place the word (string) in a bucket.
A. All words will go to same bucket, the function returns 1. There is not a good distribution.
B. All words will be sorted on the length of the string. There will be not be many words in the first bucket, only "a" or "I" as far as I can think of. Where as buckets 3-6 will be heavily occupied.
C. now the words are sorted on the first letter, we have 26 letters in the alphabet but not all words are evenly presented (words starting with x is way less than words starting with h)
D. has most likely the best distribution as it uses prime numbers. The word "bag" is the sum of (b=3 + a=2 + g=17) = 22.
For function B-D, the result can be bigger than 10. So in the example, the results are divided by 10 and the remainder is used to conclude the bucket the word is going to.
The slot index must be an integer in range [0,9]. The remainder function (for divisor 10) maps all integers to that range in the most uniform way.

How to find two elements that have smallest difference in an array?

How do I find two elements in an array that have the smallest difference?
In other words, how to find two elements that have a the smallest standard deviation.
For instance, if I have an array like:
arr = [158,2,15,38,17,91]
the result would be 15 and 17.
I assume the question is, "for which two elements of the array is the absolute value of their difference minimum?".
arr.combination(2).min_by { |a,b| (a-b).abs }
#=> [15, 17]
See Array#combination and Enumerable#min_by.

Calculate Median in An Array - Can someone tell me what is going on in this line of code?

This is a solution for calculating the median value in an array. I get the first three lines, duh ;), but the third line is where the magic is happening. Can someone explain how the 'sorted' variable is using and why it's next to brackets, and why the other variable 'len' is enclosed in those parentheses and then brackets? It's almost like sorted is all of a sudden being used as an array? Thanks!
def median(array)
sorted = array.sort
len = sorted.length
return ((sorted[(len - 1) / 2] + sorted[len / 2]) / 2.0).to_f
end
puts median([3,2,3,8,91])
puts median([2,8,3,11,-5])
puts median([4,3,8,11])
Consider this:
[1,2,2,3,4] and [1,2,3,4]. Both arrays are sorted, but have odd and even numbers of elements respectively. So, that piece of code is taking into account these 2 cases.
sorted is indeed an array. You sort [2,3,1,4] and you get back [1,2,3,4]. Then you calculate the middle index (len - 1) / 2 and len / 2 for even / odd number of elements, and find the average of them.
Yes, array.sort is returning an array and it is assigned to sorted. You can then access it via array indices.
If you have an odd number of elements, say 5 elements as in the example, the indices come out to be:
(len-1)/2=(5-1)/2=2
len/2=5/2=2 --- (remember this is integer division, so the decimal gets truncated)
So you take the value at index 2 and add them, and then divide by 2, which is the same as the value at index 2.
If you have an even number of elements, say 4,
(len-1)/2=(4-1)/2=1 --- (remember this is integer division, so the decimal gets truncated)
len/2=4/2=2
So in this case, you are effectively averaging the two middle elements 1 and 2, which is the definition of median for when you have an even number of elements.
It's almost like sorted is all of a sudden being used as an array?
Yes, it is. On line 2 it's being initialized as being an array with the same elements as the input, but in ascending order (default sort is ascending). On line 3 you have len which is initialized with the length of the sorted array, so yeah, sorted is being used as an array since then, because that's what it is.

How to generate all unique 4 character permutations of a seed string? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Algorithm to return all combinations of k elements from n
Generate Distinct Combinations PHP
I have an array containing a number of characters/letter,s e.g:
$seed = array('a','b','c','d','e','f',.....,'z','1','2','3',...'9');
I want to get all possible unique 4 character combinations/permutations from the seed, for example:
abcd, azxy, ag12, aaaa, etc
What's the best way to accomplish this?
I have thought about dividing the seed array into 4 letter groups, then go through each group and generate all possible combinations of that group, but that will leave out many combinations (i.e it will process abcd and wxyz, but not abyz and wxcd)
For each character in the array, write that character followed by each of the unique 3 character strings either from the characters after it (if you actually mean combinations) or from all the characters (which is what I think you mean).
How to generate all unique 3 character permutations of a seed string?
See this very similar question.
You may also want to read about recursion.
Python code
>>> def product(chars, n):
if n == 0:
yield ''
else:
for c in chars:
for result in product(x, n - 1): # Recursive call
yield c + result
>>> list(product(['a', 'b', 'c'], 2))
['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']
(Note: in real Python code you should use itertools.product rather than writing it yourself.)
Generating permutations is like summing up numbers. This is beautifully explained in the freely available book Higher Order Perl, page 128

Resources