diff --git a/README.md b/README.md index 1979684..c339ec1 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,51 @@ console.log(result.normalized); // [0.1, 0.2, 0.3, 0.4] See [YOUNG_FIELD.md](YOUNG_FIELD.md) for complete documentation and examples. +### Young Discrete Mathematics Usage + +```javascript +const { + YoungDiagram, + YoungTableau, + YoungLattice, + YoungsRule, + createStandardTableauFromPermutation +} = require('reality-simulation-code'); + +// Create a Young Diagram (partition) +const diagram = new YoungDiagram([4, 3, 1]); +console.log(diagram.size()); // 8 +console.log(diagram.toString()); // ASCII representation + +// Get conjugate partition +const conjugate = diagram.conjugate(); +console.log(conjugate.toArray()); // [3, 2, 2, 1] + +// Create a Young Tableau +const tableau = new YoungTableau([ + [1, 2, 5], + [3, 4], + [6] +], true); +console.log(tableau.isValid()); // true + +// Work with Young Lattice (all partitions) +const lattice = new YoungLattice(); +const partitions = lattice.getLevel(4); +console.log(partitions.length); // 5 partitions of 4 + +// Calculate representation dimension using hook length formula +const dimension = YoungsRule.hookLengthFormula([3, 2, 1]); +console.log(dimension); // 16 + +// Robinson-Schensted correspondence +const permutation = [3, 1, 4, 2]; +const rsTableau = createStandardTableauFromPermutation(permutation); +console.log(rsTableau.toString()); +``` + +See [YOUNG_DISCRETE_MATH.md](YOUNG_DISCRETE_MATH.md) for complete documentation and examples. + linktr.ee/xaoex linktr.ee/oktays @@ -126,6 +171,7 @@ Release Notes * Introducing "young ring" an abstract mathematical ring that is defined for the first time by me (Oktay) for the purpose of creating a dynamic enterprise: entities/organizations/projects. young rings are defined by formation: combining relational algebra with the foundational definitions from group + ring theory. * **NEW: Young Situation White Paper** - See [WHITEPAPER_YOUNG_SITUATION.md](WHITEPAPER_YOUNG_SITUATION.md) for formal mathematical definitions of Young Situation, Family, Bound, Movement with sound mathematics, proofs, and induction in CS/Polytechnic style. * **NEW: Young Field Implementation** - Extension of Young Ring with multiplicative inverses and division operations. See [YOUNG_FIELD.md](YOUNG_FIELD.md) for complete usage guide and examples. Enables normalized situation valuations, probability distributions, and rate of change calculations. +* **NEW: Young Discrete Mathematics** - Comprehensive implementation of Young-related concepts in discrete mathematics: Young Diagrams (partition representations), Young Tableaux (standard and semi-standard), Young Lattice (poset of partitions), and Young's Rule (hook length formula and representation theory). See [YOUNG_DISCRETE_MATH.md](YOUNG_DISCRETE_MATH.md) for complete documentation. These classical structures from combinatorics and representation theory complement the Young Ring/Field algebraic framework. * General AI updates for psychs etc. * Make everything 100% Maxed out again. * P =! or == NP things from before + new finds. diff --git a/YOUNG_CONCEPTS_REFERENCE.md b/YOUNG_CONCEPTS_REFERENCE.md new file mode 100644 index 0000000..fe43923 --- /dev/null +++ b/YOUNG_CONCEPTS_REFERENCE.md @@ -0,0 +1,446 @@ +# Young Concepts: Complete Reference + +This document provides a comprehensive overview of all "Young" concepts implemented in this repository, showing how they relate to each other and their applications in discrete mathematics, algebra, and representation theory. + +## Overview + +The term "Young" in mathematics refers to work by **Alfred Young** (1873–1940), a British mathematician who made fundamental contributions to representation theory, group theory, and combinatorics. This repository implements both: + +1. **Novel Young Concepts** (by Oktay/xaoex): + - Young Ring + - Young Field + - Young Situation framework + +2. **Classical Young Concepts** (from discrete mathematics): + - Young Diagram + - Young Tableau + - Young Lattice + - Young's Rule + +## Complete Feature Matrix + +| Concept | Type | Domain | Purpose | Documentation | +|---------|------|--------|---------|---------------| +| **Young Ring** | Algebraic | Algebra | Dynamic enterprise modeling with relational algebra | [WHITEPAPER_YOUNG_SITUATION.md](WHITEPAPER_YOUNG_SITUATION.md) §10 | +| **Young Field** | Algebraic | Algebra | Extension of Ring with division, normalization | [YOUNG_FIELD.md](YOUNG_FIELD.md) | +| **Young Diagram** | Combinatorial | Discrete Math | Partition visualization, order theory | [YOUNG_DISCRETE_MATH.md](YOUNG_DISCRETE_MATH.md) | +| **Young Tableau** | Combinatorial | Discrete Math | Representation theory, permutation algorithms | [YOUNG_DISCRETE_MATH.md](YOUNG_DISCRETE_MATH.md) | +| **Young Lattice** | Order-theoretic | Discrete Math | Partition enumeration, poset structure | [YOUNG_DISCRETE_MATH.md](YOUNG_DISCRETE_MATH.md) | +| **Young's Rule** | Representation Theory | Algebra | Hook length formula, tensor products | [YOUNG_DISCRETE_MATH.md](YOUNG_DISCRETE_MATH.md) | + +## Architecture Diagram + +``` +Young Concepts Framework +│ +├─ Algebraic Structures (Novel - by xaoex) +│ │ +│ ├─ Young Ring (R, +, ×, 0, 1) +│ │ ├─ Abelian group (additive) +│ │ ├─ Monoid (multiplicative) +│ │ └─ Relational algebra (σ, π, ⋈) +│ │ +│ └─ Young Field (R, +, ×, ÷, 0, 1, ⁻¹) +│ ├─ Extends Young Ring +│ ├─ Multiplicative inverses +│ ├─ Division operations +│ └─ Normalization & probability +│ +└─ Discrete Math Structures (Classical) + │ + ├─ Young Diagram + │ ├─ Partition representation + │ ├─ Conjugate (transpose) + │ ├─ Containment ordering + │ └─ Successors/predecessors + │ + ├─ Young Tableau + │ ├─ Standard tableaux + │ ├─ Semi-standard tableaux + │ ├─ Robinson-Schensted + │ └─ Reading words + │ + ├─ Young Lattice + │ ├─ Poset of partitions + │ ├─ Covering relations + │ ├─ Hasse diagrams + │ └─ Maximal chains + │ + └─ Young's Rule + ├─ Hook length formula + ├─ Tensor products + ├─ Self-conjugate test + └─ Representation dimensions +``` + +## Integration Examples + +### Example 1: Combining Ring and Diagram Operations + +```javascript +const { YoungRing, YoungDiagram } = require('reality-simulation-code'); + +// Use Young Ring for algebraic operations +const ring = new YoungRing([1, 2, 3, 4, 5]); +const evens = ring.select(x => x % 2 === 0); + +// Use Young Diagram for combinatorial structure +const diagram = new YoungDiagram([...evens]); +console.log('Partition from ring selection:', diagram.toArray()); +console.log('Conjugate:', diagram.conjugate().toArray()); +``` + +### Example 2: Field Operations with Partition Dimensions + +```javascript +const { createRationalField, YoungsRule } = require('reality-simulation-code'); + +const field = createRationalField(); +const partitions = [[3, 2, 1], [4, 2], [2, 2, 2]]; + +// Calculate normalized dimensions +const dimensions = partitions.map(p => YoungsRule.hookLengthFormula(p)); +const normalized = field.normalize(dimensions); + +console.log('Dimensions:', dimensions); +console.log('Normalized:', normalized); +console.log('Sum:', normalized.reduce((a, b) => field.add(a, b), 0)); +``` + +### Example 3: Lattice Structure with Field Probabilities + +```javascript +const { YoungLattice, createSituationValuationField } = require('reality-simulation-code'); + +const lattice = new YoungLattice(); +const field = createSituationValuationField(); + +// Get all partitions of 4 +const partitions = lattice.getLevel(4); + +// Assign valuations based on dimensions +const valuations = partitions.map(p => + YoungsRule.hookLengthFormula(p.toArray()) +); + +// Create probability distribution (Plancherel measure) +const probabilities = field.createProbabilityDistribution(valuations); + +partitions.forEach((p, i) => { + console.log(`P([${p.toArray()}]) = ${probabilities[i].toFixed(4)}`); +}); +``` + +### Example 4: Complete Integration - Tableau to Field + +```javascript +const { + createStandardTableauFromPermutation, + YoungsRule, + createRationalField +} = require('reality-simulation-code'); + +// Start with a permutation +const permutation = [3, 1, 4, 1, 5, 9, 2, 6]; + +// Convert to tableau (Robinson-Schensted) +const tableau = createStandardTableauFromPermutation(permutation); +const shape = tableau.shape(); + +// Calculate dimension of representation +const dimension = YoungsRule.hookLengthFormula(shape.toArray()); + +// Use field for probability calculation +const field = createRationalField(); +const factorial = n => n <= 1 ? 1 : n * factorial(n - 1); +const probability = field.divide( + field.multiply(dimension, dimension), + factorial(tableau.size()) +); + +console.log('Permutation:', permutation); +console.log('Tableau shape:', shape.toArray()); +console.log('Dimension:', dimension); +console.log('Plancherel probability:', probability); +``` + +## Use Cases by Domain + +### 1. Discrete Mathematics & Combinatorics + +**Tools**: YoungDiagram, YoungTableau, YoungLattice + +**Applications**: +- Partition enumeration and generating functions +- Combinatorial identities and bijections +- Order theory and lattice structures +- Permutation algorithms (Robinson-Schensted) + +```javascript +const { YoungLattice, partitionsExample } = require('reality-simulation-code'); + +// Generate all partitions up to n +const allPartitions = partitionsExample(6); + +// Count partitions (partition function p(n)) +const lattice = new YoungLattice(); +for (let n = 0; n <= 10; n++) { + console.log(`p(${n}) = ${lattice.countPartitions(n)}`); +} +``` + +### 2. Representation Theory & Algebra + +**Tools**: YoungTableau, YoungsRule, YoungField + +**Applications**: +- Irreducible representations of symmetric groups +- Character theory and Schur functions +- Tensor product decompositions +- Hook length formula computations + +```javascript +const { YoungsRule, YoungTableau } = require('reality-simulation-code'); + +// Calculate dimensions for S_6 representations +const partitionsOf6 = [ + [6], [5,1], [4,2], [4,1,1], [3,3], [3,2,1], + [3,1,1,1], [2,2,2], [2,2,1,1], [2,1,1,1,1], [1,1,1,1,1,1] +]; + +for (const partition of partitionsOf6) { + const dim = YoungsRule.hookLengthFormula(partition); + console.log(`dim V_[${partition}] = ${dim}`); +} +``` + +### 3. Probability & Random Structures + +**Tools**: YoungField, YoungLattice, YoungsRule + +**Applications**: +- Plancherel measure on partitions +- Random matrix theory +- Card shuffling and riffle shuffles +- Crystal growth models + +```javascript +const { YoungLattice, YoungsRule, createRationalField } = require('reality-simulation-code'); + +const lattice = new YoungLattice(); +const field = createRationalField(); + +// Plancherel measure: probability proportional to (dim)² +function plancherelMeasure(n) { + const partitions = lattice.getLevel(n); + const dims = partitions.map(p => YoungsRule.hookLengthFormula(p.toArray())); + const squares = dims.map(d => d * d); + + // Normalize + return field.normalize(squares); +} + +const probs = plancherelMeasure(5); +console.log('Plancherel measure for n=5:', probs); +``` + +### 4. Enterprise Optimization & Situation Management + +**Tools**: YoungRing, YoungField, Young Situation framework + +**Applications**: +- Dynamic enterprise modeling +- Situation valuation and normalization +- Movement transforms (ZMT, DMT) +- Bounded optimization + +```javascript +const { + createSituationValuationField, + YoungRing +} = require('reality-simulation-code'); + +// Model enterprise situations +const field = createSituationValuationField(); + +const situations = [ + { id: 's1', name: 'Optimize', value: 100 }, + { id: 's2', name: 'Expand', value: 200 }, + { id: 's3', name: 'Maintain', value: 150 } +]; + +// Normalize to get priority distribution +const values = situations.map(s => s.value); +const priorities = field.normalize(values); + +situations.forEach((s, i) => { + s.priority = priorities[i]; +}); + +console.log('Situation priorities:', situations); +``` + +## Mathematical Connections + +### Connection 1: Partitions and Representations + +``` +Integer Partition λ + ↓ +Young Diagram + ↓ +Standard Young Tableaux + ↓ +Irreducible Representation V_λ of S_n + ↓ +Hook Length Formula → dim(V_λ) +``` + +### Connection 2: Algebraic to Combinatorial + +``` +Young Ring (algebraic) + ↓ selection σ +Filtered elements + ↓ interpret as partition +Young Diagram (combinatorial) + ↓ operations +Young Lattice (order theory) +``` + +### Connection 3: Field Operations on Partitions + +``` +Young Field (division, normalization) + ↓ normalize dimensions +Probability Distribution + ↓ apply to partitions +Plancherel Measure + ↓ random partition +Young Diagram with probability +``` + +## Complete API Quick Reference + +### Algebraic Structures + +```javascript +// Young Ring +const ring = new YoungRing(elements, addOp, mulOp, zero, one); +ring.add(a, b); +ring.multiply(a, b); +ring.select(predicate); +ring.project(mapper); +ring.join(otherRing); + +// Young Field +const field = createRationalField(); +field.divide(a, b); +field.inverse(a); +field.normalize(values); +field.rateOfChange(f, x, h); +field.createProbabilityDistribution(values); +``` + +### Discrete Math Structures + +```javascript +// Young Diagram +const diagram = new YoungDiagram([4, 3, 1]); +diagram.size(); +diagram.conjugate(); +diagram.contains(other); +diagram.successors(); +diagram.predecessors(); + +// Young Tableau +const tableau = new YoungTableau(filling, standard); +tableau.isValid(); +tableau.shape(); +tableau.insertValue(value); +tableau.readingWord(); + +// Young Lattice +const lattice = new YoungLattice(); +lattice.getLevel(n); +lattice.countPartitions(n); +lattice.getCoveringRelations(n); +lattice.getHasseDiagram(n); + +// Young's Rule +YoungsRule.hookLengthFormula(partition); +YoungsRule.tensorProduct(lambda, mu); +YoungsRule.isSelfConjugate(partition); +``` + +## Testing + +Run comprehensive tests for all components: + +```bash +# Run all tests +npm test + +# Run specific test suites +npm run test:field # Young Ring and Field tests +npm run test:discrete # Young Discrete Math tests +``` + +Test coverage: +- ✓ Young Ring: Construction, operations, relational algebra +- ✓ Young Field: Axioms F1-F5, division, normalization +- ✓ Young Diagram: Conjugate, containment, successors/predecessors +- ✓ Young Tableau: Validation, insertion, Robinson-Schensted +- ✓ Young Lattice: Partition generation, covering relations +- ✓ Young's Rule: Hook length, self-conjugate, tensor products +- ✓ Integration: Cross-component compatibility + +## Performance Characteristics + +| Operation | Complexity | Notes | +|-----------|-----------|-------| +| Young Ring operations | O(1) | Basic arithmetic | +| Young Field division | O(1) | Using inverse | +| Diagram conjugate | O(n) | n = size of partition | +| Tableau validation | O(n²) | Check all pairs | +| Robinson-Schensted | O(n²) | n = permutation length | +| Partition generation | O(p(n)) | p(n) = partition function | +| Hook length formula | O(n) | n = partition size | + +## Bibliography & References + +### Classical Mathematics +1. **Fulton, William** - *Young Tableaux* (Cambridge, 1997) +2. **Sagan, Bruce** - *The Symmetric Group* (Springer, 2001) +3. **Stanley, Richard** - *Enumerative Combinatorics Vol. 2* (Cambridge, 1999) +4. **Knuth, Donald** - *The Art of Computer Programming Vol. 3* + +### Repository Documentation +5. **xaoex** - [WHITEPAPER_YOUNG_SITUATION.md](WHITEPAPER_YOUNG_SITUATION.md) - Young Ring/Field foundations +6. **xaoex** - [YOUNG_FIELD.md](YOUNG_FIELD.md) - Young Field implementation guide +7. **xaoex** - [YOUNG_DISCRETE_MATH.md](YOUNG_DISCRETE_MATH.md) - Discrete math structures + +## Contributing + +When adding new Young-related concepts: +1. Maintain consistency with existing mathematical definitions +2. Add comprehensive tests (aim for 100% coverage) +3. Document with examples and use cases +4. Explain connections to existing components +5. Update this reference guide + +## License + +MIT License - See LICENSE file for details + +## Author + +xaoex +- https://linktr.ee/xaoex +- https://linktr.ee/oktays + +--- + +**Version**: 1.0 +**Last Updated**: December 2025 +**Repository**: https://github.com/xaoex/reality-simulation-code diff --git a/YOUNG_DISCRETE_MATH.md b/YOUNG_DISCRETE_MATH.md new file mode 100644 index 0000000..0ae5688 --- /dev/null +++ b/YOUNG_DISCRETE_MATH.md @@ -0,0 +1,583 @@ +# Young Concepts in Discrete Mathematics + +This document provides comprehensive documentation for Young-related concepts in Discrete Mathematics, including **Young Diagrams**, **Young Tableaux**, **Young Lattice**, and **Young's Rule**. + +## Overview + +The "Young" concepts in discrete mathematics are named after Alfred Young (1873–1940), a British mathematician who made fundamental contributions to representation theory and combinatorics. These structures are central to: + +- **Combinatorics**: Counting and enumerating structures +- **Representation Theory**: Studying symmetry groups and their representations +- **Algebraic Geometry**: Schubert calculus and intersection theory +- **Probability Theory**: Random partitions and card shuffling +- **Computer Science**: Algorithm design and data structures + +## Table of Contents + +1. [Young Diagram](#young-diagram) +2. [Young Tableau](#young-tableau) +3. [Young Lattice](#young-lattice) +4. [Young's Rule](#youngs-rule) +5. [Applications](#applications) +6. [Examples](#examples) +7. [API Reference](#api-reference) + +--- + +## Young Diagram + +### Definition + +A **Young Diagram** is a graphical representation of an integer partition. It consists of left-justified rows of boxes, where row lengths form a non-increasing sequence. + +### Mathematical Definition + +Given a partition λ = (λ₁, λ₂, ..., λₖ) where λ₁ ≥ λ₂ ≥ ... ≥ λₖ > 0, the Young Diagram is: + +``` +□□...□ (λ₁ boxes) +□□...□ (λ₂ boxes) +... +□□...□ (λₖ boxes) +``` + +### Example + +The partition [4, 3, 1] gives the diagram: +``` +**** +*** +* +``` + +### Key Operations + +1. **Size**: Sum of all parts: |λ| = λ₁ + λ₂ + ... + λₖ + +2. **Conjugate (Transpose)**: Flip the diagram along the main diagonal + - Example: [4, 3, 1] → [3, 2, 2, 1] + +3. **Containment**: λ ⊆ μ if λᵢ ≤ μᵢ for all i + - Used for partial ordering in Young Lattice + +4. **Successors/Predecessors**: Add/remove one box while maintaining the partition property + +### Usage + +```javascript +const { YoungDiagram } = require('reality-simulation-code'); + +// Create a diagram +const diagram = new YoungDiagram([4, 3, 1]); + +console.log(diagram.size()); // 8 +console.log(diagram.numRows()); // 3 +console.log(diagram.numColumns()); // 4 + +// Get conjugate (transpose) +const conjugate = diagram.conjugate(); +console.log(conjugate.toArray()); // [3, 2, 2, 1] + +// Check containment +const smaller = new YoungDiagram([3, 2, 1]); +console.log(diagram.contains(smaller)); // true + +// Get all ways to add one box +const successors = diagram.successors(); +console.log(successors.length); // Number of valid ways to add a box +``` + +--- + +## Young Tableau + +### Definition + +A **Young Tableau** is a Young Diagram where each box contains a number, satisfying: + +- **Standard Young Tableau**: + - Numbers 1, 2, ..., n appear exactly once + - Rows are strictly increasing (left to right) + - Columns are strictly increasing (top to bottom) + +- **Semi-Standard Young Tableau**: + - Numbers can repeat + - Rows are weakly increasing + - Columns are strictly increasing + +### Mathematical Significance + +Young Tableaux correspond to: +- Irreducible representations of symmetric groups Sₙ +- Basis vectors in representation spaces +- Standard tableaux count: given by the **hook length formula** + +### Example + +Standard Young Tableau of shape [3, 2, 1]: +``` +1 2 5 +3 4 +6 +``` + +### Robinson-Schensted Correspondence + +The Robinson-Schensted algorithm establishes a bijection between: +- Permutations of {1, 2, ..., n} +- Pairs of standard Young Tableaux of the same shape + +This is fundamental in representation theory and has applications in longest increasing subsequence problems. + +### Usage + +```javascript +const { YoungTableau, createStandardTableauFromPermutation } = require('reality-simulation-code'); + +// Create a standard tableau +const tableau = new YoungTableau([ + [1, 2, 5], + [3, 4], + [6] +], true); + +console.log(tableau.isValid()); // true +console.log(tableau.size()); // 6 +console.log(tableau.shape().toArray()); // [3, 2, 1] + +// Get reading word (bottom-to-top, right-to-left) +console.log(tableau.readingWord()); // [6, 5, 4, 3, 2, 1] + +// Robinson-Schensted insertion +const permutation = [3, 1, 4, 2]; +const rsTableau = createStandardTableauFromPermutation(permutation); +console.log(rsTableau.toString()); +``` + +--- + +## Young Lattice + +### Definition + +The **Young Lattice** is the partially ordered set (poset) of all integer partitions, ordered by inclusion of their Young Diagrams. + +### Structure + +- **Levels**: Level n contains all partitions of n +- **Covering Relations**: λ covers μ if λ is obtained from μ by adding exactly one box +- **Maximal Chains**: Correspond to standard Young Tableaux + +### Partition Function + +The number of partitions of n, denoted p(n), grows rapidly: + +| n | p(n) | Example Partitions | +|---|------|-------------------| +| 0 | 1 | [] | +| 1 | 1 | [1] | +| 2 | 2 | [2], [1,1] | +| 3 | 3 | [3], [2,1], [1,1,1] | +| 4 | 5 | [4], [3,1], [2,2], [2,1,1], [1,1,1,1] | +| 5 | 7 | ... | + +### Applications + +- **Representation Theory**: Characters of symmetric groups +- **Combinatorics**: Counting problems and generating functions +- **Statistical Mechanics**: Crystal bases and quantum groups + +### Usage + +```javascript +const { YoungLattice } = require('reality-simulation-code'); + +const lattice = new YoungLattice(); + +// Get all partitions of n +const partitions4 = lattice.getLevel(4); +console.log(partitions4.length); // 5 + +// Count partitions (partition function) +console.log(lattice.countPartitions(5)); // 7 + +// Get covering relations at level n +const relations = lattice.getCoveringRelations(3); +for (const [lower, upper] of relations) { + console.log(`${lower.toArray()} → ${upper.toArray()}`); +} + +// Get Hasse diagram structure +const hasse = lattice.getHasseDiagram(4); +console.log(`Nodes: ${hasse.nodes.length}`); +console.log(`Edges: ${hasse.edges.length}`); +``` + +--- + +## Young's Rule + +### Definition + +**Young's Rule** (also known as the Littlewood-Richardson rule) describes how to decompose tensor products of irreducible representations of symmetric groups. + +### Hook Length Formula + +The dimension of the irreducible representation corresponding to partition λ is: + +``` +dim(V_λ) = n! / ∏(i,j) h(i,j) +``` + +where h(i,j) is the **hook length** at position (i,j): +- Hook length = arm length + leg length + 1 +- Arm: boxes to the right in the same row +- Leg: boxes below in the same column + +### Example + +For partition [3, 2, 1]: +``` +Diagram: Hook lengths: +□□□ 5 4 2 +□□ 3 2 +□ 1 +``` + +Dimension = 6! / (5×4×2×3×2×1) = 720 / 240 = 16 + +### Self-Conjugate Partitions + +A partition is **self-conjugate** if it equals its own conjugate. These correspond to: +- Orthogonal representations +- Spin representations in physics +- Special combinatorial structures + +### Usage + +```javascript +const { YoungsRule } = require('reality-simulation-code'); + +// Calculate dimension using hook length formula +const dimension = YoungsRule.hookLengthFormula([3, 2, 1]); +console.log(dimension); // 16 + +// Check if partition is self-conjugate +console.log(YoungsRule.isSelfConjugate([2, 2])); // true +console.log(YoungsRule.isSelfConjugate([3, 1])); // false + +// Compute tensor product (simplified version) +const result = YoungsRule.tensorProduct([2], [2]); +console.log([...result.entries()]); // Partitions of 4 with multiplicities +``` + +--- + +## Applications + +### 1. Representation Theory + +Young concepts provide a concrete realization of abstract representation theory: + +```javascript +const { YoungTableau, YoungsRule } = require('reality-simulation-code'); + +// Standard Young Tableaux of shape λ form a basis for V_λ +const partition = [3, 2, 1]; +const dimension = YoungsRule.hookLengthFormula(partition); +console.log(`Irrep of S_6 labeled by [3,2,1] has dimension ${dimension}`); +``` + +### 2. Symmetric Function Theory + +Schur functions are indexed by partitions and form a basis for symmetric functions: + +```javascript +const { YoungDiagram } = require('reality-simulation-code'); + +// Partitions parametrize Schur functions +const lambda = new YoungDiagram([3, 2]); +console.log(`Schur function s_{${lambda.toArray()}} corresponds to this shape`); +``` + +### 3. Combinatorial Algorithms + +Robinson-Schensted correspondence and tableau algorithms: + +```javascript +const { createStandardTableauFromPermutation } = require('reality-simulation-code'); + +// Find longest increasing subsequence via Robinson-Schensted +const permutation = [3, 1, 4, 1, 5, 9, 2, 6]; +const tableau = createStandardTableauFromPermutation(permutation); +const shape = tableau.shape(); + +// Length of longest increasing subsequence = first row length +console.log(`LIS length: ${shape.toArray()[0]}`); +``` + +### 4. Probability and Random Matrices + +Random partitions arise in: +- Random matrix theory +- Card shuffling (riffle shuffles) +- Crystal growth models + +```javascript +const { YoungLattice } = require('reality-simulation-code'); + +const lattice = new YoungLattice(); +const partitions = lattice.getLevel(10); + +// Plancherel measure: probability of each partition +for (const partition of partitions) { + const dim = YoungsRule.hookLengthFormula(partition.toArray()); + const prob = (dim * dim) / factorial(10); + console.log(`P(${partition.toArray()}) = ${prob}`); +} +``` + +--- + +## Examples + +### Example 1: Enumerate All Partitions + +```javascript +const { partitionsExample } = require('reality-simulation-code'); + +const result = partitionsExample(5); +for (const [n, partitions] of Object.entries(result)) { + console.log(`n=${n}: ${partitions.map(p => `[${p}]`).join(', ')}`); +} +``` + +Output: +``` +n=0: [[]] +n=1: [[1]] +n=2: [[2], [1,1]] +n=3: [[3], [2,1], [1,1,1]] +n=4: [[4], [3,1], [2,2], [2,1,1], [1,1,1,1]] +n=5: [[5], [4,1], [3,2], [3,1,1], [2,2,1], [2,1,1,1], [1,1,1,1,1]] +``` + +### Example 2: Young Diagram Operations + +```javascript +const { youngDiagramExample } = require('reality-simulation-code'); + +const result = youngDiagramExample(); +console.log('Partition:', result.partition); +console.log('Size:', result.size); +console.log('Dimensions:', result.rows, 'x', result.cols); +console.log('\nDiagram:'); +console.log(result.ascii); +console.log('\nConjugate:', result.conjugate); +console.log('Successors:', result.successors); +console.log('Predecessors:', result.predecessors); +``` + +### Example 3: Standard Young Tableau + +```javascript +const { youngTableauExample } = require('reality-simulation-code'); + +const result = youngTableauExample(); +console.log('Shape:', result.shape); +console.log('Size:', result.size); +console.log('Valid?', result.valid); +console.log('\nTableau:'); +console.log(result.ascii); +console.log('\nReading word:', result.readingWord); +``` + +### Example 4: Hook Length Formula + +```javascript +const { hookLengthExample } = require('reality-simulation-code'); + +const result = hookLengthExample(); +console.log('Hook Length Formula Results:'); +for (const [partition, data] of Object.entries(result)) { + console.log(`[${partition}]: dimension = ${data.dimension}`); +} +``` + +### Example 5: Young Lattice Structure + +```javascript +const { youngLatticeExample } = require('reality-simulation-code'); + +const result = youngLatticeExample(4); +console.log('Partition Function p(n):'); +for (const {n, count, partitions} of result.partitionCounts) { + console.log(`p(${n}) = ${count}: ${partitions.map(p => `[${p}]`).join(', ')}`); +} +``` + +--- + +## API Reference + +### YoungDiagram + +#### Constructor +```javascript +new YoungDiagram(partition: Array) +``` + +#### Methods +- `size()`: Returns the sum of the partition +- `numRows()`: Returns the number of rows +- `numColumns()`: Returns the number of columns (length of first row) +- `conjugate()`: Returns the conjugate (transpose) diagram +- `contains(other: YoungDiagram)`: Checks if this diagram contains another +- `successors()`: Returns array of diagrams obtained by adding one box +- `predecessors()`: Returns array of diagrams obtained by removing one box +- `toString()`: Returns ASCII representation +- `toArray()`: Returns the partition as an array +- `equals(other: YoungDiagram)`: Checks equality + +### YoungTableau + +#### Constructor +```javascript +new YoungTableau(filling: Array>, standard: boolean = false) +``` + +#### Methods +- `shape()`: Returns the underlying YoungDiagram +- `size()`: Returns the number of boxes +- `isValid()`: Validates the tableau (checks row/column increasing properties) +- `get(row, col)`: Gets value at position +- `set(row, col, value)`: Sets value at position +- `toString()`: Returns ASCII representation with numbers +- `readingWord()`: Returns the reading word (bottom-to-top, right-to-left) +- `insertValue(value)`: Performs Robinson-Schensted insertion + +### YoungLattice + +#### Constructor +```javascript +new YoungLattice() +``` + +#### Methods +- `getLevel(n)`: Returns all YoungDiagrams at level n (partitions of n) +- `countPartitions(n)`: Returns p(n), the number of partitions of n +- `getCoveringRelations(n)`: Returns covering relations between levels n-1 and n +- `getHasseDiagram(n)`: Returns Hasse diagram structure up to level n +- `generatePartitions(n, max)`: Generates all partitions of n with parts ≤ max + +### YoungsRule + +#### Static Methods +- `hookLengthFormula(partition)`: Computes dimension using hook length formula +- `tensorProduct(lambda, mu)`: Computes tensor product decomposition (simplified) +- `isSelfConjugate(partition)`: Checks if partition equals its conjugate + +### Factory Functions + +- `createStandardTableauFromPermutation(permutation)`: Robinson-Schensted correspondence + +### Example Functions + +- `partitionsExample(n)`: Generates all partitions up to n +- `youngDiagramExample()`: Demonstrates YoungDiagram operations +- `youngTableauExample()`: Creates and validates a sample tableau +- `hookLengthExample()`: Computes dimensions for sample partitions +- `youngLatticeExample(n)`: Demonstrates lattice structure + +--- + +## Mathematical Background + +### Partition Theory + +An **integer partition** of n is a way of writing n as a sum of positive integers, where order doesn't matter: + +``` +5 = 5 = 4+1 = 3+2 = 3+1+1 = 2+2+1 = 2+1+1+1 = 1+1+1+1+1 +``` + +The 7 partitions of 5 correspond to 7 ways to arrange 5 identical objects. + +### Representation Theory Connection + +For the symmetric group Sₙ: +- Irreducible representations ↔ Partitions of n +- Dimension of representation ↔ Hook length formula +- Character values ↔ Symmetric functions + +This deep connection is why Young concepts are so important in algebra and combinatorics. + +### Generating Functions + +The generating function for partitions is: + +``` +∏(k≥1) 1/(1-xᵏ) = Σ p(n)xⁿ +``` + +This leads to asymptotics: p(n) ~ exp(π√(2n/3)) / (4n√3) as n → ∞ + +--- + +## References + +1. **William Fulton** - *Young Tableaux* (Cambridge University Press, 1997) +2. **Bruce Sagan** - *The Symmetric Group* (Springer, 2001) +3. **Stanley, Richard P.** - *Enumerative Combinatorics, Volume 2* (Cambridge, 1999) +4. **Knuth, Donald E.** - *The Art of Computer Programming, Vol. 3: Sorting and Searching* +5. **xaoex** - *WHITEPAPER_YOUNG_SITUATION.md* (Young Ring and Young Field foundations) + +--- + +## Integration with Young Ring and Young Field + +The Young discrete math concepts complement the existing **Young Ring** and **Young Field** implementations: + +- **Young Ring**: Algebraic structure for situation optimization +- **Young Field**: Extension with division and normalized valuations +- **Young Diagrams/Tableaux**: Combinatorial structures for discrete mathematics +- **Young Lattice**: Ordered structure for partition enumeration + +Together, these form a comprehensive framework for both algebraic and combinatorial approaches to optimization, representation theory, and discrete mathematics. + +See also: +- [YOUNG_FIELD.md](YOUNG_FIELD.md) - Young Field implementation and usage +- [WHITEPAPER_YOUNG_SITUATION.md](WHITEPAPER_YOUNG_SITUATION.md) - Mathematical foundations + +--- + +## Testing + +Run the comprehensive test suite: + +```bash +npm test # Run Young Field tests +node test-young-discrete-math.js # Run Young Discrete Math tests +``` + +Both test suites verify: +- Correctness of all operations +- Mathematical properties and axioms +- Edge cases and boundary conditions +- Integration between components + +--- + +## License + +MIT License - See LICENSE file for details + +## Author + +xaoex +- https://linktr.ee/xaoex +- https://linktr.ee/oktays + +--- + +*For the complete framework including algebraic structures (Young Ring and Young Field), see [YOUNG_FIELD.md](YOUNG_FIELD.md) and [WHITEPAPER_YOUNG_SITUATION.md](WHITEPAPER_YOUNG_SITUATION.md).* diff --git a/index.js b/index.js index 8d4c9f5..1c1625a 100644 --- a/index.js +++ b/index.js @@ -356,13 +356,25 @@ module.exports = { YoungRing, YoungField, + // Young Discrete Math classes + YoungDiagram: require('./young-discrete-math.js').YoungDiagram, + YoungTableau: require('./young-discrete-math.js').YoungTableau, + YoungLattice: require('./young-discrete-math.js').YoungLattice, + YoungsRule: require('./young-discrete-math.js').YoungsRule, + // Factory functions createRationalField, createFiniteField, createSituationValuationField, + createStandardTableauFromPermutation: require('./young-discrete-math.js').createStandardTableauFromPermutation, // Example functions normalizedSituationExample, youngFieldOperationsExample, - finiteFieldExample + finiteFieldExample, + partitionsExample: require('./young-discrete-math.js').partitionsExample, + youngDiagramExample: require('./young-discrete-math.js').youngDiagramExample, + youngTableauExample: require('./young-discrete-math.js').youngTableauExample, + hookLengthExample: require('./young-discrete-math.js').hookLengthExample, + youngLatticeExample: require('./young-discrete-math.js').youngLatticeExample }; diff --git a/package.json b/package.json index 8709ff6..d009e19 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,9 @@ "description": "Reality Simulation Codebase - SimSim Code & Contributions by xaoex", "main": "index.js", "scripts": { - "test": "node test-young-field.js", + "test": "node test-young-field.js && node test-young-discrete-math.js", + "test:field": "node test-young-field.js", + "test:discrete": "node test-young-discrete-math.js", "build": "echo \"Build complete\" && exit 0" }, "repository": { diff --git a/test-young-discrete-math.js b/test-young-discrete-math.js new file mode 100644 index 0000000..510e717 --- /dev/null +++ b/test-young-discrete-math.js @@ -0,0 +1,542 @@ +/** + * Test Suite for Young Discrete Mathematics + * Tests for Young Diagram, Young Tableau, Young Lattice, and Young's Rule + */ + +const { + YoungDiagram, + YoungTableau, + YoungLattice, + YoungsRule, + createStandardTableauFromPermutation, + partitionsExample, + youngDiagramExample, + youngTableauExample, + hookLengthExample, + youngLatticeExample +} = require('./young-discrete-math.js'); + +// ============================================================================ +// Test Utilities +// ============================================================================ + +function assert(condition, message) { + if (!condition) { + throw new Error(`Assertion failed: ${message}`); + } +} + +function testSection(name, testFn) { + console.log(`\n${'='.repeat(70)}`); + console.log(`Testing: ${name}`); + console.log('='.repeat(70)); + try { + testFn(); + console.log(`✓ ${name} - PASSED`); + } catch (error) { + console.error(`✗ ${name} - FAILED`); + console.error(error.message); + console.error(error.stack); + process.exit(1); + } +} + +// ============================================================================ +// Young Diagram Tests +// ============================================================================ + +function testYoungDiagramConstruction() { + // Test empty diagram + const empty = new YoungDiagram([]); + assert(empty.size() === 0, 'Empty diagram has size 0'); + assert(empty.numRows() === 0, 'Empty diagram has 0 rows'); + + // Test valid partition + const diagram = new YoungDiagram([4, 3, 1]); + assert(diagram.size() === 8, 'Diagram [4,3,1] has size 8'); + assert(diagram.numRows() === 3, 'Diagram has 3 rows'); + assert(diagram.numColumns() === 4, 'Diagram has 4 columns'); + + // Test that partition is normalized (sorted decreasing) + const unsorted = new YoungDiagram([2, 4, 1, 3]); + assert(unsorted.toArray().join(',') === '4,3,2,1', 'Partition is sorted'); + + console.log(' ✓ Young Diagram construction'); +} + +function testYoungDiagramConjugate() { + // Test conjugate (transpose) + const diagram = new YoungDiagram([4, 3, 1]); + const conjugate = diagram.conjugate(); + + // [4,3,1] conjugate is [3,2,2,1] + // Col 0: 3 boxes (rows 0,1,2), Col 1: 2 boxes (rows 0,1) + // Col 2: 2 boxes (rows 0,1), Col 3: 1 box (row 0) + assert(conjugate.toArray().join(',') === '3,2,2,1', 'Conjugate correct'); + + // Double conjugate should give original + const doubleConj = conjugate.conjugate(); + assert(diagram.equals(doubleConj), 'Double conjugate equals original'); + + console.log(' ✓ Young Diagram conjugate'); +} + +function testYoungDiagramContainment() { + const larger = new YoungDiagram([4, 3, 1]); + const smaller = new YoungDiagram([3, 2, 1]); + const unrelated = new YoungDiagram([2, 2, 2]); + + assert(larger.contains(smaller), 'Larger contains smaller'); + assert(larger.contains(larger), 'Diagram contains itself'); + assert(!smaller.contains(larger), 'Smaller does not contain larger'); + assert(!larger.contains(unrelated), 'Check unrelated containment'); + + console.log(' ✓ Young Diagram containment'); +} + +function testYoungDiagramSuccessors() { + const diagram = new YoungDiagram([2, 1]); + const successors = diagram.successors(); + + // From [2,1] we can get [3,1], [2,2], [2,1,1] + assert(successors.length === 3, 'Should have 3 successors'); + + // All successors should have size n+1 + for (const succ of successors) { + assert(succ.size() === diagram.size() + 1, 'Successor size is n+1'); + } + + console.log(' ✓ Young Diagram successors'); +} + +function testYoungDiagramPredecessors() { + const diagram = new YoungDiagram([3, 2, 1]); + const predecessors = diagram.predecessors(); + + // All predecessors should have size n-1 + for (const pred of predecessors) { + assert(pred.size() === diagram.size() - 1, 'Predecessor size is n-1'); + assert(diagram.contains(pred), 'Diagram contains its predecessor'); + } + + console.log(' ✓ Young Diagram predecessors'); +} + +// ============================================================================ +// Young Tableau Tests +// ============================================================================ + +function testYoungTableauConstruction() { + // Create a standard Young Tableau + const tableau = new YoungTableau([ + [1, 2, 3], + [4, 5], + [6] + ], true); + + assert(tableau.size() === 6, 'Tableau has size 6'); + assert(tableau.shape().toArray().join(',') === '3,2,1', 'Shape is [3,2,1]'); + + console.log(' ✓ Young Tableau construction'); +} + +function testYoungTableauValidation() { + // Valid standard tableau + const valid = new YoungTableau([ + [1, 2, 5], + [3, 4], + [6] + ], true); + assert(valid.isValid(), 'Valid tableau recognized'); + + // Invalid: row not increasing + const invalidRow = new YoungTableau([ + [1, 3, 2], + [4, 5] + ], true); + assert(!invalidRow.isValid(), 'Invalid row detected'); + + // Invalid: column not increasing + const invalidCol = new YoungTableau([ + [1, 2], + [3, 2] + ], true); + assert(!invalidCol.isValid(), 'Invalid column detected'); + + // Invalid standard: missing numbers + const invalidStandard = new YoungTableau([ + [1, 2, 4], + [5, 6] + ], true); + assert(!invalidStandard.isValid(), 'Missing number detected'); + + console.log(' ✓ Young Tableau validation'); +} + +function testYoungTableauGetSet() { + const tableau = new YoungTableau([ + [1, 2, 3], + [4, 5] + ], true); + + // Test get + assert(tableau.get(0, 0) === 1, 'Get (0,0) returns 1'); + assert(tableau.get(1, 1) === 5, 'Get (1,1) returns 5'); + assert(tableau.get(2, 0) === null, 'Get out of bounds returns null'); + + // Test set + assert(tableau.set(0, 0, 2), 'Set within bounds succeeds'); + assert(tableau.get(0, 0) === 2, 'Value was set'); + assert(!tableau.set(2, 0, 1), 'Set out of bounds fails'); + + console.log(' ✓ Young Tableau get/set'); +} + +function testYoungTableauReadingWord() { + const tableau = new YoungTableau([ + [1, 2, 3], + [4, 5], + [6] + ], true); + + const word = tableau.readingWord(); + // Read bottom to top, right to left: 6, 5, 4, 3, 2, 1 + assert(word.join(',') === '6,5,4,3,2,1', 'Reading word correct'); + + console.log(' ✓ Young Tableau reading word'); +} + +function testYoungTableauInsertion() { + // Start with empty tableau + let tableau = new YoungTableau([[]], true); + + // Insert values using Robinson-Schensted + tableau = tableau.insertValue(3); + tableau = tableau.insertValue(1); + tableau = tableau.insertValue(2); + + assert(tableau.size() === 3, 'Inserted 3 values'); + assert(tableau.isValid(), 'Result is valid'); + + console.log(' ✓ Young Tableau insertion'); +} + +// ============================================================================ +// Young Lattice Tests +// ============================================================================ + +function testYoungLatticePartitions() { + const lattice = new YoungLattice(); + + // Level 0: empty partition + const level0 = lattice.getLevel(0); + assert(level0.length === 1, 'Level 0 has 1 partition'); + assert(level0[0].size() === 0, 'Level 0 partition is empty'); + + // Level 1: [1] + const level1 = lattice.getLevel(1); + assert(level1.length === 1, 'Level 1 has 1 partition'); + + // Level 2: [2], [1,1] + const level2 = lattice.getLevel(2); + assert(level2.length === 2, 'Level 2 has 2 partitions'); + + // Level 3: [3], [2,1], [1,1,1] + const level3 = lattice.getLevel(3); + assert(level3.length === 3, 'Level 3 has 3 partitions'); + + // Level 4: [4], [3,1], [2,2], [2,1,1], [1,1,1,1] + const level4 = lattice.getLevel(4); + assert(level4.length === 5, 'Level 4 has 5 partitions'); + + console.log(' ✓ Young Lattice partition generation'); +} + +function testYoungLatticePartitionFunction() { + const lattice = new YoungLattice(); + + // Known values of partition function p(n) + const expected = [1, 1, 2, 3, 5, 7, 11, 15]; + + for (let n = 0; n < expected.length; n++) { + const count = lattice.countPartitions(n); + assert(count === expected[n], `p(${n}) = ${expected[n]}`); + } + + console.log(' ✓ Young Lattice partition function'); +} + +function testYoungLatticeCoveringRelations() { + const lattice = new YoungLattice(); + + // At level 2, we have [2] and [1,1] + // [2] covers [1], [1,1] covers [1] + const relations2 = lattice.getCoveringRelations(2); + assert(relations2.length === 2, 'Level 2 has 2 covering relations'); + + // At level 3, we have more covering relations + const relations3 = lattice.getCoveringRelations(3); + assert(relations3.length > 0, 'Level 3 has covering relations'); + + // Verify each relation differs by exactly one box + for (const [lower, upper] of relations3) { + assert(upper.size() === lower.size() + 1, 'Covering adds one box'); + assert(upper.contains(lower), 'Upper contains lower'); + } + + console.log(' ✓ Young Lattice covering relations'); +} + +function testYoungLatticeHasseDiagram() { + const lattice = new YoungLattice(); + const hasse = lattice.getHasseDiagram(3); + + assert(hasse.nodes.length > 0, 'Hasse diagram has nodes'); + assert(hasse.edges.length > 0, 'Hasse diagram has edges'); + + // Count nodes at each level + const nodeCounts = [0, 0, 0, 0]; + for (const node of hasse.nodes) { + nodeCounts[node.level]++; + } + + assert(nodeCounts[0] === 1, 'Level 0 has 1 node'); + assert(nodeCounts[1] === 1, 'Level 1 has 1 node'); + assert(nodeCounts[2] === 2, 'Level 2 has 2 nodes'); + assert(nodeCounts[3] === 3, 'Level 3 has 3 nodes'); + + console.log(' ✓ Young Lattice Hasse diagram'); +} + +// ============================================================================ +// Young's Rule Tests +// ============================================================================ + +function testHookLengthFormula() { + // Test known dimensions + + // [n] (single row): dimension = 1 + assert(YoungsRule.hookLengthFormula([3]) === 1, 'Single row has dimension 1'); + + // [1,1,1] (single column): dimension = 1 + assert(YoungsRule.hookLengthFormula([1, 1, 1]) === 1, 'Single column has dimension 1'); + + // [2,1]: dimension = 2 + assert(YoungsRule.hookLengthFormula([2, 1]) === 2, '[2,1] has dimension 2'); + + // [2,2]: dimension = 2 + assert(YoungsRule.hookLengthFormula([2, 2]) === 2, '[2,2] has dimension 2'); + + // [3,2,1]: 3! * 2! * 1! / (hook products) = 16 + assert(YoungsRule.hookLengthFormula([3, 2, 1]) === 16, '[3,2,1] has dimension 16'); + + console.log(' ✓ Hook length formula'); +} + +function testSelfConjugatePartitions() { + // [1] is self-conjugate + assert(YoungsRule.isSelfConjugate([1]), '[1] is self-conjugate'); + + // [2,1] is self-conjugate (conjugate is [2,1]) + assert(YoungsRule.isSelfConjugate([2, 1]), '[2,1] is self-conjugate'); + + // [2,2] is self-conjugate + assert(YoungsRule.isSelfConjugate([2, 2]), '[2,2] is self-conjugate'); + + // [3,2,1] is not self-conjugate (conjugate is [3,2,1]) + assert(YoungsRule.isSelfConjugate([3, 2, 1]), '[3,2,1] is self-conjugate'); + + // [3,1] is not self-conjugate (conjugate is [2,1,1]) + assert(!YoungsRule.isSelfConjugate([3, 1]), '[3,1] is not self-conjugate'); + + console.log(' ✓ Self-conjugate partitions'); +} + +function testTensorProduct() { + // Test tensor product computation + const result = YoungsRule.tensorProduct([2], [2]); + + assert(result.size > 0, 'Tensor product returns results'); + + // Result should contain partitions of size 4 + for (const [key, mult] of result.entries()) { + const partition = key.split(',').map(Number); + const size = partition.reduce((a, b) => a + b, 0); + assert(size === 4, 'Result partitions have correct size'); + } + + console.log(' ✓ Tensor product (Young\'s Rule)'); +} + +// ============================================================================ +// Example Function Tests +// ============================================================================ + +function testPartitionsExample() { + const result = partitionsExample(5); + + assert(result[0].length === 1, 'n=0 has 1 partition'); + assert(result[1].length === 1, 'n=1 has 1 partition'); + assert(result[2].length === 2, 'n=2 has 2 partitions'); + assert(result[3].length === 3, 'n=3 has 3 partitions'); + assert(result[4].length === 5, 'n=4 has 5 partitions'); + assert(result[5].length === 7, 'n=5 has 7 partitions'); + + console.log(' ✓ Example: partitionsExample()'); +} + +function testYoungDiagramExampleFunction() { + const result = youngDiagramExample(); + + assert(result.partition.join(',') === '4,3,1', 'Partition is [4,3,1]'); + assert(result.size === 8, 'Size is 8'); + assert(result.rows === 3, 'Has 3 rows'); + assert(result.cols === 4, 'Has 4 columns'); + assert(result.conjugate.join(',') === '3,2,2,1', 'Conjugate is [3,2,2,1]'); + assert(result.successors.length > 0, 'Has successors'); + assert(result.predecessors.length > 0, 'Has predecessors'); + + console.log(' ✓ Example: youngDiagramExample()'); + console.log(' ASCII representation:'); + console.log(result.ascii.split('\n').map(line => ' ' + line).join('\n')); +} + +function testYoungTableauExampleFunction() { + const result = youngTableauExample(); + + assert(result.size === 6, 'Tableau has size 6'); + assert(result.valid === true, 'Tableau is valid'); + assert(result.shape.join(',') === '3,2,1', 'Shape is [3,2,1]'); + assert(result.readingWord.length === 6, 'Reading word has 6 elements'); + + console.log(' ✓ Example: youngTableauExample()'); + console.log(' ASCII representation:'); + console.log(result.ascii.split('\n').map(line => ' ' + line).join('\n')); +} + +function testHookLengthExampleFunction() { + const result = hookLengthExample(); + + assert(Object.keys(result).length === 4, 'Has 4 partitions'); + + for (const [key, data] of Object.entries(result)) { + assert(data.dimension > 0, `${key} has positive dimension`); + assert(data.partition.length > 0, `${key} has partition`); + } + + console.log(' ✓ Example: hookLengthExample()'); + for (const [key, data] of Object.entries(result)) { + console.log(` [${key}]: dimension = ${data.dimension}`); + } +} + +function testYoungLatticeExampleFunction() { + const result = youngLatticeExample(4); + + assert(result.partitionCounts.length === 5, 'Has counts for n=0..4'); + assert(result.partitionCounts[4].count === 5, 'p(4) = 5'); + assert(result.hassDiagram.nodes.length > 0, 'Hasse diagram has nodes'); + assert(result.hassDiagram.edges.length > 0, 'Hasse diagram has edges'); + + console.log(' ✓ Example: youngLatticeExample()'); + for (const {n, count} of result.partitionCounts) { + console.log(` p(${n}) = ${count}`); + } +} + +function testRobinsonSchenstedCorrespondence() { + const permutation = [3, 1, 4, 2]; + const tableau = createStandardTableauFromPermutation(permutation); + + assert(tableau.size() === 4, 'Tableau has size 4'); + assert(tableau.isValid(), 'Robinson-Schensted produces valid tableau'); + + console.log(' ✓ Example: Robinson-Schensted correspondence'); + console.log(` Permutation: [${permutation.join(', ')}]`); + console.log(' Resulting tableau:'); + console.log(tableau.toString().split('\n').map(line => ' ' + line).join('\n')); +} + +// ============================================================================ +// Integration Tests +// ============================================================================ + +function testYoungIntegration() { + // Test that diagram, tableau, and lattice work together + + const lattice = new YoungLattice(); + const diagrams = lattice.getLevel(4); + + for (const diagram of diagrams) { + // Each diagram should have valid size + assert(diagram.size() === 4, 'Diagram has size 4'); + + // Conjugate should be valid + const conjugate = diagram.conjugate(); + assert(conjugate.size() === 4, 'Conjugate has same size'); + + // Hook length formula should work + const dim = YoungsRule.hookLengthFormula(diagram.toArray()); + assert(dim > 0, 'Hook length produces positive dimension'); + } + + console.log(' ✓ Integration: Diagram, Tableau, Lattice work together'); +} + +// ============================================================================ +// Run All Tests +// ============================================================================ + +function runAllTests() { + console.log('\n' + '='.repeat(70)); + console.log('YOUNG DISCRETE MATHEMATICS TEST SUITE'); + console.log('Testing: Young Diagrams, Tableaux, Lattice, and Young\'s Rule'); + console.log('='.repeat(70)); + + // Young Diagram Tests + testSection('Young Diagram Construction', testYoungDiagramConstruction); + testSection('Young Diagram Conjugate', testYoungDiagramConjugate); + testSection('Young Diagram Containment', testYoungDiagramContainment); + testSection('Young Diagram Successors', testYoungDiagramSuccessors); + testSection('Young Diagram Predecessors', testYoungDiagramPredecessors); + + // Young Tableau Tests + testSection('Young Tableau Construction', testYoungTableauConstruction); + testSection('Young Tableau Validation', testYoungTableauValidation); + testSection('Young Tableau Get/Set', testYoungTableauGetSet); + testSection('Young Tableau Reading Word', testYoungTableauReadingWord); + testSection('Young Tableau Insertion', testYoungTableauInsertion); + + // Young Lattice Tests + testSection('Young Lattice Partitions', testYoungLatticePartitions); + testSection('Young Lattice Partition Function', testYoungLatticePartitionFunction); + testSection('Young Lattice Covering Relations', testYoungLatticeCoveringRelations); + testSection('Young Lattice Hasse Diagram', testYoungLatticeHasseDiagram); + + // Young's Rule Tests + testSection('Hook Length Formula', testHookLengthFormula); + testSection('Self-Conjugate Partitions', testSelfConjugatePartitions); + testSection('Tensor Product (Young\'s Rule)', testTensorProduct); + + // Example Function Tests + testSection('Example: Partitions', testPartitionsExample); + testSection('Example: Young Diagram', testYoungDiagramExampleFunction); + testSection('Example: Young Tableau', testYoungTableauExampleFunction); + testSection('Example: Hook Length', testHookLengthExampleFunction); + testSection('Example: Young Lattice', testYoungLatticeExampleFunction); + testSection('Example: Robinson-Schensted', testRobinsonSchenstedCorrespondence); + + // Integration Tests + testSection('Integration Test', testYoungIntegration); + + console.log('\n' + '='.repeat(70)); + console.log('ALL TESTS PASSED ✓'); + console.log('='.repeat(70) + '\n'); +} + +// Run tests if this file is executed directly +if (require.main === module) { + runAllTests(); +} + +module.exports = { runAllTests }; diff --git a/young-discrete-math.js b/young-discrete-math.js new file mode 100644 index 0000000..eb05000 --- /dev/null +++ b/young-discrete-math.js @@ -0,0 +1,723 @@ +/** + * Young Discrete Mathematics Implementations + * Common situations and areas for "Young" in Discrete Mathematics + * + * Implements: + * - Young Tableaux (standard and semi-standard) + * - Young Diagrams (partition representations) + * - Young Lattice (ordered partitions) + * - Young's Rule (group theory) + * + * @author xaoex + * @see https://linktr.ee/xaoex + */ + +// ============================================================================ +// Young Diagram (Partition Representation) +// Based on partition theory in discrete mathematics +// ============================================================================ + +/** + * Young Diagram - Graphical representation of integer partitions + * + * A Young Diagram is a collection of boxes arranged in left-justified rows + * with non-increasing row lengths, representing a partition of an integer n. + * + * Example: Partition [4, 3, 1] represents: + * **** + * *** + * * + * + * This is a fundamental concept in combinatorics and representation theory. + */ +class YoungDiagram { + /** + * @param {Array} partition - Array of positive integers in non-increasing order + */ + constructor(partition = []) { + // Validate and normalize partition + this.partition = [...partition].filter(x => x > 0).sort((a, b) => b - a); + if (this.partition.length === 0) { + this.partition = []; + } + } + + /** + * Get the size (sum) of the partition + */ + size() { + return this.partition.reduce((sum, val) => sum + val, 0); + } + + /** + * Get the number of rows + */ + numRows() { + return this.partition.length; + } + + /** + * Get the number of columns + */ + numColumns() { + return this.partition.length > 0 ? this.partition[0] : 0; + } + + /** + * Get the conjugate (transpose) partition + * Flip the diagram along the main diagonal + */ + conjugate() { + if (this.partition.length === 0) return new YoungDiagram([]); + + const maxCol = this.partition[0]; + const conjugatePart = []; + + // Count boxes in each column + for (let col = 0; col < maxCol; col++) { + let count = 0; + for (let row = 0; row < this.partition.length; row++) { + if (this.partition[row] > col) { + count++; + } + } + conjugatePart.push(count); + } + + return new YoungDiagram(conjugatePart); + } + + /** + * Check if this diagram contains another diagram + * Used for ordering in Young Lattice + */ + contains(otherDiagram) { + if (this.size() < otherDiagram.size()) return false; + + for (let i = 0; i < otherDiagram.partition.length; i++) { + if (i >= this.partition.length || this.partition[i] < otherDiagram.partition[i]) { + return false; + } + } + return true; + } + + /** + * Get all diagrams that can be obtained by adding one box + */ + successors() { + const result = []; + + // Add box to existing row + for (let i = 0; i < this.partition.length; i++) { + const newPart = [...this.partition]; + newPart[i]++; + // Check if still valid (non-increasing) + if (i === 0 || newPart[i] <= newPart[i - 1]) { + result.push(new YoungDiagram(newPart)); + } + } + + // Add new row with one box + if (this.partition.length === 0 || this.partition[this.partition.length - 1] >= 1) { + const newPart = [...this.partition, 1]; + result.push(new YoungDiagram(newPart)); + } + + return result; + } + + /** + * Get all diagrams that can be obtained by removing one box + */ + predecessors() { + const result = []; + + for (let i = 0; i < this.partition.length; i++) { + const newPart = [...this.partition]; + newPart[i]--; + + // Check if still valid (positive and non-increasing) + const isValid = newPart[i] > 0 && + (i === this.partition.length - 1 || newPart[i] >= this.partition[i + 1]); + + if (isValid) { + result.push(new YoungDiagram(newPart)); + } else if (newPart[i] === 0) { + // Remove the row entirely + newPart.splice(i, 1); + result.push(new YoungDiagram(newPart)); + } + } + + return result; + } + + /** + * Generate ASCII representation + */ + toString() { + if (this.partition.length === 0) return '(empty)'; + return this.partition.map(rowLen => '*'.repeat(rowLen)).join('\n'); + } + + /** + * Get partition as array + */ + toArray() { + return [...this.partition]; + } + + /** + * Check equality with another diagram + */ + equals(other) { + if (this.partition.length !== other.partition.length) return false; + return this.partition.every((val, i) => val === other.partition[i]); + } +} + +// ============================================================================ +// Young Tableau (Combinatorial Structure) +// ============================================================================ + +/** + * Young Tableau - Filling of a Young Diagram with numbers + * + * A Young Tableau is a Young Diagram where each box contains a number, + * with specific ordering properties: + * - Standard: Numbers 1..n appear exactly once, rows/cols increasing + * - Semi-standard: Numbers can repeat, rows weakly increasing, cols strictly increasing + * + * Used in representation theory, combinatorics, and algebraic geometry. + */ +class YoungTableau { + /** + * @param {Array>} filling - 2D array representing the tableau + * @param {boolean} standard - Whether this is a standard tableau + */ + constructor(filling = [[]], standard = false) { + this.filling = filling.filter(row => row && row.length > 0); + this.standard = standard; + this.diagram = new YoungDiagram(this.filling.map(row => row.length)); + } + + /** + * Get the shape (underlying diagram) + */ + shape() { + return this.diagram; + } + + /** + * Get the size (number of boxes) + */ + size() { + return this.diagram.size(); + } + + /** + * Validate if this is a valid Young Tableau + */ + isValid() { + if (this.filling.length === 0) return true; + + // Check rows are weakly increasing + for (const row of this.filling) { + for (let i = 0; i < row.length - 1; i++) { + if (this.standard && row[i] >= row[i + 1]) return false; + if (!this.standard && row[i] > row[i + 1]) return false; + } + } + + // Check columns are strictly increasing + for (let col = 0; col < this.filling[0].length; col++) { + for (let row = 0; row < this.filling.length - 1; row++) { + if (!this.filling[row + 1] || col >= this.filling[row + 1].length) continue; + if (this.filling[row][col] >= this.filling[row + 1][col]) return false; + } + } + + // For standard tableau, check each number 1..n appears exactly once + if (this.standard) { + const nums = []; + for (const row of this.filling) { + nums.push(...row); + } + nums.sort((a, b) => a - b); + const expectedSize = this.size(); + if (nums.length !== expectedSize) return false; + for (let i = 0; i < expectedSize; i++) { + if (nums[i] !== i + 1) return false; + } + } + + return true; + } + + /** + * Get the value at position (row, col) + */ + get(row, col) { + if (row >= this.filling.length || col >= this.filling[row].length) { + return null; + } + return this.filling[row][col]; + } + + /** + * Set the value at position (row, col) + */ + set(row, col, value) { + if (row >= this.filling.length || col >= this.filling[row].length) { + return false; + } + this.filling[row][col] = value; + return true; + } + + /** + * Generate ASCII representation + */ + toString() { + if (this.filling.length === 0) return '(empty)'; + + // Find max width for padding + const maxWidth = Math.max(...this.filling.flat().map(n => String(n).length)); + + return this.filling.map(row => + row.map(val => String(val).padStart(maxWidth)).join(' ') + ).join('\n'); + } + + /** + * Get the reading word (read row by row, right to left) + */ + readingWord() { + const word = []; + for (let row = this.filling.length - 1; row >= 0; row--) { + for (let col = this.filling[row].length - 1; col >= 0; col--) { + word.push(this.filling[row][col]); + } + } + return word; + } + + /** + * Apply Robinson-Schensted insertion of a value + * Used for constructing standard tableaux + */ + insertValue(value) { + const newFilling = this.filling.map(row => [...row]); + let currentVal = value; + let rowIdx = 0; + + while (currentVal !== null) { + if (rowIdx >= newFilling.length) { + // Add new row + newFilling.push([currentVal]); + currentVal = null; + } else { + // Find position in current row + let insertPos = newFilling[rowIdx].length; + for (let i = 0; i < newFilling[rowIdx].length; i++) { + if (newFilling[rowIdx][i] > currentVal) { + insertPos = i; + break; + } + } + + if (insertPos === newFilling[rowIdx].length) { + // Append to row + newFilling[rowIdx].push(currentVal); + currentVal = null; + } else { + // Bump existing value + const bumped = newFilling[rowIdx][insertPos]; + newFilling[rowIdx][insertPos] = currentVal; + currentVal = bumped; + rowIdx++; + } + } + } + + return new YoungTableau(newFilling, this.standard); + } +} + +// ============================================================================ +// Young Lattice (Ordered Structure) +// ============================================================================ + +/** + * Young Lattice - Partially ordered set of partitions + * + * The Young Lattice is the poset of all integer partitions ordered by inclusion. + * A partition λ covers μ if λ can be obtained from μ by adding one box. + * + * This structure is fundamental in combinatorics and representation theory. + */ +class YoungLattice { + constructor() { + // Cache of computed levels + this.levels = new Map(); + this.levels.set(0, [new YoungDiagram([])]); + } + + /** + * Get all diagrams at a given level (size n) + */ + getLevel(n) { + if (this.levels.has(n)) { + return this.levels.get(n); + } + + // Generate all partitions of n + const partitions = this.generatePartitions(n); + const diagrams = partitions.map(p => new YoungDiagram(p)); + + this.levels.set(n, diagrams); + return diagrams; + } + + /** + * Generate all integer partitions of n + */ + generatePartitions(n, max = n) { + if (n === 0) return [[]]; + if (n < 0) return []; + + const result = []; + for (let i = Math.min(n, max); i >= 1; i--) { + const subPartitions = this.generatePartitions(n - i, i); + for (const sub of subPartitions) { + result.push([i, ...sub]); + } + } + + return result; + } + + /** + * Count partitions of n (partition function p(n)) + */ + countPartitions(n) { + return this.getLevel(n).length; + } + + /** + * Get all covering relations at level n + * Returns pairs [smaller, larger] where larger covers smaller + */ + getCoveringRelations(n) { + if (n === 0) return []; + + const lowerLevel = this.getLevel(n - 1); + const upperLevel = this.getLevel(n); + const relations = []; + + for (const lower of lowerLevel) { + for (const upper of upperLevel) { + // Check if upper covers lower (differs by exactly one box) + if (upper.contains(lower)) { + // Verify it's a covering relation (differs by exactly one) + const upperSum = upper.size(); + const lowerSum = lower.size(); + if (upperSum === lowerSum + 1) { + relations.push([lower, upper]); + } + } + } + } + + return relations; + } + + /** + * Get the Hasse diagram up to level n + * Returns structure with nodes and edges + */ + getHasseDiagram(n) { + const nodes = []; + const edges = []; + + for (let level = 0; level <= n; level++) { + const diagrams = this.getLevel(level); + nodes.push(...diagrams.map(d => ({ + level, + partition: d.toArray(), + diagram: d + }))); + + if (level > 0) { + const relations = this.getCoveringRelations(level); + edges.push(...relations.map(([lower, upper]) => ({ + from: lower.toArray(), + to: upper.toArray() + }))); + } + } + + return { nodes, edges }; + } + + /** + * Get maximal chains from empty partition to partition of n + * A maximal chain corresponds to a standard Young tableau + */ + getMaximalChains(n) { + if (n === 0) return [[]]; + + const chains = []; + const diagrams = this.getLevel(n); + + for (const diagram of diagrams) { + this._buildChains(diagram, [], chains); + } + + return chains; + } + + /** + * Helper: Build chains recursively + */ + _buildChains(current, path, result) { + const newPath = [current, ...path]; + + if (current.size() === 0) { + result.push(newPath.reverse()); + return; + } + + const predecessors = current.predecessors(); + for (const pred of predecessors) { + this._buildChains(pred, newPath, result); + } + } +} + +// ============================================================================ +// Young's Rule and Symmetrizer +// ============================================================================ + +/** + * Young's Rule - For decomposing tensor products in representation theory + * + * Given two partitions λ and μ, Young's Rule describes how to decompose + * the tensor product of corresponding representations. + */ +class YoungsRule { + /** + * Apply Littlewood-Richardson rule to compute tensor product + * Returns the multiplicities of irreducible representations + * + * @param {Array} lambda - First partition + * @param {Array} mu - Second partition + * @returns {Map} Map from partition to multiplicity + */ + static tensorProduct(lambda, mu) { + // Simplified version: Just enumerate possible results + // Full implementation would use Littlewood-Richardson coefficients + + const diagram1 = new YoungDiagram(lambda); + const diagram2 = new YoungDiagram(mu); + + const n1 = diagram1.size(); + const n2 = diagram2.size(); + const totalSize = n1 + n2; + + const lattice = new YoungLattice(); + const possibleResults = lattice.getLevel(totalSize); + + // For simplicity, return all partitions of the combined size + // A full implementation would compute Littlewood-Richardson coefficients + const result = new Map(); + for (const diagram of possibleResults) { + // Placeholder: assign multiplicity 1 to all valid partitions + // Real implementation would compute actual multiplicities + result.set(diagram.toArray().join(','), 1); + } + + return result; + } + + /** + * Compute the dimension of the irreducible representation + * corresponding to a partition using the hook length formula + * + * @param {Array} partition - Integer partition + * @returns {number} Dimension of the representation + */ + static hookLengthFormula(partition) { + if (partition.length === 0) return 1; + + const diagram = new YoungDiagram(partition); + const n = diagram.size(); + + // Compute hook lengths + const hooks = []; + for (let i = 0; i < partition.length; i++) { + for (let j = 0; j < partition[i]; j++) { + // Hook length = arm length + leg length + 1 + let arm = partition[i] - j - 1; // boxes to the right + let leg = 0; // boxes below + for (let k = i + 1; k < partition.length; k++) { + if (j < partition[k]) leg++; + } + hooks.push(arm + leg + 1); + } + } + + // Dimension = n! / (product of hook lengths) + let factorial = 1; + for (let i = 2; i <= n; i++) { + factorial *= i; + } + + let hookProduct = 1; + for (const h of hooks) { + hookProduct *= h; + } + + return factorial / hookProduct; + } + + /** + * Check if a partition is self-conjugate + * (equals its own transpose) + */ + static isSelfConjugate(partition) { + const diagram = new YoungDiagram(partition); + const conjugate = diagram.conjugate(); + return diagram.equals(conjugate); + } +} + +// ============================================================================ +// Factory Functions and Examples +// ============================================================================ + +/** + * Create a standard Young Tableau from a permutation + * using Robinson-Schensted correspondence + */ +function createStandardTableauFromPermutation(permutation) { + let tableau = new YoungTableau([[]], true); + + for (const value of permutation) { + tableau = tableau.insertValue(value); + } + + return tableau; +} + +/** + * Example: Generate all partitions up to n + */ +function partitionsExample(n = 5) { + const lattice = new YoungLattice(); + const result = {}; + + for (let i = 0; i <= n; i++) { + const partitions = lattice.getLevel(i).map(d => d.toArray()); + result[i] = partitions; + } + + return result; +} + +/** + * Example: Demonstrate Young Diagram operations + */ +function youngDiagramExample() { + const diagram = new YoungDiagram([4, 3, 1]); + + return { + partition: diagram.toArray(), + size: diagram.size(), + rows: diagram.numRows(), + cols: diagram.numColumns(), + ascii: diagram.toString(), + conjugate: diagram.conjugate().toArray(), + successors: diagram.successors().map(d => d.toArray()), + predecessors: diagram.predecessors().map(d => d.toArray()) + }; +} + +/** + * Example: Create and validate Young Tableau + */ +function youngTableauExample() { + // Standard Young Tableau + const tableau = new YoungTableau([ + [1, 2, 5], + [3, 4], + [6] + ], true); + + return { + filling: tableau.filling, + shape: tableau.shape().toArray(), + size: tableau.size(), + valid: tableau.isValid(), + ascii: tableau.toString(), + readingWord: tableau.readingWord() + }; +} + +/** + * Example: Demonstrate hook length formula + */ +function hookLengthExample() { + const partitions = [[3, 2, 1], [4, 2], [2, 2, 2], [5, 1]]; + const results = {}; + + for (const partition of partitions) { + const dim = YoungsRule.hookLengthFormula(partition); + results[partition.join(',')] = { + partition, + dimension: dim, + size: partition.reduce((a, b) => a + b, 0) + }; + } + + return results; +} + +/** + * Example: Young Lattice structure + */ +function youngLatticeExample(n = 4) { + const lattice = new YoungLattice(); + + return { + partitionCounts: Array.from({length: n + 1}, (_, i) => ({ + n: i, + count: lattice.countPartitions(i), + partitions: lattice.getLevel(i).map(d => d.toArray()) + })), + hassDiagram: lattice.getHasseDiagram(3) + }; +} + +// ============================================================================ +// Module Exports +// ============================================================================ + +module.exports = { + // Classes + YoungDiagram, + YoungTableau, + YoungLattice, + YoungsRule, + + // Factory functions + createStandardTableauFromPermutation, + + // Examples + partitionsExample, + youngDiagramExample, + youngTableauExample, + hookLengthExample, + youngLatticeExample +};