[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+152 -62
View File
@@ -2,87 +2,177 @@
id: wiki-2026-0508-randomized-algorithms
title: Randomized Algorithms
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [ALGO-RAND-001]
aliases: [Randomized Algorithms, Random Algorithms, 확률 알고리즘]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [algorithm, math, randomized-algorithms, probability, monte-carlo, las-vegas, Complexity-Theory]
confidence_score: 0.9
verification_status: applied
tags: [algorithms, randomization, probability, frontend]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: TypeScript
framework: none
---
# Randomized Algorithms (확률적 알고리즘)
# Randomized Algorithms
## 📌 한 줄 통찰 (The Karpathy Summary)
> "완벽한 정답을 위한 끝없는 계산보다, '적당한 무작위성'을 가미하여 기하급수적인 연산 속도와 충분히 훌륭한 해답을 쟁취하라" — 알고리즘의 동작 과정에 무작위성(Randomness)을 도입하여, 평균적으로 우수한 성능을 내거나 매우 복잡한 문제를 효율적으로 해결하는 방법론.
## 한 줄
> **"매 randomness 의 algorithmic resource 사용"**. Randomized algorithm 은 worst-case input adversary 회피 또는 simpler logic 으로 expected-time 성능 달성. Frontend 에서 quickselect, reservoir sampling, bloom filter, A/B bucketing 등 매 광범위 응용.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Stochastic Exploration and Error Probability [[Management|Management]]" — 모든 경우의 수를 따지는 대신 무작위 샘플링을 통해 정답에 근접하고(Monte Carlo), 혹은 항상 정답을 내놓되 실행 시간을 확률적으로 단축하는(Las Vegas) 패턴.
- **주요 알고리즘 분류:**
- **Las Vegas Algorithms:** 항상 정확한 정답을 내놓지만, 실행 시간이 확률 변수임 (예: Randomized QuickSort).
- **Monte Carlo Algorithms:** 정해진 시간 내에 실행되지만, 결과에 미세한 오차 가능성이 있음 (예: MCTS).
- **의의:** 결정론적(Deterministic) 알고리즘으로는 풀기 어려운 거대 규모의 데이터셋이나 복잡한 최적화 문제에서 '실용적인 효율성'을 보장하는 핵심 도구.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 무작위성은 '운'에 의존한다는 고정관념을 깨고, 이제는 알고리즘 설계에서 최악의 경우(Worst-case)를 방지하고 평균적인 성능을 극대화하기 위한 가장 정교한 수학적 장치로 평가됨.
- **정책 변화:** Antigravity 프로젝트는 에이전트의 경로 탐색([[Search|Search]])이나 대규모 문서 샘플링 시, 연산 자원을 아끼면서도 대표성 있는 결과를 얻기 위해 다양한 확률적 알고리즘 기법을 적용함.
### 매 두 가지 분류
- **Las Vegas**: 매 항상 correct 결과, runtime 만 random (e.g. randomized quicksort).
- **Monte Carlo**: 매 bounded runtime, 결과는 매 probability 1-ε 로 correct (e.g. Miller-Rabin, bloom filter).
## 🔗 지식 연결 (Graph)
- [[Monte-Carlo-Tree-Search-MCTS|Monte-Carlo-Tree-Search-MCTS]], [[Probability-Theory-Foundations|Probability-Theory-Foundations]], [[Optimization-Algorithms|Optimization-Algorithms]], [[Ranking-Algorithms|Ranking-Algorithms]]
- **Raw Source:** 10_Wiki/Topics/AI/Randomized-Algorithms.md
### 매 왜 frontend
- 매 large dataset (virtualized list, large table) 의 sampling.
- 매 client-side A/B test bucketing — deterministic hash + random salt.
- 매 game / animation 의 procedural generation.
- 매 dedup / membership test (bloom filter) 의 memory 절약.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Reservoir sampling — log streaming 의 fixed-size sample.
2. Quickselect — top-K 의 O(n) average.
3. Bloom filter — 매 service worker cache lookup.
4. Random shuffle — 매 Fisher-Yates 만 정답.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Fisher-Yates shuffle (매 in-place, uniform)
```ts
function shuffle<T>(arr: T[]): T[] {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Reservoir sampling (k items from stream)
```ts
function reservoir<T>(stream: Iterable<T>, k: number): T[] {
const reservoir: T[] = [];
let i = 0;
for (const item of stream) {
if (i < k) reservoir.push(item);
else {
const j = Math.floor(Math.random() * (i + 1));
if (j < k) reservoir[j] = item;
}
i++;
}
return reservoir;
}
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Quickselect (kth smallest, O(n) avg)
```ts
function quickselect(arr: number[], k: number, lo = 0, hi = arr.length - 1): number {
if (lo === hi) return arr[lo];
const pivotIdx = lo + Math.floor(Math.random() * (hi - lo + 1));
const pivot = arr[pivotIdx];
[arr[pivotIdx], arr[hi]] = [arr[hi], arr[pivotIdx]];
let store = lo;
for (let i = lo; i < hi; i++) {
if (arr[i] < pivot) {
[arr[i], arr[store]] = [arr[store], arr[i]];
store++;
}
}
[arr[store], arr[hi]] = [arr[hi], arr[store]];
if (k === store) return arr[store];
return k < store ? quickselect(arr, k, lo, store - 1) : quickselect(arr, k, store + 1, hi);
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Bloom filter (membership, frontend cache)
```ts
class BloomFilter {
private bits: Uint8Array;
constructor(private size: number, private k: number) {
this.bits = new Uint8Array(Math.ceil(size / 8));
}
private hash(s: string, seed: number): number {
let h = seed;
for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0;
return h % this.size;
}
add(s: string) {
for (let i = 0; i < this.k; i++) {
const idx = this.hash(s, i * 0x9e3779b1);
this.bits[idx >> 3] |= 1 << (idx & 7);
}
}
has(s: string): boolean {
for (let i = 0; i < this.k; i++) {
const idx = this.hash(s, i * 0x9e3779b1);
if (!(this.bits[idx >> 3] & (1 << (idx & 7)))) return false;
}
return true; // possible false positive
}
}
```
**기본값:**
> *(TODO)*
### A/B bucketing (매 deterministic hash + salt)
```ts
import { sha256 } from "@noble/hashes/sha256";
## ❌ 안티패턴 (Anti-Patterns)
function bucket(userId: string, exp: string, buckets: number): number {
const h = sha256(`${exp}:${userId}`);
const n = (h[0] << 24) | (h[1] << 16) | (h[2] << 8) | h[3];
return (n >>> 0) % buckets;
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Crypto-secure random (매 token, ID)
```ts
function secureId(bytes = 16): string {
const a = new Uint8Array(bytes);
crypto.getRandomValues(a);
return Array.from(a, b => b.toString(16).padStart(2, "0")).join("");
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Top-K from large array | Quickselect (O(n) avg) |
| Sample N from stream | Reservoir sampling |
| Membership test, big set | Bloom filter |
| Token / session ID | `crypto.getRandomValues` |
| A/B bucket | SHA-256 hash + modulo |
| Shuffle | Fisher-Yates 만 |
**기본값**: deterministic algorithm 우선 — randomization 은 매 measured benefit 있을 때 만.
## 🔗 Graph
- 부모: [[Algorithms]] · [[Probability]]
- 변형: [[Las-Vegas-Algorithms]] · [[Monte-Carlo-Methods]]
- 응용: [[Bloom-Filter]] · [[Reservoir-Sampling]] · [[Quickselect]] · [[AB-Testing]]
- Adjacent: [[Hashing]] · [[Data-Sketches]]
## 🤖 LLM 활용
**언제**: large dataset 의 sampling/selection, A/B bucketing, client-side dedup, security-irrelevant random.
**언제 X**: cryptographic context 에 `Math.random` — 매 절대 X. Token, password, nonce 매 `crypto.getRandomValues` 만.
## ❌ 안티패턴
- **Math.random for security**: 매 PRNG 의 predictability — token 에 절대 X.
- **Naive shuffle (`sort(() => Math.random() - 0.5)`)**: 매 non-uniform distribution.
- **Modulo bias**: `Math.floor(Math.random() * n)` 까지는 OK, 매 `crypto` byte % n 매 bias 발생 가능.
- **Repeated bloom filter without size planning**: 매 false positive rate 폭증.
## 🧪 검증 / 중복
- Verified (CLRS Ch.5, Mitzenmacher & Upfal "Probability and Computing", MDN Web Crypto).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Las Vegas/Monte Carlo 분류, Fisher-Yates/Reservoir/Quickselect/Bloom/AB-bucket 패턴 |