예제 #1
0
        public static RandomNode CopyRandomList(RandomNode head)
        {
            RandomNode current = head;


            while (current != null)
            {
                RandomNode clone = new RandomNode(current.val, null, null);
                clone.next   = current.next;
                current.next = clone;
                current      = clone.next;
            }
            current = head;
            while (current != null)
            {
                current.next.random = current.random.next;
                current             = current.next.next;
            }
            current = head;
            RandomNode newHead = head.next;

            while (current != null)
            {
                RandomNode temp = current.next;

                current.next = temp.next;
                if (temp.next != null)
                {
                    temp.next = temp.next.next;
                }
                current = current.next;
            }
            return(newHead);
        }
예제 #2
0
    private bool AddEdgeBetween(RandomNode node1, RandomNode node2)
    {
        Vector3 n1 = node1.transform.position;
        Vector3 n2 = node2.transform.position;

        // Find center between nodes
        Vector3 centerPos = new Vector3(n1.x + n2.x, 0f, n1.z + n2.z) / 2;

        // Find angle
        float angle = -Mathf.Atan2(n2.z - n1.z, n2.x - n1.x) * Mathf.Rad2Deg;

        //Debug.Log(node1.NodeType + " connecting to " + node2.NodeType + ", angle=" + angle + ", dist=" + UtilGraph.DistanceBetweenNodes(node1.transform, node2.transform));

        // Initialize edge
        CreateEdge(node1, node2, centerPos, angle);

        // Check if any overlaps occured
        //Debug.Log("Test: " + edge.CollisionOccured);
        //if (edge.CollisionOccured)
        //{
        //    Debug.Log(">>>>>>>>>>>>>>>>> Destroying edge!!");
        //    Destroy(edge.gameObject);
        //    return false;
        //}
        return(true);
    }
예제 #3
0
        public RandomNode CopyRandomList(RandomNode head)
        {
            var dummyHead    = new RandomNode(0);
            var originalHead = head;
            var current      = dummyHead;
            var kv           = new Dictionary <RandomNode, RandomNode>();

            while (head != null)
            {
                current.next = new RandomNode(head.val);
                current      = current.next;
                kv.Add(head, current);
                head = head.next;
            }

            current = dummyHead.next;
            while (originalHead != null)
            {
                if (originalHead.random != null)
                {
                    current.random = kv.GetValueOrDefault(originalHead.random, null);
                }
                originalHead = originalHead.next;
                current      = current.next;
            }

            return(dummyHead.next);
        }
예제 #4
0
    public Node Create(NodeType type)
    {
        Node node = null;

        switch (type)
        {
        case NodeType.Root:
            node = new RootNode();
            break;

        case NodeType.Action:
            node = new ActionNode();
            break;

        case NodeType.Sequencer:
            node = new SequencerNode();
            break;

        case NodeType.Selector:
            node = new SelectorNode();
            break;

        case NodeType.Random:
            node = new RandomNode();
            break;

        case NodeType.RandomSelector:
            node = new RandomSelectorNode();
            break;

        case NodeType.RandomSequencer:
            node = new RandomSequencerNode();
            break;

        case NodeType.Decorator:
            node = new DecoratorNode();
            break;

        case NodeType.Condition:
            node = new ConditionNode();
            break;

        case NodeType.ConditionWhile:
            node = new ConditionWhileNode();
            break;

        default:
            Debug.Assert(false, "未定義のノードタイプ");
            break;
        }

        if (node != null)
        {
            node.Init(idSeed);
            Register(idSeed, node);
            idSeed += 1;
        }

        return(node);
    }
예제 #5
0
    NodeState SelectRandom()
    {
        totalSum = 0f;
        foreach (RandomNode node in nodes)
        {
            totalSum += node.percentage;
        }
        foreach (RandomNode node in nodes)
        {
            float rand = Random.Range(0, totalSum);
            currentNode = node;
            randSum     = currentNode.percentage;

            if (rand <= randSum)
            {
                currentState = currentNode.node.Evaluate();
                if (currentState == NodeState.FAIL)
                {
                    nodes.Remove(node);
                    return(SelectRandom());
                }
                return(currentState);
            }
            totalSum -= currentNode.percentage;
        }
        return(NodeState.FAIL);
    }
