Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use JS shuffle algorithm

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use JS shuffle algorithm", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "how to use JS shuffle algorithm"!

Js random shuffle algorithm lies in how to sort an array randomly and get a random array. There are some codes on the Internet that are not completely random.

Js shuffle algorithm process

1. Loop this array in reverse order

two。 Take a random number k in the range from 1 to n

3.k and n exchange

4. Until it loops to the first element of the array

Shuffle algorithm-js implementation

/ * *

Shuffle algorithm

Scene: 100 numbers are randomly generated, the number range is 1-100, and they are not repeated.

* /

Functionshuffle2 (arr) {/ / time complexity O (nlogn)

Arr.sort (() = > Math.random ()-0.5)

}

Functionshuffle (arr) {/ / time complexity O (n)

Arr=arr.concat ()

Lettemp=null

Letr=Math.random () * arr.length | 0

For (leti=0;i

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report