//public static void DeleteSequence(Link sequence)
        //{
        //}
        public static string FormatSequence(Link sequence)
        {
            int visitedElements = 0;

            StringBuilder sb = new StringBuilder();

            sb.Append('[');

            StopableSequenceWalker walker = new StopableSequenceWalker(sequence, element =>
            {
                if (visitedElements > 0)
                    sb.Append(',');

                sb.Append(element.ToString());

                visitedElements++;

                if (visitedElements < MaxSequenceFormatSize)
                {
                    return true;
                }
                else
                {
                    sb.Append(", ...");
                    return false;
                }
            });

            walker.WalkFromLeftToRight();

            sb.Append(']');

            return sb.ToString();
        }
 public static char ToChar(Link link)
 {
     char c;
     if (!LinksToCharacters.TryGetValue(link, out c))
     {
         throw new ArgumentOutOfRangeException("charLink", "Указанная связь не являяется символом.");
     }
     return c;
 }
예제 #3
0
        public static LinkModel CreateLinkModel(Link link, int nestingLevel = 3)
        {
            //ThreadHelpers.SyncInvokeWithExtendedStack(() =>
            //{
            const int currentLevel = 0;
            var visitedLinks = new HashSet<Link>();
            LinkModel result = CreateLinkModel(link, visitedLinks, currentLevel, nestingLevel);
            //});

            return result;
        }
예제 #4
0
 // Проверка на пренадлежность классу
 public static bool Is(this Link link, Link @class)
 {
     if (link.Linker == Net.IsA)
     {
         if (link.Target == @class)
             return true;
         else
             return link.Target.Is(@class);
     }
     return false;
 }
예제 #5
0
 public static Link[] GetArrayOfRererersByTarget(this Link link)
 {
     if (link == null)
         return new Link[0];
     else
     {
         var array = new Link[link.ReferersByTargetCount];
         int index = 0;
         link.WalkThroughReferersByTarget(referer => array[index++] = referer);
         return array;
     }
 }
        public static Link[] GetLeftElements(Link startLink, Link leftLink)
        {
            var result = new Link[4];

            TryStepLeft(startLink, leftLink, result, 0);

            startLink.WalkThroughReferersBySource(couple =>
                {
                    if (couple.Linker == Net.And)
                        if (TryStepLeft(couple, leftLink, result, 2))
                            return Link.Stop;

                    return Link.Continue;
                });

            return result;
        }
        public static List<Link> CollectMatchingSequences(Link[] links)
        {
            if (links.Length == 1)
            {
                throw new Exception("Подпоследовательности с одним элементом не поддерживаются.");
            }

            int leftBound = 0;
            int rightBound = links.Length - 1;

            Link left = links[leftBound++];
            Link right = links[rightBound--];

            List<Link> results = new List<Link>();
            CollectMatchingSequences(left, leftBound, links, right, rightBound, ref results);
            return results;
        }
예제 #8
0
        public static Link FromNumber(long number)
        {
            if (number == 0)
                return Net.Zero;
            if (number == 1)
                return Net.One;

            var links = new Link[CountBits(number)];

            if (number >= 0)
            {
                for (long key = 1, powerOf2 = 0, i = 0; key <= number; key += key, powerOf2++)
                    if ((number & key) == key)
                        links[i++] = FromPowerOf2(powerOf2);
            }
            else
                throw new NotSupportedException("Negative numbers are not supported yet.");

            Link sum = Link.Create(Net.Sum, Net.Of, LinkConverter.FromList(links));
            return sum;
        }
예제 #9
0
        public static long ToNumber(Link link)
        {
            if (link == Net.Zero)
                return 0;
            if (link == Net.One)
                return 1;

            if (link.IsSum())
            {
                List<Link> numberParts = LinkConverter.ToList(link.Target);

                long number = 0;
                for (var i = 0; i < numberParts.Count; i++)
                {
                    long numberPart;
                    GoDownAndTakeIt(numberParts[i], out numberPart);
                    number += numberPart;
                }

                return number;
            }
            throw new ArgumentOutOfRangeException("link", "Specified link is not a number.");
        }
