Shuffle an array in ruby

Ruby program for Shuffle an array. Here more information.

#  Ruby program for
#  Shuffle the array elements
class Shuffling 
	#  Function which is swapping two array elements 
	#  of given location
	def swapElement(arr, i, j) 
		#  Get i location element
		temp = arr[i]
		#  Set new values
		arr[i] = arr[j]
		arr[j] = temp
	end

	#  Returns the random location of array elements
	def randomLocation(min, max) 
		r = Random.new
        # Calculate random number between given range
        return r.rand(min...max)
	end

	#  Function which is shuffle given array elements
	def shuffleElement(arr, size) 
		#  (i,j) indicate locations
		j = 0
		i = 0
		#  Variable which is controlling the 
		#  execution process of loop
		counter = 0
		#  Loop which is shuffling random elements in array
		while (counter < size) 
			#  Get random location of array index
			i = self.randomLocation(0, size)
			j = self.randomLocation(0, size)
			if (i != j) 
				#  Swap array elements
				self.swapElement(arr, i, j)
				counter += 1
			end
		end
	end

	#  Function which is display array elements
	def display(arr, size) 
		i = 0
		while (i < size) 
			#  Disply element value
			print("  ", arr[i])
			i += 1
		end
		print("\n")
	end
end

def main() 
	task = Shuffling.new()
	#  Define array of integer elements
	arr = [1, 0, -3, 8, 7, 3, 9, 4, 2, 5, 10, 6]
	size = arr.length
	#  Before shuffling  array elements
	print(" Initial array elements\n")
	task.display(arr, size)
	print(" After Shuffle array elements\n")
	task.shuffleElement(arr, size)
	task.display(arr, size)
	task.shuffleElement(arr, size)
	task.display(arr, size)
	task.shuffleElement(arr, size)
	task.display(arr, size)
end

main()

Output

 Initial array elements
  1  0  -3  8  7  3  9  4  2  5  10  6
 After Shuffle array elements
  2  7  -3  6  1  9  10  4  5  3  0  8
  10  8  -3  6  0  1  4  9  5  7  3  2
  7  6  -3  5  3  8  4  9  2  0  1  10


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved