在玩一些Ruby代码来重新排序图像像素,并遇到了怪异的效果。
下面的代码加载一幅图像,将像素读取到一个数组中,对像素进行Array.sort
重新排序(使用意外的但显然有效的方式),然后创建另一个图像,使用相同的图像将重新排序的像素写入该图像原始图片的尺寸。
据此:Ruby的max函数顺序如何重复?不稳定意味着结果不可预测。但是,每次我使用相同的输入运行代码时,都会得到相同的输出,因此从这种意义上说,这种情况下的排序结果是可预测的。
排序算法不稳定意味着什么?在这种情况下如何应用?
该代码仅在使用以下操作系统的Mac上进行了测试:ruby 2.5.1p57(2018-03-29修订版63029)[x86_64-darwin16]。
require 'rmagick'
include Magick
img = ImageList.new("images/test-image.jpg")
pixels = img.get_pixels(0,0,img.columns,img.rows)
# https://apidock.com/ruby/Array/sort
# The block must implement a comparison between a and b and
# * <0 when b follows a,
# * 0 when a and b are equivalent,
# * >0 when a follows b
# The result is not guaranteed to be stable.
# When the comparison of two elements returns 0, the order of the elements …
Run Code Online (Sandbox Code Playgroud)