Created
August 9, 2016 22:51
-
-
Save brihter/88f15b3750afa30b241a3c6e85aa0e00 to your computer and use it in GitHub Desktop.
some fs & treenode testing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Collections; | |
using System.Linq; | |
namespace Sandbox | |
{ | |
public class TreeExperiment : IExperiment | |
{ | |
class TreeNode | |
{ | |
public string Name { get; set;} | |
public TreeNode Parent { get; set; } | |
public bool Leaf { get; set;} | |
public Dictionary<string, TreeNode> Children { get; set; } | |
public bool Last { get; set; } | |
public TreeNode(string name) | |
{ | |
Name = name; | |
Leaf = true; | |
Last = false; | |
Parent = null; | |
Children = new Dictionary<string, TreeNode>(); | |
} | |
public TreeNode AddChild(string name) | |
{ | |
var child = new TreeNode(name); | |
child.Parent = this; | |
Leaf = false; | |
Children.Add(child.Name, child); | |
return child; | |
} | |
// /home/bostjan -> root->home->bostjan | |
public void AddPath(string path) | |
{ | |
var parts = path.Split(Path.DirectorySeparatorChar); | |
TreeNode ptr = null; | |
foreach (var part in parts) | |
{ | |
if (ptr == null) | |
ptr = this; | |
if (part.Length == 0) | |
continue; | |
if (!ptr.Children.ContainsKey(part)) | |
ptr = ptr.AddChild(part); | |
else | |
ptr = ptr.Children[part]; | |
} | |
ptr.Last = true; | |
} | |
public void Traverse(Func<TreeNode, bool> fn) | |
{ | |
TreeNode ptr = this; | |
var r = fn(ptr); | |
if (!r) | |
return; | |
foreach (var child in Children) | |
{ | |
ptr = child.Value; | |
ptr.Traverse(fn); | |
} | |
} | |
public string GetPath() | |
{ | |
var parts = new List<string>(); | |
var ptr = this; | |
while (ptr.Parent != null) | |
{ | |
parts.Add(ptr.Name); | |
ptr = ptr.Parent; | |
} | |
parts.Reverse(); | |
return string.Join(Path.DirectorySeparatorChar.ToString(), parts.ToArray()); | |
} | |
} | |
public TreeExperiment() | |
{ | |
} | |
public void Run() { | |
var paths = new List<string> { | |
"/home/bostjan/Music/dj/techno/", | |
"/home/bostjan/Music/dj/techno/shlomi aber/", | |
"/home/bostjan/Music/", | |
"/home/bostjan/Music/other" | |
}; | |
// build path tree | |
var fs = new TreeNode("/"); | |
foreach (var path in paths) | |
fs.AddPath(path); | |
// now extract the paths that need to be indexed | |
var toIndex = new List<string>(); | |
fs.Traverse(node => | |
{ | |
if (node.Last) { | |
toIndex.Add(node.GetPath()); | |
return false; | |
} | |
return true; | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment