Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a 2d array with four columns (lettered A--D) and each column has three rows. Here is a visual representation of my array:

A  B  C  D  
1  3  9  0
2  8  2  1
8  4  10 3

I want to sort the columns by the smallest number in each column. This is how I want my array to look after sorting:

D  A  C  B
0  1  9  3
1  2  2  8
3  8  10 4

The D column is first because the smallest number in the column is 0, and 0 is the smallest among all columns' smallest numbers. A is next because the smallest number in A is 1, and 1 is smaller than 2 (the smallest number in column C) and 3 (the smallest number in column B).

Any help would be appreciated.

share|improve this question

put on hold as unclear what you're asking by sawa, infused, EdChum, Hbcdev, pushy yesterday

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.If this question can be reworded to fit the rules in the help center, please edit the question.

2  
Can you share your attempt? –  Nishu yesterday
2  
How does your 2d array look like in real implementation? Are the columns (cells) nested within rows, or vice versa? Your wording sounds like the latter, but I almost always see the former. –  sawa yesterday

2 Answers 2

up vote 2 down vote accepted

I think that will do:

arr = [[1,2,8], [3,8,4], [9,2,10], [0,1,3]]
arr.sort! { |a, b| a.min <=> b.min }
share|improve this answer
input = %q(1  3  9  0
2  8  2  1
8  4  10 3)

array = input.split("\n").map(&:split).transpose

result = array.map{|x| x.map(&:to_i).sort}.sort
#=> [[0, 1, 3], [1, 2, 8], [2, 9, 10], [3, 4, 8]]
share|improve this answer
    
May I ask why it was downvoted when it works correctly with the information provided in the problem? –  Nishu yesterday
    
I didn't downvote, but the way you built the input array is unnecessary. –  Mark Thomas yesterday
    
Just to help OP, as he did not mention how 2d array was created. –  Nishu yesterday
    
The OP said "here is a visual representation of my array", so we can assume he had a regular Ruby array, and he was trying to be helpful to us. Your assumption that he started with text is most likely incorrect. –  Mark Thomas yesterday
    
You're not asking why it was downvoted when it doesn't work correctly? –  sawa yesterday

Not the answer you're looking for? Browse other questions tagged or ask your own question.