예제 #10
0
        private static LinkModel CreateLinkModel(Link link, HashSet<Link> visitedLinks, int currentLevel, int maxLevel)
        {
            var model = new LinkModel(link);

            if (currentLevel < maxLevel)
            {
                if (currentLevel == 0 || link.TotalReferers < 10)
                {
                    currentLevel++;

                    link.WalkThroughReferers(referer =>
                    {
                        if (link != referer && visitedLinks.Add(referer))
                        {
                            model.ReferersModels.Add(CreateLinkModel(referer, visitedLinks, currentLevel, maxLevel));
                        }
                    });

                    model.ReferersModels.Sort((x, y) => x.Link.ToInt().CompareTo(y.Link.ToInt()));
                }
            }

            return model;
        }
예제 #11
0
        private static void GoDownAndTakeIt(Link link, out long number)
        {
            if (!LinksToNumbers.TryGetValue(link, out number))
            {
                Link previousNumberLink = link.Target.Source;

                GoDownAndTakeIt(previousNumberLink, out number);

                var previousNumberIndex = (int)Math.Log(number, 2);

                int newNumberIndex = previousNumberIndex + 1;
                Link newNumberLink = Link.Create(Net.Sum, Net.Of, previousNumberLink & previousNumberLink);

                number = number + number;

                NumbersToLinks[newNumberIndex] = newNumberLink;
                LinksToNumbers[newNumberLink] = number;
            }
        }
예제 #12
0
 public SequenceWalker(Link sequence, Action<Link> visit)
 {
     _root = sequence;
     _visit = visit;
     _stack = new Stack<Link>();
 }
 public static bool IsChar(Link link)
 {
     return link != null && LinksToCharacters.ContainsKey(link);
 }
        private static void SetLetterCodes(Link letter, char lowerCaseCharacter, out Link lowerCase, out Link upperCase)
        {
            char upperCaseCharacter = char.ToUpper(lowerCaseCharacter);

            if (upperCaseCharacter != lowerCaseCharacter)
            {
                lowerCase = Link.Create(Net.LowerCase, Net.Of, letter);
                Link lowerCaseCharacterCode = Link.Create(Net.Code, Net.ThatIsRepresentedBy, LinkConverter.FromNumber(lowerCaseCharacter));

                Link.Create(lowerCase, Net.Has, lowerCaseCharacterCode);

                upperCase = Link.Create(Net.UpperCase, Net.Of, letter);
                Link upperCaseCharacterCode = Link.Create(Net.Code, Net.ThatIsRepresentedBy, LinkConverter.FromNumber(upperCaseCharacter));

                Link.Create(upperCase, Net.Has, upperCaseCharacterCode);
            }
            else
            {
                lowerCase = letter;
                upperCase = null;
                Link.Create(letter, Net.Has, Link.Create(Net.Code, Net.ThatIsRepresentedBy, LinkConverter.FromNumber(lowerCaseCharacter)));
            }
        }
        private static void RegisterExistingLetter(Link letter)
        {
            letter.WalkThroughReferersBySource(referer =>
                {
                    if (referer.Linker == Net.Has)
                    {
                        Link target = referer.Target;
                        if (target.Source == Net.Code && target.Linker == Net.ThatIsRepresentedBy)
                        {
                            char charCode = (char)LinkConverter.ToNumber(target.Target);

                            CharactersToLinks[charCode] = letter;
                            LinksToCharacters[letter] = charCode;
                        }
                    }
                });
        }
        private static void RegisterExistingCharacter(Link character)
        {
            if (character.Source == Net.Character && character.Linker == Net.ThatHas)
            {
                Link code = character.Target;
                if (code.Source == Net.Code && code.Linker == Net.ThatIsRepresentedBy)
                {
                    var charCode = (char)LinkConverter.ToNumber(code.Target);

                    CharactersToLinks[charCode] = character;
                    LinksToCharacters[character] = charCode;
                }
            }
        }
        private static void GenerateAlphabetBasis(ref Link alphabet, ref Link letterOfAlphabet, Link[] letters)
        {
            // Принцип, на примере латинского алфавита.
            //latin alphabet: alphabet that consists of a and b and c and ... and z.
            //a: letter of latin alphabet that is before b.
            //b: letter of latin alphabet that is between (a and c).
            //c: letter of latin alphabet that is between (b and e).
            //...
            //y: letter of latin alphabet that is between (x and z).
            //z: letter of latin alphabet that is after y.

            int firstLetterIndex = 0;

            for (int i = firstLetterIndex; i < letters.Length; i++)
            {
                letters[i] = Net.CreateThing();
            }

            int lastLetterIndex = letters.Length - 1;

            Link.Update(ref letters[firstLetterIndex], letterOfAlphabet, Net.ThatIsBefore, letters[firstLetterIndex + 1]);
            Link.Update(ref letters[lastLetterIndex], letterOfAlphabet, Net.ThatIsAfter, letters[lastLetterIndex - 1]);

            int secondLetterIndex = firstLetterIndex + 1;
            for (int i = secondLetterIndex; i < lastLetterIndex; i++)
            {
                Link.Update(ref letters[i], letterOfAlphabet, Net.ThatIsBetween, letters[i - 1] & letters[i + 1]);
            }

            Link.Update(ref alphabet, Net.Alphabet, Net.ThatConsistsOf, LinkConverter.FromList(letters));
        }
 public static bool WalkRight(Link sequence, Func<Link, bool> visit)
 {
     return (new StopableSequenceWalker(sequence, visit)).WalkFromLeftToRight();
 }