예제 #6
0
    //private Dictionary<RandomNode, List<RandomNode>>
    public override void CreateEdges(string mode)
    {
        // Dictionary for counting number of times nodeID has been used - Dict<nodeID, counter>
        Dictionary <int, int> nodeUsedCounter = new Dictionary <int, int>();

        for (int x = 0; x < nodes.Count; x++)
        {
            nodeUsedCounter.Add(nodes[x].NodeID, 0);
        }

        int edgesAdded = 0, overLapCheck = 3;

        while (edgesAdded < numberOfEdges || overLapCheck < 0)
        {
            // Find least used node
            int leastUsedNode = 0;
            int value         = UtilGraph.INF;
            foreach (var node in nodeUsedCounter)
            {
                if (node.Value < value)
                {
                    value         = node.Value;
                    leastUsedNode = node.Key;
                }
            }
            RandomNode node1 = nodes[leastUsedNode];

            // Find a random node
            RandomNode node2       = nodes[RandomRangeExcept(0, numberOfNodes, leastUsedNode)];
            bool       extraChance = true;
            while (node1.IsNeighborWith(node2) && extraChance)
            {
                node2 = nodes[RandomRangeExcept(0, numberOfNodes, leastUsedNode)];

                if (node1.IsNeighborWith(node2))
                {
                    extraChance = false;
                }
            }

            if (!extraChance)
            {
                break;
            }

            // Add edge between nodes (if no collisions with other edges or nodes)
            if (AddEdgeBetween(node1, node2))
            {
                // Update frequency of these nodes
                nodeUsedCounter[node1.NodeID] += 1;
                nodeUsedCounter[node2.NodeID] += 1;
                edgesAdded++;
            }
            else
            {
                overLapCheck--;
            }
        }
    }
예제 #7
0
 public void AddNeighbor(RandomNode node)
 {
     if (!neighbors.Contains(node))
     {
         neighbors.Add(node);
         node.AddNeighbor(this);
     }
 }
예제 #8
0
 public void RemoveNeighbor(RandomNode node)
 {
     if (neighbors.Contains(node))
     {
         neighbors.Remove(node);
         node.RemoveNeighbor(this);
     }
 }
예제 #9
0
    //TODO use NodeType to categorize Types.
    public static BaseNode CreateNode(ActionNodeData aData)
    {
        if (aData.NodeType == null)
        {
            Debug.LogError("Type not set");
            return(null);
        }

        aData.GUID          = string.IsNullOrEmpty(aData.GUID) ? Guid.NewGuid().ToString() : aData.GUID;
        aData.OutputPortIDs = aData.OutputPortIDs ?? new List <string>();

        //The copy prevent the node to modify the list in the ActionNodeData
        List <string> copy = new List <string>();

        foreach (var outputPort in aData.OutputPortIDs)
        {
            copy.Add(outputPort);
        }

        BaseNode node;
        Type     type = Type.GetType(aData.NodeType);

        if (type == typeof(ChangeSceneNode))
        {
            node = ChangeSceneNode.Create("Change Scene", aData.Position, aData.GUID, copy);
        }
        else if (type == typeof(StartNode))
        {
            node = StartNode.Create("Start Node", aData.Position, aData.GUID, copy);
        }
        else if (type == typeof(ConditionalNode))
        {
            node = ConditionalNode.Create("Conditional", aData.Position, aData.GUID, copy);
        }
        else if (type == typeof(MultiNode))
        {
            node = MultiNode.Create("Multi Output", aData.Position, aData.GUID, copy);
        }
        else if (type == typeof(ExitNode))
        {
            node = ExitNode.Create("Exit Node", aData.Position, aData.GUID, copy);
        }
        else if (type == typeof(RandomNode))
        {
            node = RandomNode.Create("Random Node", aData.Position, aData.GUID, copy);
        }
        else if (type == typeof(TakeObjectNode))
        {
            node = TakeObjectNode.Create("Take Object", aData.Position, aData.GUID, copy);
        }
        else
        {
            throw new NotImplementedException($"Node type {type} not handled in NodeFactory");
        }

        node?.SetSerializedScript(aData.SerializedScript);
        return(node);
    }
