`
Hooopo
  • 浏览: 329892 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

shuffle in Array

    博客分类:
  • Ruby
阅读更多

# Timing different way to shuffle an array in ruby

class Array

  # The ruby way of swapping two variable values

  def swap!(a,b)
    self[a], self[b] = self[b], self[a]
  end


  # the "assembler" way of swapping two variable
values

 
def swap_with_int_var!(a,b)
    c = self[a]
    self[a] = self[b]
    self[b] = c
  end


  # Shuffling arrays is usually done by iterating through the
indices, and swapping
  # each value with a value at a random position

  # shuffling based on push/delete

 
def shuffle!
    size.downto(1) { |n| push delete_at(rand(n)) }
    self
  end


  # shuffling with the ruby way of swapping

 
def shuffle_II
    (size-1).downto(1) { |n| swap!(n, rand(size)) }
    self
  end


  # shuffling with the "assembler" way of swapping

 
def shuffle_III
    (size-1).downto(1) { |n| swap_with_int_var!(n, rand(size)) }
    self
  end



 
def shuffle_IV
    sort_by { rand }
  end

                                                           
 
def shuffle_V
    (length - 1).downto 1 do |slot|
      source = rand(slot + 1)
      self[slot], self[source] = self[source], self[slot]
    end
    self
  end
end



def time_shuffle_method(size)
  a = (0..size).to_a

  start_time = Time.new
  3000.times { yield a }
  end_time = Time.new

  return end_time - start_time
end


# To inspect shuffling methods, invoke with argument "test"
and optionally, size

if (ARGV[0] == 'test')                                      
  size =  ARGV[1] ? ARGV[1].to_i : 5
  puts (0..size).to_a.shuffle!
  puts '--'
  puts (0..size).to_a.shuffle_II
  puts '--'
  puts (0..size).to_a.shuffle_III
  puts '--'
  puts (0..size).to_a.shuffle_IV
  puts '--'
  puts (0..size).to_a.shuffle_V

  exit
end


shuffle_time = time_shuffle_method(500) { |a| a.shuffle! }
puts "Time elapsed for shuffle!    : #{shuffle_time}"

shuffle_time_II = time_shuffle_method(500) { |a| a.shuffle_II }
puts "Time elapsed for shuffle_II  :
#{shuffle_time_II}"

shuffle_time_III = time_shuffle_method(500) { |a| a.shuffle_III
}
puts "Time elapsed for shuffle_III : #{shuffle_time_III}"

shuffle_time_IV = time_shuffle_method(500) { |a| a.shuffle_IV }
puts "Time elapsed for shuffle_IV  :
#{shuffle_time_IV}"

shuffle_time_V  = time_shuffle_method(500) { |a| a.shuffle_V  }
puts "Time elapsed for shuffle_V   : #{shuffle_time_V
}"

=begin

  Here are results from running on my machine

  Conclusion: fancy ruby manipulations take their time
  Stick with the "ordinary" shuffle implementation
( shuffle_III )

stephan@[~/ruby/steam]: ruby /tmp/shuffle_timer
Time elapsed for shuffle!    : 4.352824
Time elapsed for shuffle_II  : 6.03016
Time elapsed for shuffle_III : 3.088946
Time elapsed for shuffle_IV  : 3.890105
Time elapsed for shuffle_V   : 6.351477
stephan@[~/ruby/steam]: ruby /tmp/shuffle_timer
Time elapsed for shuffle!    : 4.382251
Time elapsed for shuffle_II  : 6.046666                     
Time elapsed for shuffle_III : 3.220461
Time elapsed for shuffle_IV  : 4.00079
Time elapsed for shuffle_V   : 6.292253

=end
分享到:
评论

相关推荐

    leetcode伪代码-shuffle_the_array:shuffle_the_array

    leetcode伪代码suffle_the_array 题目解读: 题目来源: 原文: Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn]. Return the array in the form [x1,y1,x2,y2,...,xn,yn]. ...

    Python实现随机取一个矩阵数组的某几行

    for i in range(10): array = np.vstack((array, [i+1, i+1])) print(array) # [[ 0 0] # [ 1 1] # [ 2 2] # [ 3 3] # [ 4 4] # [ 5 5] # [ 6 6] # [ 7 7] # [ 8 8] # [ 9 9] # [10 10]] rand_arr = np.arange...

    lodash underscore js库速查手册

    _.map(list, iterator, [context]) Alias: collect Produces a new array of values by mapping each value in list through a transformation function ( _.reduce(list, iterator, memo, [context]) Aliases: ...

    leetcode伪代码-shuffle-string:随机串

    leetcode伪代码shuffle-string 题目解读: 题目来源: 原文: Given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position ...

    php对数组内元素进行随机调换的方法

    分享给大家供大家参考。具体分析如下: 这是一个自定义的php数组元素随机调换的函数,php已经有一个内置的同样功能的函数shuffle($... shuffle($Array); // // http://de2.php.net/manual/de/function.shuffle.php // f

    resnet50图片分类作业.zip

    ④ Read all the pictures in the folder, read the pictures as data, change the picture size, convert it into array, and label the pictures ⑤ Divide the training set and test set, and encode the tag ...

    numpy的Fancy Indexing和array比较详解

    np.random.shuffle(x) print(x) #打印所有的元素 print(x[2])#获取某个元素的值 print(x[1:3])#切片 print(x[3:9:2])#指定间距切片 index = [2,4,7,9] #索引数组 print(x[index])#获取索引数组中的元素的值 ind = np...

    fisher-yates:一个紧凑的模块,可以对数组进行随机排序

    渔民 一个紧凑的模块,用于对数组进行随机排序。... var shuffleInplace = require ( 'fisher-yates/inplace' ) var array = [ 1 , 2 , 3 ] shuffleInplace ( array ) console . log ( array ) // => [2, 1, 3]

    LeetCode最全代码

    421 | [Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/) | [C++](./C++/maximum-xor-of-two-numbers-in-an-array.cpp) [Python](./Python/...

    PHP ORM(面向对象PDO数据库框架&API框架)

    //$user->set_where_and(User::$field_age, SqlOperator::In, array(27, 29)); //$user->set_where_and(User::$field_regtime, SqlOperator::LessThan, '-6 month'); //创建数据库连接 $db = create_pdo(); $...

    picu:PICU是Carbon的公用事业

    array ; 之间 在每个单元格之间插入一个新值 var a = [ 1 , 2 , 3 ] ; var b = arrayUtils . inbetween ( a , 'x' ) ; // b -> [1, 'x', 2, 'x', 3] .shuffle 随机排列数组 var a = [ 1 , 2 , 3 ] ; var b = ...

    tensorflow使用range_input_producer多线程读取数据实例

    inputs = tf.slice(array, [i * BATCH_SIZE], [BATCH_SIZE]) 原理解析: 第一行会产生一个队列,队列包含0到NUM_EXPOCHES-1的元素,如果num_epochs有指定,则每个元素只产生num_epochs次,否则循环产生。shuffle指定...

    VB编程资源大全(英文源码 其它)

    array.zip A simple program that shows how a two-dimensional array works within a VB program.<END><br>70,Bubblesort.zip A simple Bubble Sort code that shows how the program works within a VB ...

    判断numpy 中 infinite 和NAN的问题

    上面的vec是一个np array,可以判断数组中的任意元素是否合法,特别适合放在train或者shuffle之前 np.isfinite(vec).all() 判断是否为无限大,vec是一个np array,return 返回值依然是 True False np.isfini

    python飞机大战

    random.shuffle(perm) groups = groups[perm] batch_data = [] for i in range(0, num_batchs): index = groups == i batch_data.append(self.x[:, index]) return batch_data def rbmBB(self, x): self.x ...

    PHP和MySQL Web开发第4版pdf以及源码

    3.8.1 使用shuffle()函数 3.8.2 使用array_reverse()函数 3.9 从文件载入数组 3.10 执行其他的数组操作 3.10.1 在数组中浏览:each()、current()、reset()、end()、next()、pos()和prev() 3.10.2 对数组的每一...

    PHP和MySQL WEB开发(第4版)

    3.8.1 使用shuffle()函数 3.8.2 使用array_reverse()函数 3.9 从文件载入数组 3.10 执行其他的数组操作 3.10.1 在数组中浏览:each()、current()、reset()、end()、next()、pos()和prev() 3.10.2 对数组的每一个元素...

    PHP和MySQL Web开发第4版

    3.8.1 使用shuffle()函数 3.8.2 使用array_reverse()函数 3.9 从文件载入数组 3.10 执行其他的数组操作 3.10.1 在数组中浏览:each()、current()、reset()、end()、next()、pos()和prev() 3.10.2 对数组的每一...

Global site tag (gtag.js) - Google Analytics