예제 #19
0
 public LinkModel(Link link)
     : this(link, new List<LinkModel>())
 {
 }
예제 #20
0
 public LinkModel(Link link, List<LinkModel> referersModels)
 {
     Link = link;
     ReferersModels = referersModels;
 }
예제 #21
0
        private static void CollectMatchingSequences(Link leftLink, int leftBound, Link[] middleLinks, Link rightLink, int rightBound, ref List<Link> results)
        {
            long leftLinkTotalReferers = leftLink.ReferersBySourceCount + leftLink.ReferersByTargetCount;
            long rightLinkTotalReferers = rightLink.ReferersBySourceCount + rightLink.ReferersByTargetCount;

            if (leftLinkTotalReferers <= rightLinkTotalReferers)
            {
                var nextLeftLink = middleLinks[leftBound];

                Link[] elements = GetRightElements(leftLink, nextLeftLink);
                if (leftBound <= rightBound)
                {
                    for (int i = elements.Length - 1; i >= 0; i--)
                    {
                        var element = elements[i];
                        if (element != null)
                        {
                            CollectMatchingSequences(element, leftBound + 1, middleLinks, rightLink, rightBound, ref results);
                        }
                    }
                }
                else
                {
                    for (int i = elements.Length - 1; i >= 0; i--)
                    {
                        var element = elements[i];
                        if (element != null)
                        {
                            results.Add(element);
                        }
                    }
                }
            }
            else
            {
                var nextRightLink = middleLinks[rightBound];

                Link[] elements = GetLeftElements(rightLink, nextRightLink);

                if (leftBound <= rightBound)
                {
                    for (int i = elements.Length - 1; i >= 0; i--)
                    {
                        var element = elements[i];
                        if (element != null)
                        {
                            CollectMatchingSequences(leftLink, leftBound, middleLinks, elements[i], rightBound - 1, ref results);
                        }
                    }
                }
                else
                {
                    for (int i = elements.Length - 1; i >= 0; i--)
                    {
                        var element = elements[i];
                        if (element != null)
                        {
                            results.Add(element);
                        }
                    }
                }
            }
        }
