I'm using geokit to give me distances between two post codes. I need to determine which post code is the nearest.
point_a = Geokit::Geocoders::GoogleGeocoder.geocode "se18 7hp"
alpha = ["cr0 3rl", "W2 1AA"]
miles = alpha.map do |m| point_a.distance_to(m) end
miles.min # => 11.005310790913377
How do I do the reverse of miles.min to get to know which post code was the nearest from point_a?
To get the index of an array element, use Array#index
So, in your case, it will be
alpha[miles.index(miles.min)]
Related
I am fairly new to this so I apologize in advance of my newbieness. I have been working on a project that I want to get the sum, highest,lowest out of a hash/array. I have tried numerous times to get this right but I typically will get an error such as, fixNum cannot convert int to string and undefined method. I will attempt to fix these issues and then run into another issue so I am at a loss. For the record in my text file I have 1,Foo,22 2,Smith,30 my output looks like this {1=>["Foo",22], 2=>["Smith",30]} I would like the highest number to show 30, lowest to be 22 and total to be 52 for different outputs.
You can do as below suppose lets say a variable a = {a: [a,1],b: [b,1] } then
values = a.values.map(&:last) //Gives the last element of each array
max= a.max
min = a.min
sum = a.sum
Okay, this is very ugly and someone will probably improve upon it but it works. Assuming I understand the output you would like.
elements = h.map{ |element| element[1] }.map { |element| element[1]}
# sum
elements.sum
# highest
elements.max
# lowest
elements.min
https://repl.it/repls/AntiqueOldfashionedRom
Convert to hash and calculate min max based on values
data = "1,Foo,22 2,Smith,30"
people =
data.split(",")
.each_slice(3)
.map {|slice| [slice[0], [slice[1], slice[2]]] }
.to_h
values = people.values.map {|person| person[1] }
min = values.min
max = values.max
sum = values.sum
I found the below code to segment the images using K means clustering,but in the below code,they are using some calculation to find the min,max values.I know the basic concept of K-means algorithm.but I couldn't understand this code.Can any one please explain.
function [Centroid,new_cluster]=kmeans_algorithm(input_image,k)
% k = 4;
input_image=double(input_image);
new_image=input_image;
input_image=input_image(:);
min_val=min(input_image);
input_image=round(input_image-min_val+1);
length_input_image=length(input_image);
max_val=max(input_image)+1;
hist_gram=zeros(1,max_val);
hist_gram_count=zeros(1,max_val);
for i=1:length_input_image
if(input_image(i)>0)
hist_gram(input_image(i))=hist_gram(input_image(i))+1;
end;
end
IDX=find(hist_gram);
hist_length=length(IDX);
Centroid=(1:k)*max_val/(k+1);
while(true)
old_Centroid=Centroid;
for i=1:hist_length
new_val=abs(IDX(i)-Centroid);
hist_val=find(new_val==min(new_val));
hist_gram_count(IDX(i))=hist_val(1);
end
for i=1:k,
loop_count=find(hist_gram_count==i);
Centroid(i)=sum(loop_count.*hist_gram(loop_count))/sum(hist_gram(loop_count));
end
if(Centroid==old_Centroid) break;end;
end
length_input_image=size(new_image);
new_cluster=zeros(length_input_image);
for i=1:length_input_image(1),
for j=1:length_input_image(2),
new_val=abs(new_image(i,j)-Centroid);
loop_count=find(new_val==min(new_val));
new_cluster(i,j)=loop_count(1);
end
end
Centroid=Centroid+min_val-1;
especially what's the purpose of this input_image(:)in the above code. In google they said it like matrix.but still I'm confused,whether this is matrix or array
The notation (:) collapses a multi-dimensional vector into a column vector.
data = rand(10,4);
size(data(:))
% 40 1
Then you can apply a normal function to an entire multi-dimensional array
min(data(:));
Instead of to each dimension independently
min(min(data));
In the code that you have posted, they collapse input_image to a column vector just to make it easier to apply functions like min, max, and length.
Update
The code that you have posted doesn't actually perform k-means clustering. It simply creates a histogram of all values in the image. They use min and max to determine the number of bins to use for the histogram.
I am trying to calculate distance between two points in kilometers but it is giving me wrong.
location.each do |loc|
distance = Haversine.distance(28.6139, 77.209, loc[:lat].to_f, loc[:long].to_f).to_km
puts " #{distance}"
end
Here is the distance which I am getting and which is wrong
7385.99072855455
7383.795725224046
7392.13122601482
7391.537885880786
The data of the location is in my database
[{"id":1,"lat":28.6139,"lng":77.209,"location":"","object_id":1,"created_at":"2016-06-07T05:46:53.000Z","updated_at":"2016-06-07T05:46:53.000Z","object_type":"abc"},{"id":2,"lat":28.6692,"lng":77.4538,"location":"","object_id":2,"created_at":"2016-06-07T05:49:23.000Z","updated_at":"2016-06-07T05:49:23.000Z","object_type":"cde"},{"id":3,"lat":28.4595,"lng":77.0266,"location":"","object_id":3,"created_at":"2016-06-07T05:50:22.000Z","updated_at":"2016-06-07T05:50:22.000Z","object_type":"ggg"},{"id":4,"lat":28.4744,"lng":77.504,"location":"","object_id":4,"created_at":"2016-06-07T05:50:24.000Z","updated_at":"2016-06-07T05:50:24.000Z","object_type":"eerr"}]
You have a typo: loc[:long] instead of loc[:lng], the line should read:
Haversine.distance(28.6139, 77.209, loc[:lat].to_f, loc[:lng].to_f).to_km
You passed nil.to_f as _longitude of the second point. This is equivalent to passing 0
I have an array of arrays, like so:
[['1','2'],['a','b'],['x','y']]
I need to combine those arrays into a string containing all possible combinations of all three sets, forward only. I have seen lots of examples of all possible combinations of the sets in any order, that is not what I want. For example, I do not want any of the elements in the first set to come after the second set, or any in the third set to come before the first, or second, and so on. So, for the above example, the output would be:
['1ax', '1ay', '1bx', '1by', '2ax', '2ay', '2bx', '2by']
The number of arrays, and length of each set is dynamic.
Does anybody know how to solve this in Ruby?
Know your Array#product:
a = [['1','2'],['a','b'],['x','y']]
a.first.product(*a[1..-1]).map(&:join)
Solved using a recursive, so-called "Dynamic Programming" approach:
For n-arrays, combine the entries of the first array with each result on the remaining (n-1) arrays
For a single array, the answer is just that array
In code:
def variations(a)
first = a.first
if a.length==1 then
first
else
rest = variations(a[1..-1])
first.map{ |x| rest.map{ |y| "#{x}#{y}" } }.flatten
end
end
p variations([['1','2'],['a','b'],['x','y']])
#=> ["1ax", "1ay", "1bx", "1by", "2ax", "2ay", "2bx", "2by"]
puts variations([%w[a b],%w[M N],['-'],%w[x y z],%w[0 1 2]]).join(' ')
#=> aM-x0 aM-x1 aM-x2 aM-y0 aM-y1 aM-y2 aM-z0 aM-z1 aM-z2 aN-x0 aN-x1 aN-x2
#=> aN-y0 aN-y1 aN-y2 aN-z0 aN-z1 aN-z2 bM-x0 bM-x1 bM-x2 bM-y0 bM-y1 bM-y2
#=> bM-z0 bM-z1 bM-z2 bN-x0 bN-x1 bN-x2 bN-y0 bN-y1 bN-y2 bN-z0 bN-z1 bN-z2
You could also reverse the logic, and with care you should be able to implement this non-recursively. But the recursive answer is rather straightforward. :)
Pure, reduce with product:
a = [['1','2'],['a','b'],['x','y']]
a.reduce() { |acc, n| acc.product(n).map(&:flatten) }.map(&:join)
# => ["1ax", "1ay", "1bx", "1by", "2ax", "2ay", "2bx", "2by"]
As far as I understood, matrices are very inflexible to work with. Therefor, I'm trying to get an array of vectors do deal with. My needs are: to be able to add vectors and make arithmetical operations on their components. Writing the code below,
require 'matrix'
x = Matrix.rows( IO.readlines("input.txt").each {|line| line.split} )
puts x.row_vectors
ruby falls into an exception. Why?
matrix.rb:1265:in `to_s': undefined method `join' for "1.2357 2.1742 -5.4834 -2.0735":String (NoMethodError)
OK then, I've calmed down and tried another approach. I wrote:
a = Array.[]( IO.readlines("input.txt").each {|line| Vector.[](line.split) } )
But the only way I can access my vectors inside an array is adressing the second index:
puts a[0][0]
This means, that when I would like to access desired scalar inside a vector, I'll will be forced to use the third index, like:
puts a[0][0][1]
So, the second question is - where the hell that second index comes from? How to get rid of it? Am I missing something when reading data into array?
I can't reproduce your first problem. Extracting what looks like input.txt, I can execute that first expression without an exception.
As to the second question, your expression seems kind of complex. How about:
b = IO.readlines("input.txt").map { |x| x.split(' ') }
This will get you a "2D" array of arrays, and you will need only two subscripts. (As to your question about where did the extra array come from, you got one from the Array constructor, one from IO.readlines, and one from the Vector constructor . . . I think.)
Or maybe:
result = []
IO.foreach('input.txt') { |ln| result << ln.split(' ') }