예제 #10
0
        protected override void onGUI()
        {
            RandomNode myTarget = (RandomNode)target;

            EditorGUIExtension.SimpleBox("", 5, "", delegate()
            {
                var min = myTarget.Variables.GetByName("Min");
                var max = myTarget.Variables.GetByName("Max");

                VariableEditor.VariableField(min, null, true);
                VariableEditor.VariableField(max, null, true);
            });

            EditorGUILayout.Space();
        }
예제 #11
0
        public DGRandNode(RandomNode rand, StateNode state)
            : base(rand, state)
        {
            if (rand == null)
            {
                throw new ArgumentNullException("rand");
            }
            this.mRandomNode = rand;
            this.mSlices     = new SliceList(this);

            this.mSliceAnchors = new AnchorPoint[0];
            this.mSliceStrings = new string[0];
            this.mSliceCount   = 0;
            this.mMGH          = 7;

            this.UpdateVisualization();
        }
    private RandomNode CopyList(RandomNode head)
    {
        if (head == null)
        {
            return(null);
        }

        RandomNode cur  = head;
        RandomNode next = null;

        while (cur != null)
        {
            next          = cur.next;
            cur.next      = new RandomNode(cur.value);
            cur.next.next = next;
            cur           = next;
        }

        cur = head;
        RandomNode copyNode = null;

        while (cur != null)
        {
            next          = cur.next.next;
            cur.next.rand = cur.rand == null ? null : cur.rand.next;
            cur           = next;
        }

        RandomNode res = head.next;

        cur = head;

        while (cur != null)
        {
            next          = cur.next.next;
            copyNode      = cur.next;
            cur.next      = next;
            copyNode.next = next != null ? next.next : null;
            cur           = next;
        }

        return(res);
    }
예제 #13
0
            public RandomNode CopyRandomList(RandomNode head)
            {
                if (head == null)
                {
                    return(null);
                }

                RandomNode current = head;

                while (current != null)
                {
                    RandomNode next = current.next;
                    current.next = new RandomNode(current.val, next, null);
                    current      = next;
                }

                current = head;
                while (current != null)
                {
                    if (current.random != null)
                    {
                        current.next.random = current.random.next;
                    }
                    current = current.next.next;
                }

                current = head;
                RandomNode copyHead = head.next;

                while (current != null)
                {
                    RandomNode after = current.next.next;
                    RandomNode copy  = current.next;
                    current.next = after;
                    if (after != null)
                    {
                        copy.next = after.next;
                    }
                    current = after;
                }
                return(copyHead);
            }
예제 #14
0
 /// <summary>
 /// clone
 /// </summary>
 /// <returns></returns>
 public IBehaviourNode Clone()
 {
     var behaviourNode = new RandomNode();
     base.CopyToCompositeNode(behaviourNode);
     return behaviourNode;
 }
예제 #15
0
 public RandomNode(int _val)
 {
     val = _val;
     next = null;
     random = null;
 }
예제 #16
0
    // Start is called before the first frame update
    public void ReadTree(TextAsset textAsset)
    {
        dialogTree = new Dictionary <string, DialogNode>();
        dialogFile = textAsset;

        dialog = new JSONObject(dialogFile.text);
        dialog = dialog[0]["nodes"];

        //parses the json file based on node types
        foreach (JSONObject n in dialog.list)
        {
            switch (n[nodeType].str)
            {
            case "start":
                DialogNode a = new DialogNode(n[next].str, DialogNode.NodeType.START);
                dialogTree.Add(n[nodeName].str, a);
                break;

            case "show_message":

                if (n[text][lang].str.Contains("\\n"))
                {
                    n[text][lang].str = n[text][lang].str.Replace("\\n", "\n");
                }

                if (n.keys.Contains("choices"))
                {
                    ChoiceNode c = new ChoiceNode(n[speaker][0].str, n[text][lang].str, n[choices]);
                    dialogTree.Add(n[nodeName].str, c);
                }
                else
                {
                    TextBoxNode tb = new TextBoxNode(n[next].str, n[speaker][0].str, n[text][lang].str);
                    dialogTree.Add(n[nodeName].str, tb);
                }
                break;

            case "chance_branch":
            case "random_branch":
                if (n.keys.Contains("chance_1"))
                {
                    RandomNode cb = new RandomNode(n[branch], (int)n[chance].i);
                    dialogTree.Add(n[nodeName].str, cb);
                }
                else
                {
                    RandomNode rb = new RandomNode((int)n[poss].i, n[branch]);
                    dialogTree.Add(n[nodeName].str, rb);
                }
                break;

            case "execute":
                string   function = n[text].str;
                string[] inputs   = function.Split(',');

                CodeNode cn = new CodeNode(n[next].str, Int32.Parse(inputs[0]), inputs[1], inputs[2]);
                dialogTree.Add(n[nodeName].str, cn);

                break;

            default:
                DialogNode d = new DialogNode(n[next].str, DialogNode.NodeType.NULL);
                dialogTree.Add(n[nodeName].str, d);
                break;
            }
        }
    }
 private Random <TContext> MapRandomNode(RandomNode node)
 {
     return(new Random <TContext>(node.Name, Map(node.Child), node.Threshold, node.RandomProvider));
 }
