Project1

标题: 新人问个问题,生成3个随机数字abc,并把他们排序。 [打印本页]

作者: RGSS_2    时间: 2014-2-6 20:21
标题: 新人问个问题,生成3个随机数字abc,并把他们排序。
恩,就是这样。

Q%`4XS6_8IP_1D1C`G_Z](U.jpg (16.79 KB, 下载次数: 34)

Q%`4XS6_8IP_1D1C`G_Z](U.jpg

]_~NKE~2NRHKONIE_[}TM2T.jpg (49.01 KB, 下载次数: 30)

这是我做的,可还是少点什么

这是我做的,可还是少点什么

作者: RGSS_2    时间: 2014-2-6 20:51
我刚学,不怎么会额。
作者: SuperMario    时间: 2014-2-7 00:49
方法可以返回3个参数的,就是一个数组。
作者: 铃仙·优昙华院·因幡    时间: 2014-2-7 12:25

  1. a = []
  2. 0...3.times do |number|
  3.   a << rand(100)
  4. end
  5. p a.sort
复制代码
得到的就是排好顺序的数字了.

如果你想获取的是一串数字里最大或者最小的那个, 也可以用默认的方法来解决.

  1. a = []
  2. 0...3.times do |number|
  3.   a << rand(100)
  4. end
  5. p a.max # 获取最大的
  6. p a.min # 获取最小的
复制代码
再或者不想用默认的方法的话, 也可以借用 冒泡排序 的算法来解决.

  1. a = []
  2. 0...3.times do |number|
  3.   a << rand(100)
  4. end
  5. max_number = 0
  6. for i in a
  7.   max_number = i if max_number < i
  8. end
  9. p max_number
复制代码

作者: RGSS_2    时间: 2014-2-7 12:50
铃仙·优昙华院·因幡 发表于 2014-2-7 12:25
得到的就是排好顺序的数字了.

如果你想获取的是一串数字里最大或者最小的那个, 也可以用默认的方法来解决. ...
  1. def m (a)
  2.    d = a   
  3.    return d
  4.   end
  5. mer = m   (rand(100) ).to_s
  6.   p mer
  7.   
  8. def ma(b)
  9.    d = b  
  10.    return d
  11.   end
  12. maer = ma  (rand(100) ).to_s
  13.   p maer
  14.   
  15.    def max(c)
  16.    d = c   
  17.    return d
  18.   end
  19. maxer = max(rand(100) ).to_s
  20.   p maxer
  21.   
  22.   e = [mer, maer,maxer]
  23.    p  [e[0],e[1],e[2]] if e[0]>e[1] and e[0]>e[2] and e[1]>e[2]
  24.    p  [e[0],e[2],e[1]] if e[0]>e[1] and e[0]>e[2] and e[2]>e[1]
  25.    
  26.    p  [e[1],e[0],e[2]] if e[1]>e[0] and e[1]>e[2] and e[0]>e[2]
  27.    p  [e[1],e[2],e[0]] if e[1]>e[0] and e[1]>e[2] and e[2]>e[0]
  28.    
  29.    p  [e[2],e[0],e[1]] if e[2]>e[0] and e[2]>e[1] and e[0]>e[1]
  30.    p  [e[2],e[1],e[0]] if e[2]>e[0] and e[2]>e[1] and e[1]>e[0]
复制代码
自己想了半天,就想出了这个。可我发现了个问题, 这是次排序的数量还好是3个,要是30个岂不是麻烦死?{:2_264:}新人刚学脚本,你那个我看的不是特别懂(我自己太笨)。
作者: RGSS_2    时间: 2014-2-7 12:56
RGSS_2 发表于 2014-2-7 12:50
自己想了半天,就想出了这个。可我发现了个问题, 这是次排序的数量还好是3个,要是30个岂不是麻烦死?{: ...

   e = [rand(100), rand(100),rand(100)]
   p  [e[0],e[1],e[2]] if e[0]>e[1] and e[0]>e[2] and e[1]>e[2]
   p  [e[0],e[2],e[1]] if e[0]>e[1] and e[0]>e[2] and e[2]>e[1]
   
   p  [e[1],e[0],e[2]] if e[1]>e[0] and e[1]>e[2] and e[0]>e[2]
   p  [e[1],e[2],e[0]] if e[1]>e[0] and e[1]>e[2] and e[2]>e[0]
   
   p  [e[2],e[0],e[1]] if e[2]>e[0] and e[2]>e[1] and e[0]>e[1]
   p  [e[2],e[1],e[0]] if e[2]>e[0] and e[2]>e[1] and e[1]>e[0]
这样应该比刚刚简单多。
作者: 铃仙·优昙华院·因幡    时间: 2014-2-7 12:59
RGSS_2 发表于 2014-2-7 12:56
e = [rand(100), rand(100),rand(100)]
   p  [e[0],e[1],e[2]] if e[0]>e[1] and e[0]>e[2] and e[1] ...

你这种写法连排序都算不上. 看看百科吧.

http://baike.baidu.com/link?url= ... IJvq-0cEA3EOpUrk6Rt
作者: fux2    时间: 2014-2-7 19:08
  1. a,b,c=rand(100),rand(100),rand(100)
  2. p a,b,c
  3. a,b,c=*[a,b,c].sort
  4. p a,b,c
复制代码
这么简单的事情为什么楼上的代码都那么长……




欢迎光临 Project1 (https://rpg.blue/) Powered by Discuz! X3.1