예제 #22
0
        public static bool TryStepRight(Link startLink, Link rightLink, Link[] result, int offset)
        {
            int added = 0;

            startLink.WalkThroughReferersBySource(couple =>
                {
                    if (couple.Linker == Net.And)
                    {
                        var coupleTarget = couple.Target;
                        if (coupleTarget == rightLink)
                        {
                            result[offset] = couple;
                            if (++added == 2)
                                return Link.Stop;
                        }
                        else if (coupleTarget.Linker == Net.And && coupleTarget.Source == rightLink)
                        {
                            result[offset + 1] = couple;
                            if (++added == 2)
                                return Link.Stop;
                        }
                    }

                    return Link.Continue;
                });

            return added > 0;
        }
예제 #23
0
        private static void Create()
        {
            #region Core

            if (!Link.TryGetMapped(NetMapping.IsA, out Net.IsA)
             || !Link.TryGetMapped(NetMapping.IsNotA, out Net.IsNotA)
             || !Link.TryGetMapped(NetMapping.Link, out Net.Link)
             || !Link.TryGetMapped(NetMapping.Thing, out Net.Thing))
            {
                // Наивная инициализация (Не является корректным объяснением).
                Net.IsA = Link.CreateMapped(Link.Itself, Link.Itself, Link.Itself, NetMapping.IsA); // Стоит переделать в "[x] is a member|instance|element of the class [y]"
                Net.IsNotA = Link.CreateMapped(Link.Itself, Link.Itself, Net.IsA, NetMapping.IsNotA);
                Net.Link = Link.CreateMapped(Link.Itself, Net.IsA, Link.Itself, NetMapping.Link);
                Net.Thing = Link.CreateMapped(Link.Itself, Net.IsNotA, Net.Link, NetMapping.Thing);

                Link.Update(ref Net.IsA, Net.IsA, Net.IsA, Net.Link); // Исключение, позволяющие завершить систему
            }

            #endregion

            Net.Of = CreateMappedLink(NetMapping.Of);
            Net.And = CreateMappedLink(NetMapping.And);
            Net.ThatConsistsOf = CreateMappedLink(NetMapping.ThatConsistsOf);
            Net.Has = CreateMappedLink(NetMapping.Has);
            Net.Contains = CreateMappedLink(NetMapping.Contains);
            Net.ContainedBy = CreateMappedLink(NetMapping.ContainedBy);

            Net.One = CreateMappedThing(NetMapping.One);
            Net.Zero = CreateMappedThing(NetMapping.Zero);

            Net.Sum = CreateMappedThing(NetMapping.Sum);
            Net.Character = CreateMappedThing(NetMapping.Character);
            Net.String = CreateMappedThing(NetMapping.String);
            Net.Name = Link.CreateMapped(Link.Itself, Net.IsA, Net.String, NetMapping.Name);

            Net.Set = CreateMappedThing(NetMapping.Set);
            Net.Group = CreateMappedThing(NetMapping.Group);

            Net.ParsedFrom = CreateMappedLink(NetMapping.ParsedFrom);
            Net.ThatIs = CreateMappedLink(NetMapping.ThatIs);
            Net.ThatIsBefore = CreateMappedLink(NetMapping.ThatIsBefore);
            Net.ThatIsAfter = CreateMappedLink(NetMapping.ThatIsAfter);
            Net.ThatIsBetween = CreateMappedLink(NetMapping.ThatIsBetween);
            Net.ThatIsRepresentedBy = CreateMappedLink(NetMapping.ThatIsRepresentedBy);
            Net.ThatHas = CreateMappedLink(NetMapping.ThatHas);

            Net.Text = CreateMappedThing(NetMapping.Text);
            Net.Path = CreateMappedThing(NetMapping.Path);
            Net.Content = CreateMappedThing(NetMapping.Content);
            Net.Empty = CreateMappedThing(NetMapping.Empty);
            Net.EmptyContent = Link.CreateMapped(Net.Content, Net.ThatIs, Net.Empty, NetMapping.EmptyContent);
            Net.Alphabet = CreateMappedThing(NetMapping.Alphabet);
            Net.Letter = Link.CreateMapped(Link.Itself, Net.IsA, Net.Character, NetMapping.Letter);
            Net.Case = CreateMappedThing(NetMapping.Case);
            Net.Upper = CreateMappedThing(NetMapping.Upper);
            Net.UpperCase = Link.CreateMapped(Net.Case, Net.ThatIs, Net.Upper, NetMapping.UpperCase);
            Net.Lower = CreateMappedThing(NetMapping.Lower);
            Net.LowerCase = Link.CreateMapped(Net.Case, Net.ThatIs, Net.Lower, NetMapping.LowerCase);
            Net.Code = CreateMappedThing(NetMapping.Code);

            SetNames();
        }
