Okay, much better only in a relative term, comparing to my earlier sorting which didn’t take care of duplicate elements. Two major changes here. 1. I do away with the temporary variable for holding on the smallest number result from each round of the comparison, instead elements are now passed over directly to the sorted […]
Finally have the time to come back to the sorting exercise, here is a slightly better version of sort. It still doesn’t take care of duplicate elements, but compare to the first sorting version, this one is shorter, as the whole finding smallest element left in the array is now done by inject and a […]
Apparently you can have optional parameter listed in the middle for your method in Ruby version 1.9 C:\>pik switch 191 C:\>irb irb(main):001:0> def talk(a,*b,c) irb(main):002:1> p a,b,c irb(main):003:1> end => nil irb(main):004:0> talk ‘a’,’b’,’c’ "a" ["b"] "c" => ["a", ["b"], "c"]C:\>pik switch 191 C:\>irb irb(main):001:0> def talk(a,*b,c) irb(main):002:1> p a,b,c irb(main):003:1> end => nil […]
A beautiful visualization of sorting algorithm… via Hacker News
Another way for factorial, extending the integer class, so the function will feel more natural, instead of fact 6 for example, you just call it by 6.fact. Also, added a function to sum up the factorial value, counting down. Example, for 6!, it will be 6! + 5! + 4! + 3! + 2! + […]
Hours ago I got a programming test question about factorial, which I didn’t do really well, only completed with the help of the interviewer. Damn. The worst thing is that I have done this question before, and I know in the head I can use recursion for it, but I totally go blank on how […]
Am running through “Learn to Program” from Chris Pine, again. I have been cracking my head on the exercise to write a sort method instead of just using the array#sort come with ruby. As the exercise actually came at the stage of the tutorial that more advanced techniques like ternary operator is yet to be […]
a = [9,5,6,3,7] a.sort { |x,y| x==5? 1:x<=>y } [3, 6, 7, 9, 5]a = [9,5,6,3,7] a.sort { |x,y| x==5? 1:x<=>y } [3, 6, 7, 9, 5] So, I sort the array consisting 9,5,6,3,7, run it through a block, put the elements to x and y then sort it in ascending order, except for the […]
And so I always understand it wrongly, 1 2 s = "hello" s[0,2] = "He"s = "hello" s[0,2] = "He" That I thought the second operand is the ending index, and that somehow it works like range, where 1 2 a = [1,2,3] a[0…2] = [1,2]a = [1,2,3] a[0…2] = [1,2] So, the last index […]
So glad when I come across rvm, but then I learned that it is only for Linux and OSX. I do work in Ubuntu sometimes, but other time I have to work in a Windows environment. Then, I discover pik, hey, doing the same thing for you, but in Windows. So now even in XP, […]