예제 #18
0
    void GenerateBehaviors()
    {
        Animator a = GetAnimator();

        ////////////////////////////////// Movement //////////////////////////////////

        EvadeNode     evade     = new EvadeNode(this.rB, speed, 0.4f, 25);
        IsBlockedNode isBlocked = new IsBlockedNode(transform, evade, 1, 1);
        MoveNode      move      = new MoveNode(rB, target, speed, atkRange);

        SequenceNode evading = new SequenceNode(new List <Node>()
        {
            isBlocked, evade
        });
        SelectorNode movement = new SelectorNode(new List <Node>()
        {
            evading, move
        });

        ////////////////////////////////// Death //////////////////////////////////

        HealthCheckNode         isDead              = new HealthCheckNode(this, 0, true);
        ClampSuccessNode        isDeadClamped       = new ClampSuccessNode(isDead);
        AnimationNode           deathAnim           = new AnimationNode(a, "Die");
        OnAnimationCompleteNode onDeathAnimComplete = new OnAnimationCompleteNode(a, "Die");
        DestroyNode             destroy             = new DestroyNode(this.gameObject);

        SequenceNode death = new SequenceNode(new List <Node> {
            isDeadClamped, deathAnim, onDeathAnimComplete, destroy
        });

        ////////////////////////////////// Cover //////////////////////////////////

        HealthCheckNode   isLow         = new HealthCheckNode(this, consideredLowHP, true);
        SoundNode         hurtSFX       = new SoundNode(Sound.SeaMonsterHurt);
        RandomNode        chanceHurtSFX = new RandomNode(hurtSFX, 0.4f);
        ColorFlashNode    hurtFlash     = new ColorFlashNode(GetMaterial(), Color.red, 3, 1);
        RecoverHealthNode hpRecover     = new RecoverHealthNode(this, hpRecoveryMultiplier);
        FindCover         findCover     = new FindCover(this, target, 10);

        SequenceNode hurting = new SequenceNode(new List <Node>()
        {
            chanceHurtSFX, hurtFlash
        });
        SequenceNode recovering = new SequenceNode(new List <Node>()
        {
            hpRecover, hurting
        });
        SequenceNode covering = new SequenceNode(new List <Node>()
        {
            findCover, movement
        });
        ParallelNode recoveringAndCovering = new ParallelNode(new List <Node>()
        {
            recovering, covering
        }, 2);

        SequenceNode cover = new SequenceNode(new List <Node>()
        {
            isLow, recoveringAndCovering
        });

        ////////////////////////////////// Attack //////////////////////////////////

        // Condition To Start Attack Sequence
        IsInRangeNode isInATKRange = new IsInRangeNode(atkRange, transform, target);

        // Attack Sequence
        AnimationNode readyUpAnim = new AnimationNode(a, "Aim");
        LookNode      aim         = new LookNode(rB, target, 1, 12, 7);
        AnimationNode strikeAnim  = new AnimationNode(a, "Fire");
        TimerNode     atkTimer    = new TimerNode(1);

        // Wrapping Nodes
        SequenceNode attackPattern = new SequenceNode(new List <Node>()
        {
            readyUpAnim, aim, strikeAnim, atkTimer
        });
        ResetOnStateNode resetATK  = new ResetOnStateNode(attackPattern, NodeState.SUCCESS);
        SequenceNode     attacking = new SequenceNode(new List <Node>()
        {
            isInATKRange, resetATK
        });
        SelectorNode attack = new SelectorNode(new List <Node>()
        {
            attacking, movement
        });


        ////////////////////////////////// Patrol //////////////////////////////////

        PatrolNode   patrolMove     = new PatrolNode(rB, Mathf.RoundToInt(speed * 0.7f), 0.5f, 6, 20, 1.5f, 4);
        SelectorNode evadeAndPatrol = new SelectorNode(new List <Node>()
        {
            evading, patrolMove
        });

        SpotTargetNode spotTarget = new SpotTargetNode(transform, 40, 80, LayerMask.NameToLayer("Target"), LayerMask.NameToLayer("Enemy"));

        FlagNode      flag          = new FlagNode(NodeState.SUCCESS, NodeState.FAILURE);
        FlagActivator flagActivator = new FlagActivator(flag);

        SequenceNode spotAndStop = new SequenceNode(new List <Node>()
        {
            spotTarget, flagActivator
        });

        SelectorNode patroling = new SelectorNode(new List <Node>()
        {
            spotAndStop, evadeAndPatrol
        });
        SequenceNode patrol = new SequenceNode(new List <Node>()
        {
            flag, patroling
        });

        ////////////////////////////////// Top Node //////////////////////////////////

        topNode = new Tree(new SelectorNode(new List <Node>()
        {
            death, cover, patrol, attack
        }));

        BehaviorTreeManager.AddTree(topNode);
    }