예제 #24
0
        public static Link[] GetRightElements(Link startLink, Link rightLink)
        {
            var result = new Link[4];

            TryStepRight(startLink, rightLink, result, 0);

            startLink.WalkThroughReferersByTarget(couple =>
                {
                    if (couple.Linker == Net.And)
                        if (TryStepRight(couple, rightLink, result, 2))
                            return Link.Stop;

                    return Link.Continue;
                });

            return result;
        }
        private static void CreateAlphabet(char[] lettersCharacters, string alphabetName, CharacterMapping mapping)
        {
            Link alphabet;
            if (Link.TryGetMapped(mapping, out alphabet))
            {
                Link letters = alphabet.Target;

                letters.WalkThroughSequence(letter =>
                {
                    Link lowerCaseLetter = Link.Search(Net.LowerCase, Net.Of, letter);
                    Link upperCaseLetter = Link.Search(Net.UpperCase, Net.Of, letter);

                    if (lowerCaseLetter != null && upperCaseLetter != null)
                    {
                        RegisterExistingLetter(lowerCaseLetter);
                        RegisterExistingLetter(upperCaseLetter);
                    }
                    else
                    {
                        RegisterExistingLetter(letter);
                    }
                });
            }
            else
            {
                alphabet = Net.CreateMappedThing(mapping);
                Link letterOfAlphabet = Link.Create(Net.Letter, Net.Of, alphabet);
                Link[] lettersLinks = new Link[lettersCharacters.Length];

                GenerateAlphabetBasis(ref alphabet, ref letterOfAlphabet, lettersLinks);

                for (int i = 0; i < lettersCharacters.Length; i++)
                {
                    char lowerCaseCharacter = lettersCharacters[i];
                    Link lowerCaseLink, upperCaseLink;
                    SetLetterCodes(lettersLinks[i], lowerCaseCharacter, out lowerCaseLink, out upperCaseLink);

                    CharactersToLinks[lowerCaseCharacter] = lowerCaseLink;
                    LinksToCharacters[lowerCaseLink] = lowerCaseCharacter;

                    if (upperCaseLink != null)
                    {
                        char upperCaseCharacter = char.ToUpper(lowerCaseCharacter);
                        CharactersToLinks[upperCaseCharacter] = upperCaseLink;
                        LinksToCharacters[upperCaseLink] = upperCaseCharacter;
                    }
                }

                alphabet.SetName(alphabetName);

                for (int i = 0; i < lettersCharacters.Length; i++)
                {
                    char lowerCaseCharacter = lettersCharacters[i];
                    char upperCaseCharacter = Char.ToUpper(lowerCaseCharacter);

                    if (lowerCaseCharacter != upperCaseCharacter)
                    {
                        lettersLinks[i].SetName("{" + upperCaseCharacter + " " + lowerCaseCharacter + "}");
                    }
                    else
                    {
                        lettersLinks[i].SetName("{" + lowerCaseCharacter + "}");
                    }
                }
            }
        }
 public StopableSequenceWalker(Link sequence, Func<Link, bool> visit)
 {
     _root = sequence;
     _visit = visit;
     _stack = new Stack<Link>();
 }