0

I am trying to sort large inputs in the fastest way in ascending order. The code is something like this:

t=gets
ti=t.to_i
r=[]
for i in(0..ti)
    k=gets
    r[i]=k.to_i
end
r.sort_by{|x| -x.last}

This is giving me an error saying undefined method 'last' for nil:nilclass <nomethoderror> from tsort.rb: in sort_by from tsort.rb in 'each' from tsort.rb in 'sort_by'

I don't know where am I wrong.

That's what I have tried for sorting an array...which is r[] which has all the numbers in t! Can anyone please help.

My inputs are less than 10^6!

2
  • 5
    Try to give you're variable names more meaning. Its a bit difficult to read. Commented May 28, 2009 at 13:39
  • Apparently some of your Array elements are nil. That is strange, because you explicitly call to_i on all arguments. Even nil.to_i is 0. Can you let us know which input you are supplying? Is this exactly identical to your production code? Commented May 28, 2009 at 13:56

3 Answers 3

4

I can't reproduce your exact error, I get undefined method 'last' for n:Fixnum (NoMethodError). That makes sense, because you're calling the last method on x, which will hold the values of your Array r, all Fixnums, which do not have a last method.

It should work if you replace the last line with:

r.sort

The sort method will sort your Array in ascending order by default.

Sign up to request clarification or add additional context in comments.

Comments

3

If you want to sort a list of integers taken from STDIN I suggest something like the following:

lines = STDIN.readlines.map { |x| x.strip.to_i }.sort
puts lines.join(', ')

It's cleaner, more rubyish and faster (read the documentation for Enumerable.sort_by to see why sort is a better alternative to sort_by).

I also see your code expects a number that says how many lines to read. You can get the same behavior by modifying the example above as follows:

line_count = gets.strip.to_i
lines = (1..line_count).collect { gets.strip.to_i }.sort
puts lines.join(', ')

2 Comments

i want to sort a particular quantity of numbers , that i will take as input so how to do t using lines = STDIN.readlines.map { |x| x.strip.to_i }.sort puts lines.join(', ')
@mekasperasky: I've edited my answer to reflect your requirement.
0

Try the sort function on Array's think it does what you need.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.