예제 #19
0
 public RandomNode(int _val, RandomNode _next, RandomNode _random)
 {
     val    = _val;
     next   = _next;
     random = _random;
 }
예제 #20
0
 public RandomNode(int data)
 {
     this.value = data;
     next       = null;
 }
예제 #21
0
 public RandomNode(int data, RandomNode next, RandomNode rand)
 {
     this.value = data;
     this.next  = next;
     this.rand  = rand;
 }
예제 #22
0
        private DGNode InitDGN(DGNode src, DecisionGraphNode dgn)
        {
            int    i;
            DGNode dst = null;

            for (i = this.mDGraph.NodeCount - 1; i >= 0; i--)
            {
                dst = this.mDGraph.NodeAt(i);
                if (dst.DGN == dgn)
                {
                    break;
                }
            }
            if (i < 0)
            {
                int                 j;
                DGEdge              edge;
                AnchorPoint         ap;
                DecisionGraphNode[] dgns;
                DGMulticastNode     dgmcn = null;
                switch (dgn.ChunkType)
                {
                case NextStateNode.ResourceType:
                    NextStateNode nsn = dgn as NextStateNode;
                    dst = new DGSnSnNode(nsn, this);
                    this.mDGraph.AddNode(dst);
                    dst.SetParent(this);
                    break;

                case RandomNode.ResourceType:
                    RandomNode rand = dgn as RandomNode;
                    DGRandNode dgrn = new DGRandNode(rand, this);
                    this.mDGraph.AddNode(dgrn);
                    dgrn.SetParent(this);
                    List <RandomNode.Slice> slices = rand.Slices;
                    if (slices.Count > 0)
                    {
                        for (i = 0; i < slices.Count; i++)
                        {
                            ap   = dgrn.GetSliceAnchor(i);
                            dgns = slices[i].Targets.ToArray();
                            for (j = 0; j < dgns.Length; j++)
                            {
                                dst  = this.InitDGN(dgrn, dgns[j]);
                                edge = new DGEdge(dgrn, dst, false);
                                ap.Edges.Add(edge);
                                dst.EntryAnchor.Edges.Add(edge);
                                this.mDGraph.AddEdge(edge);
                                edge.SetParent(this);
                            }
                        }
                    }
                    dst = dgrn;
                    break;

                case SelectOnDestinationNode.ResourceType:
                    SelectOnDestinationNode sodn
                        = dgn as SelectOnDestinationNode;
                    DGSoDnNode dgsodn
                        = new DGSoDnNode(sodn, this);
                    this.mDGraph.AddNode(dgsodn);
                    dgsodn.SetParent(this);
                    if (sodn.CaseCount > 0)
                    {
                        SelectOnDestinationNode.Case[] cases = sodn.Cases;
                        for (i = 0; i < cases.Length; i++)
                        {
                            ap   = dgsodn.GetCaseAnchorAt(i);
                            dgns = cases[i].Targets;
                            for (j = 0; j < dgns.Length; j++)
                            {
                                dst  = this.InitDGN(dgsodn, dgns[j]);
                                edge = new DGEdge(dgsodn, dst, false);
                                ap.Edges.Add(edge);
                                dst.EntryAnchor.Edges.Add(edge);
                                this.mDGraph.AddEdge(edge);
                                edge.SetParent(this);
                            }
                        }
                    }
                    dst = dgsodn;
                    break;

                case SelectOnParameterNode.ResourceType:
                    SelectOnParameterNode sopn
                        = dgn as SelectOnParameterNode;
                    DGSoPnNode dgsopn
                        = new DGSoPnNode(sopn, this);
                    this.mDGraph.AddNode(dgsopn);
                    dgsopn.SetParent(this);
                    if (sopn.CaseCount > 0)
                    {
                        SelectOnParameterNode.Case[] cases = sopn.Cases;
                        for (i = 0; i < cases.Length; i++)
                        {
                            ap   = dgsopn.GetCaseAnchorAt(i);
                            dgns = cases[i].Targets;
                            for (j = 0; j < dgns.Length; j++)
                            {
                                dst  = this.InitDGN(dgsopn, dgns[j]);
                                edge = new DGEdge(dgsopn, dst, false);
                                ap.Edges.Add(edge);
                                dst.EntryAnchor.Edges.Add(edge);
                                this.mDGraph.AddEdge(edge);
                                edge.SetParent(this);
                            }
                        }
                    }
                    dst = dgsopn;
                    break;

                case CreatePropNode.ResourceType:
                    CreatePropNode cpn   = dgn as CreatePropNode;
                    DGPropNode     dgcpn = new DGPropNode(cpn, this);
                    this.mDGraph.AddNode(dgcpn);
                    dgcpn.SetParent(this);
                    dgmcn = dgcpn;
                    break;

                case ActorOperationNode.ResourceType:
                    ActorOperationNode aon   = dgn as ActorOperationNode;
                    DGAcOpNode         dgaon = new DGAcOpNode(aon, this);
                    this.mDGraph.AddNode(dgaon);
                    dgaon.SetParent(this);
                    dgmcn = dgaon;
                    break;

                case StopAnimationNode.ResourceType:
                    StopAnimationNode san   = dgn as StopAnimationNode;
                    DGStopNode        dgsan = new DGStopNode(san, this);
                    this.mDGraph.AddNode(dgsan);
                    dgsan.SetParent(this);
                    dgmcn = dgsan;
                    break;

                case PlayAnimationNode.ResourceType:
                    PlayAnimationNode pan   = dgn as PlayAnimationNode;
                    DGPlayNode        dgpan = new DGPlayNode(pan, this);
                    this.mDGraph.AddNode(dgpan);
                    dgpan.SetParent(this);
                    dgmcn = dgpan;
                    break;
                }
                if (dgmcn != null)
                {
                    MulticastDecisionGraphNode mcn
                        = dgn as MulticastDecisionGraphNode;
                    if (mcn.TargetCount > 0)
                    {
                        ap   = dgmcn.TargetAnchor;
                        dgns = mcn.Targets;
                        for (i = 0; i < dgns.Length; i++)
                        {
                            dst  = this.InitDGN(dgmcn, dgns[i]);
                            edge = new DGEdge(dgmcn, dst, false);
                            ap.Edges.Add(edge);
                            dst.EntryAnchor.Edges.Add(edge);
                            this.mDGraph.AddEdge(edge);
                            edge.SetParent(this);
                        }
                    }
                    dst = dgmcn;
                }
            }
            return(dst);
        }
