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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
//! # Tree-Memory-Sort //! //! An in-memory topological sort algorithm for trees based on Group Theory //! //! ### Design //! //! This algorithm uses in-memory swapping directly on the array which nodes are stored. //! Since swap operations satisfy the axioms of Group Theory, //! the topological sort can be made more efficient by using a group generator. //! //! A group generator is an array which stores an index for every node index. //! When swap operations are performed on the array instead of the data, //! it is possible to predict where nodes will be stored in the solution //! without changing the meaning of the current node indices. //! //! Once a solution has been found, the group generator can be used to //! retrace the swapping operations required to order the tree. //! //! The order which swaps are retraced might be different than the solving phase: //! //! ```text //! `a, b, c` => `a, (c, b)` => `(c, a), b` => `c, a, b` (solving phase) //! `c, a, b` => `(b), a, (c)` => `(a, b), c` => `a, b, c` (retrace phase) //! ``` //! //! //! ### Primes example //! //! This example shows how the algorithm works using some simple numbers. //! //! Assume that you have two equations: //! //! ```text //! 12 = 2 * 6 //! 6 = 3 * 2 //! ``` //! //! If you arrange these equations as a tree, //! you will naturally start at the top `12` and list //! children of each node in the same order as in the equations. //! //! When using an automated theorem prover that re-writes //! a tree like this, it can get messy. //! Some algorithms relies on a well-ordered tree to perform efficiently. //! //! By performing topological sort on the tree, //! it can be restored to a well-ordered form: //! //! ```text //! Tree i i' //! -------------------------- //! 12 3 => 0 //! |- 2 2 => 1 //! |- 6 1 => 2 //! |- 3 4 => 3 //! |- 2 0 => 4 //! ``` //! //! The algorithm does not change the relative connections inside the tree, //! just how nodes are stored in memory. //! However, it needs to change the indices such they point to the correct nodes. //! //! Source code: //! //! ```rust //! extern crate tree_mem_sort; //! //! use tree_mem_sort::sort; //! //! #[derive(Debug)] //! pub struct Number { //! /// The value of the number. //! pub value: u32, //! /// Which number this was factored from. //! pub parent: Option<usize>, //! /// Prime factors. //! pub children: Vec<usize>, //! } //! //! fn main() { //! let mut nodes = vec![ //! Number { //! value: 2, //! parent: Some(1), //! children: vec![], //! }, // 0 //! Number { //! value: 6, //! parent: Some(0), //! children: vec![4, 0], //! }, // 1 //! Number { //! value: 2, //! parent: Some(2), //! children: vec![], //! }, // 2 //! Number { //! value: 12, //! parent: None, //! children: vec![2, 1], //! }, // 3 //! Number { //! value: 3, //! parent: Some(2), //! children: vec![], //! }, // 4 //! ]; //! for i in 0..nodes.len() { //! println!("{}: {:?}", i, nodes[i]); //! } //! // Prints `[2, 6, 2, 12, 3]` //! println!("{:?}", nodes.iter().map(|n| n.value).collect::<Vec<u32>>()); //! //! sort(&mut nodes, |n| &mut n.parent, |n| &mut n.children); //! println!(""); //! for i in 0..nodes.len() { //! println!("{}: {:?}", i, nodes[i]); //! } //! // Prints `[12, 2, 6, 3, 2]` //! println!("{:?}", nodes.iter().map(|n| n.value).collect::<Vec<u32>>()); //! } //! ``` //! //! ### Limitations //! //! The `sort` algorithm assumes that each node is referenced by maximum one parent. //! If you share nodes between parent nodes, the algorithm might enter an infinite loop. //! //! One can use `sort_dag` to sort a tree where nodes can have multiple parents. //! In order for the algorithm to work with shared nodes, //! the tree must be a Directed Acyclic Graph (DAG). //! If the tree is not a DAG, the algorithm will run in an infinite loop. //! //! ### Why topological sort on trees? Why not use DAG representation? //! //! The idea is to preserve the following properties, and otherwise minimize work: //! //! - Each child is greater than their parent //! - Each sibling is greater than previous siblings //! //! Topological sorts is often associated with Directed Acyclic Graphs (DAG) and not trees. //! This algorithm works on DAGs, but not on all trees with shared nodes. //! //! - If every node is referenced by maximum one parent, then it is automatically a DAG //! - Trees with ordered children encode arrows among siblings, which affects whether it is a DAG //! //! For example, the following tree with shared nodes is not a DAG: //! //! ```text //! A //! |- B //! |- D //! |- C //! |- C //! |- D //! ``` //! //! Notice that `B` orders `D` before `C`, so `D` is less than `C`. //! However, since `D` is a child of `C` it must be greater than `C`. //! This leads to a contradiction. //! //! If you try to sort the tree above using `sort_dag`, it will run in an infinite loop. //! //! Trees are easy to reason about and has a more efficient encoding for this library's common usage. //! For `N` children, the arrows of an equivalent DAG requires at least `N` arrows. //! In addition, these arrows must be arranged in a such way that the children becomes a total order. //! This is necessary to determine the order for every pair of children. //! By using a tree with ordered children, the memory required for arrows is zero, //! because the children are stored in an array anyway. //! //! A left-child first traversal of a tree without shared nodes //! can be used to produce a topological order. //! However, building indices from traversal of a tree makes all indices //! of a right-child larger than the indices of a left-child. //! This moves nodes around more than desirable. //! //! For forests, a tree traversal also requires an extra pass through all nodes. //! Here, the algorithm that sorts trees also works for forests without modification. //! //! A topological sort of a tree has the property that if you push a new node //! at the end of the array storing the nodes, which node's parent is any existing node, //! then the new tree is topologically sorted. //! The same is not true for indices built from tree traversal. #![deny(missing_docs)] /// Performs in-memory topological sort on a tree where /// order is determined by every child being greater than their parent, /// and every sibling being greater than previous siblings. pub fn sort<T, P, C>(nodes: &mut [T], parent: P, children: C) where P: Fn(&mut T) -> &mut Option<usize>, C: Fn(&mut T) -> &mut [usize] { // This problem can be solved efficiently using Group Theory. // This avoids the need for cloning nodes into a new array, // while performing the minimum work to get a normalized tree. // // Create a group generator that is modified by swapping to find a solution. // The group generator keeps track of indices, such that child-parent relations // do not have to change until later. // // Use the order in the generator to detect whether a swap has been performed. // The condition for swapping `a, b` is `gen[a] > gen[b]`. let mut gen: Vec<usize> = (0..nodes.len()).collect(); loop { let mut changed = false; for i in 0..nodes.len() { let children = children(&mut nodes[i]); for j in 0..children.len() { let a = children[j]; // Store child after its parent. if gen[i] > gen[a] { gen.swap(i, a); changed = true; } // Check all pairs of children. for k in j + 1..children.len() { let b = children[k]; // Store children in sorted order. if gen[a] > gen[b] { gen.swap(a, b); changed = true; } } } } if !changed { break; } } // Update the tree data with the new indices from the generator. // Do this before performing the actual swapping, // since the generator maps from old indices to new indices. for i in 0..nodes.len() { let p = parent(&mut nodes[i]); *p = p.map(|p| gen[p]); for ch in children(&mut nodes[i]) { *ch = gen[*ch] } } // Swap nodes using the group generator as guide. // When swapping has been performed, update the generator to keep track of state. // This is because multiple swaps sharing elements might require multiple steps. // // The order which swaps are retraced might be different than the solving phase: // // `a, b, c` => `a, (c, b)` => `(c, a), b` => `c, a, b` (solving phase) // `c, a, b` => `(b), a, (c)` => `(a, b), c` => `a, b, c` (retrace phase) // // However, since the generator solution is produced by swapping operations, // it is guaranteed to be restorable to the identity generator when retracing. // In fact, it works for any permutation of the identity generator. // // There is no need to loop more than once because each index is stored uniquely by lookup, // such that if `g[i] = i` then there exists no `j != i` such that `g[j] = i`. // // Retrace by putting nodes where they belong (`g[i]`). // Once a node is put where it belongs, no need further work is needed for `g[i]`. // It means that the problem has been reduced from size `n` to `n-1`. // // However, in order to put one node from `i` to where it belongs `g[i]`, // one must also keep track of the node who occupied the previous `j = g[i]`. // Not only keep track of the node data, but where it belongs `g[j]` too. // // Fortunately, the old position (`i`) is free as a temporary location. // This is why `i` and `g[i]` are swapped. // The same swap is done in the group generator to track where the new node belongs: // `gen[j] => gen[i]` // // This procedure is repeated for the new node `i`, // putting it where it belongs `g[i]`, and in return receive a new task `gen[j] => gen[i]`. // The task is repeated until `i` belongs to where it should be, // then it goes to the next step, where the same procedure is repeated. // All nodes which have previously been put where they belong does not need any work, // and there is no need to go back, since no node will be swapped with an earlier location. for i in 0..nodes.len() { while gen[i] != i { let j = gen[i]; nodes.swap(i, j); gen.swap(i, j); } } } /// The same algorithm as `sort`, but for Directed Acyclic Graphs (DAGs), /// encoded as trees with shared nodes. /// /// WARNING: To avoid an infinite loop, one must be careful about the order of children. /// E.g. if `A` has children `C, B` and `B` has child `C`, then the tree is not a DAG. /// This is because the order of children is preserved after sorting. pub fn sort_dag<T, P, C>(nodes: &mut [T], parents: P, children: C) where P: Fn(&mut T) -> &mut [usize], C: Fn(&mut T) -> &mut [usize] { let mut gen: Vec<usize> = (0..nodes.len()).collect(); loop { let mut changed = false; for i in 0..nodes.len() { let children = children(&mut nodes[i]); for j in 0..children.len() { let a = children[j]; // Store child after its parent. if gen[i] > gen[a] { gen.swap(i, a); changed = true; } // Check all pairs of children. for k in j + 1..children.len() { let b = children[k]; // Store children in sorted order. if gen[a] > gen[b] { gen.swap(a, b); changed = true; } } } } if !changed { break; } } for i in 0..nodes.len() { for p in parents(&mut nodes[i]) { *p = gen[*p]; } for ch in children(&mut nodes[i]) { *ch = gen[*ch] } } for i in 0..nodes.len() { while gen[i] != i { let j = gen[i]; nodes.swap(i, j); gen.swap(i, j); } } } #[cfg(test)] mod tests { use super::*; #[derive(PartialEq, Debug)] struct Node { val: u32, parent: Option<usize>, children: Vec<usize>, } #[test] fn empty() { let mut nodes: Vec<Node> = vec![]; sort(&mut nodes, |n| &mut n.parent, |n| &mut n.children); assert_eq!(nodes.len(), 0); } #[test] fn one() { let mut nodes: Vec<Node> = vec![Node { val: 0, parent: None, children: vec![], }]; sort(&mut nodes, |n| &mut n.parent, |n| &mut n.children); assert_eq!( nodes, vec![Node { val: 0, parent: None, children: vec![] }] ); } #[test] fn two() { let mut nodes: Vec<Node> = vec![ Node { val: 0, parent: None, children: vec![], }, Node { val: 1, parent: None, children: vec![], }, ]; sort(&mut nodes, |n| &mut n.parent, |n| &mut n.children); assert_eq!( nodes, vec![ Node { val: 0, parent: None, children: vec![] }, Node { val: 1, parent: None, children: vec![] }, ] ); let mut nodes: Vec<Node> = vec![ Node { val: 1, parent: Some(1), children: vec![], }, Node { val: 0, parent: None, children: vec![0], }, ]; sort(&mut nodes, |n| &mut n.parent, |n| &mut n.children); assert_eq!( nodes, vec![ Node { val: 0, parent: None, children: vec![1] }, Node { val: 1, parent: Some(0), children: vec![] }, ] ); } #[test] fn three() { let mut nodes: Vec<Node> = vec![ Node { val: 2, parent: Some(1), children: vec![], }, Node { val: 1, parent: Some(2), children: vec![0], }, Node { val: 0, parent: None, children: vec![1], }, ]; sort(&mut nodes, |n| &mut n.parent, |n| &mut n.children); assert_eq!( nodes, vec![ Node { val: 0, parent: None, children: vec![1] }, Node { val: 1, parent: Some(0), children: vec![2] }, Node { val: 2, parent: Some(1), children: vec![] } ] ); let mut nodes: Vec<Node> = vec![ Node { val: 1, parent: Some(2), children: vec![1], }, Node { val: 2, parent: Some(0), children: vec![], }, Node { val: 0, parent: None, children: vec![0], }, ]; sort(&mut nodes, |n| &mut n.parent, |n| &mut n.children); assert_eq!( nodes, vec![ Node { val: 0, parent: None, children: vec![1] }, Node { val: 1, parent: Some(0), children: vec![2] }, Node { val: 2, parent: Some(1), children: vec![] } ] ); let mut nodes: Vec<Node> = vec![ Node { val: 2, parent: Some(2), children: vec![], }, Node { val: 1, parent: Some(2), children: vec![], }, Node { val: 0, parent: None, children: vec![1, 0], }, ]; sort(&mut nodes, |n| &mut n.parent, |n| &mut n.children); assert_eq!( nodes, vec![ Node { val: 0, parent: None, children: vec![1, 2] }, Node { val: 1, parent: Some(0), children: vec![] }, Node { val: 2, parent: Some(0), children: vec![] } ] ); let mut nodes: Vec<Node> = vec![ Node { val: 1, parent: Some(2), children: vec![], }, Node { val: 2, parent: Some(2), children: vec![], }, Node { val: 0, parent: None, children: vec![0, 1], }, ]; sort(&mut nodes, |n| &mut n.parent, |n| &mut n.children); assert_eq!( nodes, vec![ Node { val: 0, parent: None, children: vec![1, 2] }, Node { val: 1, parent: Some(0), children: vec![] }, Node { val: 2, parent: Some(0), children: vec![] } ] ); let mut nodes: Vec<Node> = vec![ Node { val: 1, parent: Some(1), children: vec![], }, Node { val: 0, parent: None, children: vec![0, 2], }, Node { val: 2, parent: Some(1), children: vec![], }, ]; sort(&mut nodes, |n| &mut n.parent, |n| &mut n.children); assert_eq!( nodes, vec![ Node { val: 0, parent: None, children: vec![1, 2] }, Node { val: 1, parent: Some(0), children: vec![] }, Node { val: 2, parent: Some(0), children: vec![] } ] ); let mut nodes: Vec<Node> = vec![ Node { val: 2, parent: Some(1), children: vec![], }, Node { val: 0, parent: None, children: vec![2, 0], }, Node { val: 1, parent: Some(1), children: vec![], }, ]; sort(&mut nodes, |n| &mut n.parent, |n| &mut n.children); assert_eq!( nodes, vec![ Node { val: 0, parent: None, children: vec![1, 2] }, Node { val: 1, parent: Some(0), children: vec![] }, Node { val: 2, parent: Some(0), children: vec![] } ] ); } #[test] fn four() { let mut nodes: Vec<Node> = vec![ Node { val: 3, parent: Some(1), children: vec![], }, Node { val: 2, parent: Some(2), children: vec![0], }, Node { val: 1, parent: Some(3), children: vec![1], }, Node { val: 0, parent: None, children: vec![2], }, ]; sort(&mut nodes, |n| &mut n.parent, |n| &mut n.children); assert_eq!( nodes, vec![ Node { val: 0, parent: None, children: vec![1] }, Node { val: 1, parent: Some(0), children: vec![2] }, Node { val: 2, parent: Some(1), children: vec![3] }, Node { val: 3, parent: Some(2), children: vec![] } ] ); let mut nodes: Vec<Node> = vec![ Node { val: 2, parent: Some(2), children: vec![1], }, Node { val: 3, parent: Some(0), children: vec![], }, Node { val: 1, parent: Some(3), children: vec![0], }, Node { val: 0, parent: None, children: vec![2], }, ]; sort(&mut nodes, |n| &mut n.parent, |n| &mut n.children); assert_eq!( nodes, vec![ Node { val: 0, parent: None, children: vec![1] }, Node { val: 1, parent: Some(0), children: vec![2] }, Node { val: 2, parent: Some(1), children: vec![3] }, Node { val: 3, parent: Some(2), children: vec![] } ] ); let mut nodes: Vec<Node> = vec![ Node { val: 2, parent: Some(3), children: vec![1], }, Node { val: 3, parent: Some(0), children: vec![], }, Node { val: 0, parent: None, children: vec![3], }, Node { val: 1, parent: Some(2), children: vec![0], }, ]; sort(&mut nodes, |n| &mut n.parent, |n| &mut n.children); assert_eq!( nodes, vec![ Node { val: 0, parent: None, children: vec![1] }, Node { val: 1, parent: Some(0), children: vec![2] }, Node { val: 2, parent: Some(1), children: vec![3] }, Node { val: 3, parent: Some(2), children: vec![] } ] ); let mut nodes: Vec<Node> = vec![ Node { val: 2, parent: Some(2), children: vec![], }, Node { val: 3, parent: Some(3), children: vec![], }, Node { val: 1, parent: Some(3), children: vec![0], }, Node { val: 0, parent: None, children: vec![2, 1], }, ]; sort(&mut nodes, |n| &mut n.parent, |n| &mut n.children); assert_eq!( nodes, vec![ Node { val: 0, parent: None, children: vec![1, 3] }, Node { val: 1, parent: Some(0), children: vec![2] }, Node { val: 2, parent: Some(1), children: vec![] }, Node { val: 3, parent: Some(0), children: vec![] } ] ); let mut nodes: Vec<Node> = vec![ Node { val: 3, parent: Some(3), children: vec![], }, Node { val: 1, parent: None, children: vec![], }, Node { val: 2, parent: Some(3), children: vec![], }, Node { val: 0, parent: None, children: vec![2, 0], }, ]; sort(&mut nodes, |n| &mut n.parent, |n| &mut n.children); assert_eq!( nodes, vec![ Node { val: 0, parent: None, children: vec![2, 3] }, Node { val: 1, parent: None, children: vec![] }, Node { val: 2, parent: Some(0), children: vec![] }, Node { val: 3, parent: Some(0), children: vec![] } ] ); let mut nodes: Vec<Node> = vec![ Node { val: 3, parent: Some(2), children: vec![], }, Node { val: 2, parent: Some(2), children: vec![], }, Node { val: 1, parent: Some(3), children: vec![1, 0], }, Node { val: 0, parent: None, children: vec![2], }, ]; sort(&mut nodes, |n| &mut n.parent, |n| &mut n.children); assert_eq!( nodes, vec![ Node { val: 0, parent: None, children: vec![1] }, Node { val: 1, parent: Some(0), children: vec![2, 3] }, Node { val: 2, parent: Some(1), children: vec![] }, Node { val: 3, parent: Some(1), children: vec![] } ] ); let mut nodes: Vec<Node> = vec![ Node { val: 0, parent: None, children: vec![3, 2], }, Node { val: 2, parent: Some(3), children: vec![], }, Node { val: 3, parent: Some(0), children: vec![], }, Node { val: 1, parent: Some(0), children: vec![1], }, ]; sort(&mut nodes, |n| &mut n.parent, |n| &mut n.children); assert_eq!( nodes, vec![ Node { val: 0, parent: None, children: vec![1, 3] }, Node { val: 1, parent: Some(0), children: vec![2] }, Node { val: 2, parent: Some(1), children: vec![] }, Node { val: 3, parent: Some(0), children: vec![] }, ] ); } }