일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
Tags
- Decorator
- 시바견
- DWG
- 30. Substring with Concatenation of All Words
- attribute
- kaggle
- 컴퓨터의 구조
- Python Code
- 715. Range Module
- Protocol
- 파이썬
- Convert Sorted List to Binary Search Tree
- Python Implementation
- shiba
- Substring with Concatenation of All Words
- Class
- 운영체제
- 43. Multiply Strings
- LeetCode
- concurrency
- 프로그래머스
- 315. Count of Smaller Numbers After Self
- Python
- Regular Expression
- t1
- 109. Convert Sorted List to Binary Search Tree
- iterator
- 밴픽
- data science
- Generator
Archives
- Today
- Total
Scribbling
Shuffle Algorithm: Knuth Shuffle 본문
Computer Science/Algorithms & Data Structures
Shuffle Algorithm: Knuth Shuffle
focalpoint 2022. 1. 15. 22:53This post is about Knuth Shuffle, a shuffle algorithm.
- This algorithm allows random shuffle, giving all permuations of array equal likelihood.
- No need for additional arrays, so memory complexity is O(1).
- Time complexity is O(N)
Code is pretty simple as below.
To give all permuations of a particular array equal likelihood, all the number should have the same probability to be placed in a certain index.
So, while iterating all the indexes (i), choose a random index (j) in range [i, len(x)-1] and swap their values. Here, range of j should include i so that certain index's numbers can stay the same.
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def shuffle(x):
import random
for i in range(0, len(x)-1):
j = random.randint(i, len(x)-1)
x[i], x[j] = x[j], x[i]
shuffle(x)
print(x)
'Computer Science > Algorithms & Data Structures' 카테고리의 다른 글
Monotonic Stack (0) | 2022.08.08 |
---|---|
LeetCode: 839. Similar String Groups (0) | 2022.05.25 |
AVL Tree, Python Code (0) | 2022.01.07 |
Segment Tree, Python Implementation (0) | 2022.01.06 |
Priority Queue (0) | 2021.12.22 |