예제 #23
0
        public static void Main(string[] args)
        {
            //create Stack
            var stk = StackHelper.Create(new int[] { 10, 11, 12, 13, 14, 15 });

            Console.Write("Create list(10, 11, 12, 13, 14, 15) as Stack :");
            StackHelper.PrintAll(stk);
            Console.WriteLine("\n");

            //Create Queue
            var q = QueueHelper.Create(new int[] { 10, 11, 12, 13, 14, 15, 16 });

            Console.Write("Create list(10, 11, 12, 13, 14, 15, 16 ) as Queue :");
            QueueHelper.PrintAll(q);
            Console.WriteLine("\n");

            q = QueueHelper.Create(new int[] { 1, 2, 3, 4 });
            ReorderList.GetReorderList(q.Head);

            //Check list is circular.
            bool isCircular = CheckListIsCircular.Check(q.Head);

            Console.Write("List(10, 11, 12, 13, 14, 15, 16 ) is Circular?:" + isCircular.ToString());
            Console.WriteLine("\n");

            //Reverse List
            var reversedQ = ReverseList.Reverse(q.Head);

            Console.Write("Reversed List( 10->11->12->13->14-> 15->16) Values:");
            QueueHelper.PrintAll(reversedQ);
            Console.WriteLine("\n");

            //SwapNode
            q = QueueHelper.Create(new int[] { 10, 11, 12, 13, 14, 15, 16 });
            var swapedList = SwapPairs.SwapNodes(q.Head);

            Console.Write("Swaped List( 10->11->12->13->14->15->16 ) Values in Pairs:");
            QueueHelper.PrintAll(swapedList);
            Console.WriteLine("\n");

            //Sort Based on actual Value
            q = QueueHelper.Create(new int[] { 1, 2, 3, -4, -5, -6, -10 });
            var actualValueSorted = SortBasedOnAbsoluteValue.Sort1(q.Head);

            Console.Write("Sort Based on Actual values in List(1-> 2->3->-4->-5-> -6-> -10):");
            QueueHelper.PrintAll(actualValueSorted);
            Console.WriteLine("\n");

            //Sort Based on actual Value
            q = QueueHelper.Create(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            int k          = 3;
            var altRevList = AlternativeKNodes.ReverseAlterNativeKNodes(q.Head, k);

            Console.Write($"Reversed Alternative {k} Nodes in list(1->2->3->4->5->6->7->8->9->10 ):");
            QueueHelper.PrintAll(altRevList);
            Console.WriteLine("\n");

            //Reverse List
            q = QueueHelper.Create(new int[] { 10, 11, 12, 13, 14, 15, 16 });
            var reversedRecurQ = ReverseRecursively.Reverse(q.Head);

            Console.Write("Reverse List(10->11->12->13->14->15->16) Values Recursively:");
            QueueHelper.PrintAll(reversedRecurQ);
            Console.WriteLine("\n");

            //Merge Two Sorted Queues
            var q1         = QueueHelper.Create(new int[] { 1, 5 });
            var q2         = QueueHelper.Create(new int[] { 2, 3, 4 });
            var mergedList = MergeKSortedLists.MergeRecursive(q1.Head, q2.Head);

            Console.Write("Merge list1(1-> 5)  and list2( 2->3->4) :");
            QueueHelper.PrintAll(mergedList);
            Console.WriteLine("\n");

            //List Iterator
            var listIterator = new ListIterator();

            Console.Write("Write List in Order:");
            while (listIterator.HasAny())
            {
                Console.Write(listIterator.Next() + " ");
            }
            Console.WriteLine("\n");

            //deleting the middle node
            q = QueueHelper.Create(new int[] { 10, 11, 12, 13, 14, 15, 16 });
            var updatedList = DeleteNodeInTheMiddle.DeleteMiddleNode(q.Head);

            Console.Write("List(10-> 11->12->13->14->15->16) after deleting the middle node:");
            QueueHelper.PrintAll(updatedList);
            Console.WriteLine("\n");

            //NtheElement from the Last
            q = QueueHelper.Create(new int[] { 10, 11, 12, 13, 14, 15, 16 });
            int n       = 5;
            var nthNode = NthElementFromLast.FindNthElementFromLast(q.Head, n);

            Console.Write(n + "th element from Last(10->11->12->13->14->15->16):" + nthNode.Val);
            Console.WriteLine("\n");

            //Double linkedlist
            var doubleList = new DoubleList();

            doubleList.InsertNode(10);
            doubleList.InsertNode(11);
            doubleList.InsertNode(12);
            doubleList.InsertNode(13);
            doubleList.InsertNode(14);
            doubleList.PrintList();
            Console.WriteLine("\n");

            //Circular linkedlist

            var circularList = new CircularList();

            circularList.SetLoopBackVal(20);

            circularList.Insert(10);
            circularList.Insert(20);
            circularList.Insert(30);
            circularList.Insert(40);
            circularList.Insert(50);
            circularList.SetLoopBack();

            //collition node
            Node collitionNode = circularList.GetCollitionNode();

            Console.Write("Colliding Node in a circular list(10->20->30->40->50->20):" + collitionNode.Val);
            Console.WriteLine("\n");

            //check a string is palindrum
            Palindrum palindrum = new Palindrum();
            bool      result    = palindrum.Check("MALAYALAM");

            Console.Write("Is 'MALAYALAM' a Palindrum word:" + result.ToString());
            Console.WriteLine("\n");

            //TBD
            //partition based on a pivot
            q = QueueHelper.Create(new int[] { 1, 3, 2, 9, 4, 7, 11, 5 });
            int pivot         = 4;
            var partitionList = PartitionBasedOnPivot.Partition(q.Head, pivot);

            Console.Write($"Partition  List( 1->3->2->9->4->7->11->5 ) based on Pivot({pivot}) :");
            QueueHelper.PrintAll(partitionList);
            Console.WriteLine("\n");

            //Number addition
            LQueue num1 = QueueHelper.Create(new int[] { 8, 7 });
            LQueue num2 = QueueHelper.Create(new int[] { 8, 9 });
            var    sum  = NumberListAddition.AddNumList(num1.Head, num2.Head);

            Console.Write("List Addition List1(8->7) and List2(8->9):");
            QueueHelper.PrintAll(sum);
            Console.WriteLine("\n");

            var sum1 = NumberListAddition.AddNumListRecursion(num1.Head, num2.Head);

            Console.Write("List Addition List1(8->7) and List2(8->9) Recursively:");
            QueueHelper.PrintAll(sum);
            Console.WriteLine("\n");

            //RandomNode r1 = new RandomNode();
            //r1.val = 1;
            //RandomNode r2 = new RandomNode();
            //r2.val = 2;
            //RandomNode r3 = new RandomNode();
            //r3.val = 3;
            //RandomNode r4 = new RandomNode();
            //r4.val = 4;
            //RandomNode r5 = new RandomNode();
            //r5.val = 5;
            //r1.next = r2;
            //r2.next = r3;
            //r3.next = r4;
            //r4.next = r5;
            //r5.next = null;
            //r1.random = r4;
            //r2.random = r1;
            //r3.random = r5;
            //r4.random = r2;
            //r5.random = r3;

            RandomNode r1 = new RandomNode();

            r1.val = 1;
            RandomNode r2 = new RandomNode();

            r2.val    = 2;
            r1.next   = r2;
            r2.next   = null;
            r1.random = r2;
            r2.random = r2;
            var clone = CloneListWithRandomPtr.CopyRandomList(r1);

            q = QueueHelper.Create(new int[] { 1, 2, 3, 4, 5, 6, 7 });
            var oddEvenList = OddEvenLinkedList.GetOddEvenList(q.Head);

            LRUCache lru = new LRUCache(4);

            lru.put(1, 1);
            lru.put(2, 2);
            lru.put(3, 3);
            lru.put(4, 4);
            lru.put(4, 5);
            var s1     = q = QueueHelper.Create(new int[] { 1, 3, 5 });
            var s2     = q = QueueHelper.Create(new int[] { 2, 4 });
            var merged = MergeKSortedLists.Merge(s1.Head, s2.Head);

            Console.ReadLine();
        }
예제 #24
0
 public RandomNode(int _val)
 {
     this.val    = _val;
     this.next   = null;
     this.random = null;
 }
예제 #25
0
	void OnEnable()
	{
		rn = target as RandomNode;
		rn.GetChildNodes();
	}
예제 #26
0
 public bool IsNeighborWith(RandomNode node)
 {
     return(neighbors.Contains(node));
 }