コード例 #1
0
ファイル: CircularQueueTest.cs プロジェクト: havok/ngenerics
        public void RandomEnqueueDequeue()
        {
            var circularQueue = new CircularQueue<int>(66);

            var currentItems = new List<int>();
            var rand = new Random(Convert.ToInt32(DateTime.Now.Ticks % Int32.MaxValue));

            for (var i = 0; i < 513; i++)
            {
                var number = rand.Next(10000);

                if (number % 2 == 0)
                {
                    circularQueue.Enqueue(number);
                    currentItems.Add(number);
                }
                else
                {
                    if (circularQueue.Count > 0)
                    {
                        Assert.IsTrue(currentItems.Remove(circularQueue.Dequeue()));
                    }
                }

                foreach (var item in currentItems)
                {
                    Assert.IsTrue(circularQueue.Contains(item));
                }
            }
        }
コード例 #2
0
ファイル: Contains.cs プロジェクト: havok/ngenerics
        public void Empty()
        {
            var circularQueue = new CircularQueue<int>(20);

            Assert.IsFalse(circularQueue.Contains(1));
            Assert.IsFalse(circularQueue.Contains(2));
        }
コード例 #3
0
    public void CircularQueue_EnqueueDequeueManyChunks_ShouldWorkCorrectly()
    {
        // Arrange
        var queue = new CircularQueue<int>();
        int chunks = 100;

        // Act & Assert in a loop
        int value = 1;
        for (int i = 0; i < chunks; i++)
        {
            Assert.AreEqual(0, queue.Count);
            var chunkSize = i + 1;
            for (int counter = 0; counter < chunkSize; counter++)
            {
                Assert.AreEqual(value - 1, queue.Count);
                queue.Enqueue(value);
                Assert.AreEqual(value, queue.Count);
                value++;
            }
            for (int counter = 0; counter < chunkSize; counter++)
            {
                value--;
                Assert.AreEqual(value, queue.Count);
                queue.Dequeue();
                Assert.AreEqual(value - 1, queue.Count);
            }
            Assert.AreEqual(0, queue.Count);
        }
    }
コード例 #4
0
 public CacheStream2(int bufferBlockSize, int bufferBlockCount, string filename)
 {
     m_bufferBlockSize = bufferBlockSize;
     m_bufferBlockCount = bufferBlockCount;
     m_file = new NativeFileReader(filename);
     m_queue = new CircularQueue<byte[]>(bufferBlockCount);
 }
コード例 #5
0
ファイル: CircularQueueSpec.cs プロジェクト: drunkcod/Cone
        public void TryEnqueue_fails_when_at_capacity()
        {
            var q = new CircularQueue<int>(1);
            Assume.That(() => q.TryEnqueue(0));

            Check.That(() => !q.TryEnqueue(1));
        }
コード例 #6
0
ファイル: Enqueue.cs プロジェクト: havok/ngenerics
        public void OverFlow()
        {
            var circularQueue = new CircularQueue<int>(5);

            for (var i = 0; i < 10; i++)
            {
                circularQueue.Enqueue(i);
            }

            Assert.AreEqual(circularQueue.Count, 5);

            for (var i = 0; i < 5; i++)
            {
                Assert.AreEqual(circularQueue.Count, 5 - i);
                Assert.AreEqual(circularQueue.Dequeue(), i + 5);
                Assert.AreEqual(circularQueue.Count, 4 - i);
            }

            circularQueue = new CircularQueue<int>(100);

            for (var i = 0; i < 200; i++)
            {
                circularQueue.Enqueue(i);
            }

            for (var i = 100; i < 200; i++)
            {
                Assert.AreEqual(circularQueue.Dequeue(), i);
            }
        }
コード例 #7
0
ファイル: FoxPriceData.cs プロジェクト: HongSeokHwan/legacy
 public FoxPriceData(int maxQueueCount, int oneSecCount, String code)
 {
     this._oneSecCount = oneSecCount;
     this._maxQueueCount = maxQueueCount;
     this._cq = new CircularQueue(maxQueueCount);
     this._code = code;
 }
コード例 #8
0
 static TetrisController()
 {
     /*
         0100 0000
         0100 1111
         0100 0000
         0100 0000
     */
     TetrisIGroup = new CircularQueue<ushort>(new ushort[] { 17476, 3840 });
     /*
         0010 0100 0011 0000
         0010 0111 0010 0111
         0110 0000 0010 0001
         0000 0000 0000 0000
     */
     TetrisJGroup = new CircularQueue<ushort>(new ushort[] { 8800, 18176, 12832, 1808 });
     /*
         0100 0000 1100 0010
         0100 1110 0100 1110
         0110 1000 0100 0000
         0000 0000 0000 0000
     */
     TetrisLGroup = new CircularQueue<ushort>(new ushort[] { 17504, 3712, 50240, 11776 });
     /*
         0000
         0110
         0110
         0000
     */
     TetrisOGroup = new CircularQueue<ushort>(new ushort[] { 1632 });
     /*
         0100 0011
         0110 0110
         0010 0000
         0000 0000
     */
     TetrisSGroup = new CircularQueue<ushort>(new ushort[] { 17952, 13824 });
     /*
         0010 0010 0000 0010
         0111 0011 0111 0110
         0000 0010 0010 0010
         0000 0000 0000 0000
     */
     TetrisTGroup = new CircularQueue<ushort>(new ushort[] { 9984, 8992, 1824, 9760 });
     /*
         0010 0110
         0110 0011
         0100 0000
         0000 0000
      */
     TetrisZGroup = new CircularQueue<ushort>(new ushort[] { 9792, 25344 });
     TetrisI = new Tetris(TetrisIGroup, Brushes.Red);
     TetrisJ = new Tetris(TetrisJGroup, Brushes.Cyan);
     TetrisL = new Tetris(TetrisLGroup, Brushes.Yellow);
     TetrisO = new Tetris(TetrisOGroup, Brushes.Blue);
     TetrisS = new Tetris(TetrisSGroup, Brushes.Green);
     TetrisT = new Tetris(TetrisTGroup, Brushes.Orange);
     TetrisZ = new Tetris(TetrisZGroup, Brushes.Purple);
     Tetris = new List<Tetris>(new Tetris[] { TetrisI, TetrisJ, TetrisL, TetrisO, TetrisS, TetrisT, TetrisZ });
 }
コード例 #9
0
ファイル: Remove.cs プロジェクト: havok/ngenerics
        public void Interface()
        {
            ICollection<int> c = new CircularQueue<int>(20);
            Assert.IsFalse(c.Remove(5));

            c.Add(2);

            Assert.AreEqual(c.Count, 1);
            Assert.IsTrue(c.Remove(2));
            Assert.AreEqual(c.Count, 0);

            c.Add(4);
            c.Add(5);
            c.Add(6);

            Assert.AreEqual(c.Count, 3);
            Assert.IsFalse(c.Remove(2));
            Assert.AreEqual(c.Count, 3);

            Assert.IsTrue(c.Remove(5));
            Assert.AreEqual(c.Count, 2);

            Assert.IsTrue(c.Remove(6));
            Assert.AreEqual(c.Count, 1);

            Assert.IsTrue(c.Remove(4));
            Assert.AreEqual(c.Count, 0);
        }
コード例 #10
0
        public void EnqueueFullTest()
        {
            _circularQueue = new CircularQueue<int>(_nodes.Length);
            var i = 0;

            var next = _circularQueue.NextIndex(null);
            _circularQueue.Enqueue(i++);
            if (next != null)
                Assert.AreEqual(i - 1, _circularQueue.QueueList[next.Value], "Could not get the right value at the element - " + (i - 1));

            next = _circularQueue.NextIndex(i - 1);
            _circularQueue.Enqueue(i++);
            if (next != null)
                Assert.AreEqual(i - 1, _circularQueue.QueueList[next.Value], "Could not get the right value at the element - " + (i - 1));

            next = _circularQueue.NextIndex(i - 1);
            _circularQueue.Enqueue(i++);
            if (next != null)
                Assert.AreEqual(i - 1, _circularQueue.QueueList[next.Value], "Could not get the right value at the element - " + (i - 1));

            next = _circularQueue.NextIndex(i - 1);
            _circularQueue.Enqueue(i++);
            if (next != null)
                Assert.AreEqual(i - 1, _circularQueue.QueueList[next.Value], "Could not get the right value at the element - " + (i - 1));

            next = _circularQueue.NextIndex(i - 1);
            _circularQueue.Enqueue(i++);
            if (next != null)
                Assert.AreEqual(i - 1, _circularQueue.QueueList[next.Value], "Could not get the right value at the element - " + (i - 1));

            next = _circularQueue.NextIndex(i - 1);
            _circularQueue.Enqueue(i++);
            if (next != null)
                Assert.AreEqual(i - 1, _circularQueue.QueueList[next.Value], "Could not get the right value at the element - " + (i - 1));
        }
コード例 #11
0
ファイル: Contruction.cs プロジェクト: havok/ngenerics
 public void Simple()
 {
     var circularQueue = new CircularQueue<int>(4);
     Assert.AreEqual(circularQueue.Count, 0);
     Assert.IsTrue(circularQueue.IsEmpty);
     Assert.IsFalse(circularQueue.IsFull);
 }
コード例 #12
0
 public void EnqueueSingleTest()
 {
     _circularQueue = new CircularQueue<int>(_nodes.Length);
     LoadInput();
     const int expectedValue = 5;
     _circularQueue.Enqueue(expectedValue);
     Assert.AreEqual(expectedValue, _circularQueue.Dequeue(), "Could not extract the right element inserted in a full queue");
 }
コード例 #13
0
ファイル: ScreenConnection.cs プロジェクト: PyrO70/hwkinect
 /// <summary>
 /// Create a new message connection between screen and server.
 /// </summary>
 /// <param name="receiveQueue"> Temporary queue used to store received messages. </param>
 /// <param name="socket"> Socket to use to send and receive messages. </param>
 public ScreenConnection(CircularQueue<Message> receiveQueue, Socket socket)
 {
     m_socket = socket;
     m_receiveQueue = receiveQueue;
     m_receiveBuffer = new CircularBuffer(4096);
     m_serializer = new TextMessageSerializer();
     //m_serializer = new BinaryMessageSerializer();
 }
コード例 #14
0
ファイル: IsReadOnly.cs プロジェクト: GTuritto/ngenerics
        public void Simple()
        {
            var circularQueue = new CircularQueue<int>(40);
            Assert.IsFalse(circularQueue.IsReadOnly);

            circularQueue = CircularQueueTest.GetFullTestQueue();
            Assert.IsFalse(circularQueue.IsReadOnly);
        }
コード例 #15
0
ファイル: Engine.cs プロジェクト: Vipeax/cleanLayer
        public static void Initialize(CircularQueue<Location> waypoints, int timeBetweenPulses = 333)
        {
            TimeBetweenPulses = timeBetweenPulses; // Defaults to 333 = 3 pulses every second
            Waypoints = waypoints;

            States = new List<State>(); // Instantiate a new list of states
            LoadInternalStates(); // Load the States from the internal assembly (subclasses of State)
            States.Sort(); // Sort the list by priority
        }
コード例 #16
0
ファイル: Accept.cs プロジェクト: havok/ngenerics
        public void Empty()
        {
            var circularQueue = new CircularQueue<int>(40);
            var visitor = new TrackingVisitor<int>();

            circularQueue.AcceptVisitor(visitor);

            Assert.AreEqual(visitor.TrackingList.Count, 0);
        }
コード例 #17
0
    public void Dequeue_EmptyQueue_ThrowsException()
    {
        // Arrange
        var queue = new CircularQueue<int>();

        // Act
        queue.Dequeue();

        // Assert: expect and exception
    }
コード例 #18
0
        public void shouldCopyUsingToArray()
        {
            var testee = new CircularQueue<int>(new[] { 1, 2, 3, 4 });
            testee.Cycle();
            testee.Cycle();
            var expected = new[] { 3, 4, 1, 2 };

            var actual = testee.ToArray();

            Assert.IsTrue(actual.SequenceEqual(expected), actual.PrintContentsToString(", "));
        }
コード例 #19
0
ファイル: NetworkManager.cs プロジェクト: xaznblade/hwkinect
        public NetworkManager(IPAddress serverAddress, int serverPort)
        {
            this.serverAddress = serverAddress;
            this.serverPort = serverPort;
            this.messageQueue = new CircularQueue<Message>(256);

            m_conn = new ScreenConnection(this.messageQueue);
            m_conn.Connected += OnConnected;
            m_conn.ConnectFailed += OnConnectFailed;
            m_conn.Disconnected += OnDisconnected;
        }
コード例 #20
0
ファイル: Screen.cs プロジェクト: PyrO70/hwkinect
 public Screen(string name, int id, Socket socket, Server server)
 {
     m_name = name;
     m_id = id;
     m_server = server;
     m_bubbles = new Dictionary<int, ServerBalloon>();
     m_queue = new CircularQueue<Message>(64);
     m_connection = new ScreenConnection(m_queue, socket);
     m_thread = new Thread(Run);
     m_thread.Start();
 }
コード例 #21
0
ファイル: CircularQueueSpec.cs プロジェクト: drunkcod/Cone
        public void TryEnqueue_fails_if_write_catches_up_to_read()
        {
            var q = new CircularQueue<int>(2);
            int ignored;
            Assume.That(() => q.TryEnqueue(0));
            Assume.That(() => q.TryDeque(out ignored));

            Assume.That(() => q.TryEnqueue(0));
            Assume.That(() => q.TryEnqueue(1));
            Check.That(() => !q.TryEnqueue(2));
        }
コード例 #22
0
ファイル: FeedReader.cs プロジェクト: xaznblade/hwkinect
 public FeedReader(Server server, string feedUrl, double pullIntervals)
 {
     this.m_server = server;
     this.m_feedUrl = feedUrl;
     this.m_interval = pullIntervals;
     this.m_queue = new CircularQueue<Message>(64);
     this.m_client = new WebClient();
     this.m_timer = new System.Timers.Timer(m_interval);
     this.m_timer.Elapsed += (sender, args) => Refresh();
     this.m_thread = new Thread(Run);
     this.m_thread.Start();
 }
コード例 #23
0
 public void CircularQueue_push_cmp()
 {
     CircularQueue<int> x = new CircularQueue<int>(3);
     x.push(10);
     Assert.IsTrue(x.cmp(new[] { 10 }));
     x.push(15);
     Assert.IsTrue(x.cmp(new[] { 10, 15}));
     x.push(20);
     Assert.IsTrue(x.cmp(new[] { 10, 15, 20 }));
     x.push(25);
     Assert.IsTrue(x.cmp(new[] { 15, 20, 25 }));
 }
コード例 #24
0
        public CircularQueueTests()
        {
            var methods = new Func<int, int, int>[]
            {
                (x, y) => x + y,
                (x, y) => x - y,
                (x, y) => x * y,
                (x, y) => x / y
            };

            this.testee = new CircularQueue<Func<int, int, int>>(methods);
        }
コード例 #25
0
ファイル: CopyTo.cs プロジェクト: GTuritto/ngenerics
        public void ExeptionInvalidArray1()
        {
            var circularQueue = new CircularQueue<int>(30);

            for (var i = 1; i < 20; i++)
            {
                circularQueue.Enqueue(i);
            }

            var array = new int[19];

            circularQueue.CopyTo(array, 1);
        }
コード例 #26
0
ファイル: CircularQueueSpec.cs プロジェクト: drunkcod/Cone
        public void is_first_in_first_out()
        {
            var q = new CircularQueue<int>(2);

            Assume.That(() => q.TryEnqueue(0));
            Assume.That(() => q.TryEnqueue(1));

            int value;
            Check.That(
                () => q.TryDeque(out value) && value == 0,
                () => q.TryDeque(out value) && value == 1
            );
        }
コード例 #27
0
ファイル: Enqueue.cs プロジェクト: havok/ngenerics
        public void Simple()
        {
            var circularQueue = new CircularQueue<int>(4);

            circularQueue.Enqueue(1);
            Assert.AreEqual(circularQueue.Dequeue(), 1);

            circularQueue.Enqueue(2);
            circularQueue.Enqueue(3);
            Assert.AreEqual(circularQueue.Dequeue(), 2);
            Assert.AreEqual(circularQueue.Dequeue(), 3);

            circularQueue.Enqueue(4);
            circularQueue.Enqueue(5);
            circularQueue.Enqueue(6);
            circularQueue.Enqueue(7);

            Assert.AreEqual(circularQueue.Dequeue(), 4);
            Assert.AreEqual(circularQueue.Dequeue(), 5);
            Assert.AreEqual(circularQueue.Dequeue(), 6);
            Assert.AreEqual(circularQueue.Dequeue(), 7);

            circularQueue.Enqueue(8);
            circularQueue.Enqueue(9);
            Assert.AreEqual(circularQueue.Dequeue(), 8);
            circularQueue.Enqueue(10);
            Assert.IsFalse(circularQueue.IsEmpty);
            Assert.IsFalse(circularQueue.IsFull);
            circularQueue.Enqueue(11);
            circularQueue.Enqueue(12);

            Assert.IsFalse(circularQueue.IsEmpty);

            Assert.IsTrue(circularQueue.IsFull);
            Assert.AreEqual(circularQueue.Count, 4);

            Assert.AreEqual(circularQueue.Dequeue(), 9);
            Assert.AreEqual(circularQueue.Count, 3);

            Assert.AreEqual(circularQueue.Dequeue(), 10);
            Assert.AreEqual(circularQueue.Count, 2);

            Assert.AreEqual(circularQueue.Dequeue(), 11);
            Assert.AreEqual(circularQueue.Count, 1);

            Assert.AreEqual(circularQueue.Dequeue(), 12);

            Assert.IsFalse(circularQueue.IsFull);
            Assert.IsTrue(circularQueue.IsEmpty);
            Assert.AreEqual(circularQueue.Count, 0);
        }
コード例 #28
0
        public NetworkManager(IPAddress serverAddress, int serverPort)
        {
            this.serverAddress = serverAddress;
            this.serverPort = serverPort;

            this.balloonCache = new Dictionary<string, Balloon>();
            this.messageQueue = new CircularQueue<Message>(256);

            m_conn = new ScreenConnection(this.messageQueue);
            m_conn.Connected += OnConnected;
            m_conn.ConnectFailed += OnConnectFailed;
            m_conn.Disconnected += OnDisconnected;
            m_conn.MessageReceived += OnMessageReceived;
        }
コード例 #29
0
ファイル: Navigation.cs プロジェクト: Vipeax/cleanLayer
        public static CircularQueue<Location> LoadFile(string filePath)
        {
            if (!File.Exists(filePath))
                throw new FileNotFoundException("Could not find the specified file!", filePath);

            var ret = new CircularQueue<Location>();
            XElement file = XElement.Load(filePath);
            var points = from p in file.Descendants("Location")
                         select p;
            foreach (XElement point in points)
                ret.Enqueue(new Location(point));

            return ret;
        }
コード例 #30
0
ファイル: Server.cs プロジェクト: PyrO70/hwkinect
        public Server(int port)
        {
            m_port = port;
            m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
                                  ProtocolType.Tcp);
            m_queue = new CircularQueue<Message>(64);
            m_nextScreenID = 0;
            m_nextBalloonID = 0;
            m_screens = new List<Screen>();
            m_bubbles = new Dictionary<int, ServerBalloon>();
            m_reader = new FeedReader(this, "http://localhost", 1000);
            //m_reader.Start();

            m_random = new Random();
        }
コード例 #31
0
ファイル: HashBag.cs プロジェクト: zhuthree/lucenenet
        /// <summary>
        /// Remove all items *not* in a supplied collection from this bag,
        /// counting multiplicities.
        /// </summary>
        /// <param name="items">The items to retain</param>
        public virtual void RetainAll(SCG.IEnumerable <T> items)
        {
            updatecheck();

            HashBag <T> res = new HashBag <T>(itemequalityComparer);

            foreach (T item in items)
            {
                KeyValuePair <T, int> p = new KeyValuePair <T, int>(item);
                if (dict.Find(ref p))
                {
                    KeyValuePair <T, int> q = p;
                    if (res.dict.Find(ref q))
                    {
                        if (q.Value < p.Value)
                        {
                            q.Value++;
                            res.dict.Update(q);
                            res.size++;
                        }
                    }
                    else
                    {
                        q.Value = 1;
                        res.dict.Add(q);
                        res.size++;
                    }
                }
            }

            if (size == res.size)
            {
                return;
            }

            CircularQueue <T> wasRemoved = null;

            if ((ActiveEvents & EventTypeEnum.Removed) != 0)
            {
                wasRemoved = new CircularQueue <T>();
                foreach (KeyValuePair <T, int> p in dict)
                {
                    int removed = p.Value - res.ContainsCount(p.Key);
                    if (removed > 0)
                    {
//#warning We could send bag events here easily using a CircularQueue of (should?)
                        for (int i = 0; i < removed; i++)
                        {
                            wasRemoved.Enqueue(p.Key);
                        }
                    }
                }
            }
            dict = res.dict;
            size = res.size;

            if ((ActiveEvents & EventTypeEnum.Removed) != 0)
            {
                raiseForRemoveAll(wasRemoved);
            }
            else if ((ActiveEvents & EventTypeEnum.Changed) != 0)
            {
                raiseCollectionChanged();
            }
        }
コード例 #32
0
    static void Main()
    {
        var queue = new CircularQueue <int>();

        queue.Enqueue(1);
        queue.Enqueue(2);
        queue.Enqueue(3);
        queue.Enqueue(4);
        queue.Enqueue(5);
        queue.Enqueue(6);

        Console.WriteLine("Count = {0}", queue.Count);
        Console.WriteLine(string.Join(", ", queue.ToArray()));
        Console.WriteLine("---------------------------");

        var first = queue.Dequeue();

        Console.WriteLine("First = {0}", first);
        Console.WriteLine("Count = {0}", queue.Count);
        Console.WriteLine(string.Join(", ", queue.ToArray()));
        Console.WriteLine("---------------------------");

        queue.Enqueue(-7);
        queue.Enqueue(-8);
        queue.Enqueue(-9);
        Console.WriteLine("Count = {0}", queue.Count);
        Console.WriteLine(string.Join(", ", queue.ToArray()));
        Console.WriteLine("---------------------------");

        first = queue.Dequeue();
        Console.WriteLine("First = {0}", first);
        Console.WriteLine("Count = {0}", queue.Count);
        Console.WriteLine(string.Join(", ", queue.ToArray()));
        Console.WriteLine("---------------------------");

        queue.Enqueue(-10);
        Console.WriteLine("Count = {0}", queue.Count);
        Console.WriteLine(string.Join(", ", queue.ToArray()));
        Console.WriteLine("---------------------------");

        first = queue.Dequeue();
        Console.WriteLine("First = {0}", first);
        Console.WriteLine("Count = {0}", queue.Count);
        Console.WriteLine(string.Join(", ", queue.ToArray()));
        Console.WriteLine("---------------------------");


        queue.Enqueue(-7);
        queue.Enqueue(-8);
        queue.Enqueue(-9);
        queue.Enqueue(-9);
        queue.Enqueue(-9);
        queue.Enqueue(-9);
        queue.Enqueue(-9);
        queue.Enqueue(-9);
        queue.Enqueue(-9);
        queue.Enqueue(-9);
        queue.Enqueue(-9);
        Console.WriteLine("Count = {0}", queue.Count);
        Console.WriteLine(string.Join(", ", queue.ToArray()));
        Console.WriteLine("---------------------------");
        Console.Read();
    }
コード例 #33
0
        public void zero_capacity_queue_is_empty()
        {
            var q = new CircularQueue <int>(0);

            Assert.IsTrue(q.Empty);
        }
コード例 #34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RewardCalculator"/> class.
 /// </summary>
 /// <param name="type">The type.</param>
 private RewardCalculator(RewardCalculatorType type)
 {
     Type     = type;
     Winnings = new CircularQueue <double>(14);
     Loosings = new CircularQueue <double>(14);
 }
コード例 #35
0
 public void CircularQueueWithCapacity1ThrowsContractException()
 {
     var sut = new CircularQueue <string>(1);
 }
コード例 #36
0
        public void NextOnEmpty()
        {
            CircularQueue <string> circularQueue = new CircularQueue <string>();

            circularQueue.Next();
        }
コード例 #37
0
        static void Main(string[] args)
        {
            #region 1. Two Sum

            TwoSums twoSums = new TwoSums(new int[] { 2, 7, 11, 15 }, 18);
            twoSums.PrintExample();

            #endregion

            #region 3. LongestSubstringWithoutRepeatingCharacters

            LongestSubstringWithoutRepeatingCharacters longestSubstringWithoutRepeating = new LongestSubstringWithoutRepeatingCharacters("abcdecb");
            longestSubstringWithoutRepeating.PrintExample();

            #endregion

            #region 7. Reverse Integer

            ReverseInteger reverseInteger = new ReverseInteger(-54321);
            reverseInteger.PrintExample();

            #endregion

            #region 8. String to Integer (atoi)

            StringToInteger stringToInteger = new StringToInteger("  -42");
            stringToInteger.PrintExample();

            #endregion

            #region 9. Palindrome Number

            PalindromeNumber palindromeNumber = new PalindromeNumber(121);
            palindromeNumber.PrintExample();

            #endregion

            #region 20. Valid Parentheses

            ValidParentheses validParentheses = new ValidParentheses("(){[]}");
            validParentheses.PrintExample();

            #endregion

            #region 26. Remove Duplicates from Sorted Array

            RemoveDuplicatesFromSortedArray removeDuplicatesFromSortedArray = new RemoveDuplicatesFromSortedArray(new [] { 1, 2, 3, 3, 4, 5, 5, 5, 5, 5, 5, 6 });
            removeDuplicatesFromSortedArray.PrintExample();

            #endregion

            #region 35. Search Insert Position

            SearchInsertPosition searchInsertPosition = new SearchInsertPosition(new [] { 1, 3, 5, 10 }, 9);
            searchInsertPosition.PrintExample();

            #endregion

            #region 58. Length of Last Word

            LengthOfLastWord lengthOfLastWord = new LengthOfLastWord("Hello World");
            lengthOfLastWord.PrintExample();

            #endregion

            #region 104. Maximum Depth of Binary Tree



            #endregion

            #region 125. Valid Palindrome

            ValidPalindrome validPalindrome = new ValidPalindrome("A man, a plan, a canal: Panama");
            validPalindrome.PrintExample();

            #endregion

            #region 136. Single Number

            SingleNumber singleNumber = new SingleNumber(new [] { 2, 2, 3, 3, 1 });
            singleNumber.PrintExample();

            #endregion

            #region 150. Evaluate Reverse Polish Notation

            EvaluateReversePolishNotation evaluateReversePolishNotation = new EvaluateReversePolishNotation(new [] { "2", "1", "+", "3", "*" });
            evaluateReversePolishNotation.PrintExample();

            #endregion

            #region 155. Min Stack

            MinStack minStack = new MinStack();
            minStack.PrintExample();

            #endregion

            #region 167. Two Sum II - Input array is sorted

            TwoSumII twoSumII = new TwoSumII(new [] { 1, 2, 3, 7 }, 10);
            twoSumII.PrintExample();

            #endregion

            #region 200. Number of Islands

            NumberOfIslands numberOfIslands = new NumberOfIslands(new char[, ]
            {
                { '1', '1', '0', '0', '0' },
                { '1', '1', '0', '0', '0' },
                { '0', '0', '1', '0', '0' },
                { '0', '0', '0', '1', '1' }
            });
            numberOfIslands.PrintExample();

            #endregion

            #region 217. Contains Duplicate

            ContainsDuplicate containsDuplicate = new ContainsDuplicate(new [] { 1, 2, 3, 1 });
            containsDuplicate.PrintExample();

            #endregion

            #region 268. Missing Number

            MissingNumber missingNumber = new MissingNumber(new [] { 9, 6, 4, 2, 3, 5, 7, 0, 1 });
            missingNumber.PrintExample();

            #endregion

            #region 344. Reverse String

            ReverseString reverseString = new ReverseString("A man with a plan");
            reverseString.PrintExample();

            #endregion

            #region 387. First Unique Character in a String

            FirstUniqueCharacterInAString firstUniqueChar = new FirstUniqueCharacterInAString("loveleetcode");
            firstUniqueChar.PrintExample();

            #endregion

            #region 412. FizzBuzz

            FizzBuzz fizzBuzz = new FizzBuzz(15);
            fizzBuzz.PrintExample();

            #endregion

            #region 485. Max Consecutive Ones

            MaxConsecutiveOnes maxConsecutiveOnes = new MaxConsecutiveOnes(new int[] { 1, 1, 0, 1, 1, 1 });
            maxConsecutiveOnes.PrintExample();

            #endregion

            #region 509. Fibonacci Number

            FibonacciNumber fibonacciNumber = new FibonacciNumber(10);
            fibonacciNumber.PrintExample();

            #endregion

            #region 622. Design Circular Queue

            CircularQueue circularQueue = new CircularQueue(1);
            Console.WriteLine("622. Design Circular Queue");
            Console.WriteLine($"Front()   : {circularQueue.Front()}");
            Console.WriteLine($"IsEmpty() : {circularQueue.IsEmpty()}");
            circularQueue.EnQueue(1);
            Console.WriteLine($"EnQueue(1)");
            Console.WriteLine($"IsEmpty() : {circularQueue.IsEmpty()}");
            Console.WriteLine($"IsFull()  : {circularQueue.IsFull()}\n");

            #endregion

            #region 707. Design Linked List

            LinkedList linkedList = new LinkedList(new Node());
            linkedList.AddAtTail(10);
            linkedList.AddAtTail(20);
            linkedList.PrintLinkedList();

            #endregion

            #region 709. To Lower Case

            ToLowerCase toLowerCase = new ToLowerCase("LOVELY");
            toLowerCase.PrintExample();

            #endregion

            #region 739. Daily Temperatures

            DailyTemperatures dailyTemperatures = new DailyTemperatures(new [] { 89, 62, 70, 58, 47, 47, 46, 76, 100, 70 });
            dailyTemperatures.PrintExample();

            #endregion

            #region 747. Largest Number at Least Twice of Others

            LargestNumberAtLeastTwiceOfOthers largestNumberAtLeastTwiceOfOthers = new LargestNumberAtLeastTwiceOfOthers(new [] { 3, 6, 1, 0 });
            largestNumberAtLeastTwiceOfOthers.PrintExample();

            #endregion

            #region 771. Jewels and Stones
            string          j = "aA", s = "aAAbbbb";
            JewelsAndStones jewelsAndStones = new JewelsAndStones(j, s);
            jewelsAndStones.PrintExample();

            #endregion

            #region 832. Flipping an Image
            int[][] flippingImageArray      = new int[3][];
            flippingImageArray[0] = new int[] { 1, 1, 0 };
            flippingImageArray[1] = new int[] { 1, 0, 1 };
            flippingImageArray[2] = new int[] { 0, 0, 0 };
            FlippingAnImage flippingAnImage = new FlippingAnImage(flippingImageArray);
            flippingAnImage.PrintExample();

            #endregion

            #region 917. Reverse Only Letters

            ReverseOnlyLetters reverseOnlyLetters = new ReverseOnlyLetters("Qedo1ct-eeLg=ntse-T!");
            reverseOnlyLetters.PrintExample();

            #endregion


            Console.ReadLine();
        }
コード例 #38
0
 public EnqueueOperation(CircularQueue queue) => this.queue = queue;
コード例 #39
0
    IEnumerator PlayAI()
    {
        int FrameCount = 0;
        CircularQueue <float[]> History = new CircularQueue <float[]>();

        History.Init(m_nHistoryCount, new float[m_nInputSize]);
        UpdateStateBuffer();
        for (int i = 0; i < m_nHistoryCount; i++)
        {
            History.pushBack(m_faStateBuffer);
        }
        double[] daInput      = new double[m_nn.m_nInputSize];
        double[] daNext_input = new double[m_nn.m_nInputSize];
        double[] daReward     = new double[m_nn.m_nOutputSize];

        float[]           HistoryData;
        WaitForEndOfFrame endofFrame = new WaitForEndOfFrame();

        while (true)
        {
            for (int i = 0; i < m_nHistoryCount; i++)
            {
                History.getValue(i, out HistoryData);
                Array.Copy(HistoryData, 0, daInput, i * HistoryData.Length, HistoryData.Length);
            }
            m_nn.SetInput(daInput);
            m_nn.FeedForward();

            int nSelected_dir = m_bTraning ? m_nn.GetOutputIXEpsilonGreedy(m_fTraningRandomValue) : m_nn.GetOutputIXEpsilonGreedy(0.0);
            m_scriptPaddle.Move((Paddle_2D.MoveDir)nSelected_dir);

            yield return(endofFrame);

            float fReward = m_scriptBall.m_fReward;

            if (fReward > 0.5f)
            {
                counter++;
            }
            if (fReward != 0.0f)
            {
                counter_all++;
            }

            //Debug.Log(counter_all);

            if (counter_all == 1000)
            {
                //static double time = timeGetTime();

                //if (m_bTraning == true)
                //{
                Debug.Log((float)counter / (float)counter_all * 100.0f);
                //}
                //std::cout << (float)counter / (float)counter_all * 100.0f << " % " << (timeGetTime() - time) / 1000.0f << " sec" << std::endl;

                //time = timeGetTime();

                counter     = 0;
                counter_all = 0;
            }

            //Debug.Log("FrameCount: " + ++FrameCount + " Reward: " + fReward);
            //if (fReward < 0.0f)
            //{
            //    fReward = 0.0f;
            //}
            m_scriptBall.m_fReward = 0;

            m_nn.copyOutputVectorTo(ref daReward);
            History.pushBack(UpdateStateBuffer().Clone() as float[]);

            for (int i = 0; i < m_nHistoryCount; i++)
            {
                History.getValue(i, out HistoryData);
                Array.Copy(HistoryData, 0, daNext_input, i * HistoryData.Length, HistoryData.Length);
            }
            m_nn.SetInput(daNext_input);
            m_nn.FeedForward();

            double?dNext_Q = m_nn.GetMaxValueFromOutput();
            if (dNext_Q.HasValue)
            {
                daReward[nSelected_dir] = fReward + (m_fGamma * dNext_Q.Value);
            }

            if (m_bTraning)
            {
                if (fReward > 0)
                {
                    m_nn.SetInput(daInput);
                    for (int i = 0; i < 20; i++)
                    {
                        m_nn.FeedForward();
                        m_nn.PropBackward(daReward);
                    }
                }
            }

            m_nn.SetInput(daInput);
            m_nn.FeedForward();
            m_nn.PropBackward(daReward);
        }
    }
コード例 #40
0
ファイル: CircularQueueTests.cs プロジェクト: abeyerdev/FGLib
 public void CannotCreateQueueSmallerThan2_Test()
 {
     CircularQueue <string> failure = new CircularQueue <string>(1);
 }
コード例 #41
0
ファイル: CircularQueueTests.cs プロジェクト: abeyerdev/FGLib
        public void CanConstruct_Test()
        {
            CircularQueue <string> queue = new CircularQueue <string>(5);

            Assert.IsInstanceOfType(queue, typeof(CircularQueue <string>));
        }
コード例 #42
0
        public void IsEmpty_EmptyQueue_ReturnsTrue()
        {
            var stack = new CircularQueue <int>();

            Assert.IsTrue(stack.IsEmpty);
        }
コード例 #43
0
        public void TestInitialCount()
        {
            CircularQueue <int> queue = new CircularQueue <int>(10);

            Assert.AreEqual(0, queue.Count);
        }
コード例 #44
0
ファイル: Accept.cs プロジェクト: vh-vahan/ngenerics
        public void ExceptionNullVisitor()
        {
            var circularQueue = new CircularQueue <int>(20);

            Assert.Throws <ArgumentNullException>(() => circularQueue.AcceptVisitor(null));
        }
コード例 #45
0
        public void AddItemToReadonly()
        {
            CircularQueue <string> circularQueue = new CircularQueue <string>(new[] { "First", "Second", "Third" }, true);

            circularQueue.Enqueue("First");
        }
コード例 #46
0
        public void IsEmptyReturnsTrueOnEmptyQueue()
        {
            var Queue = new CircularQueue <string>(2);

            Assert.IsTrue(Queue.IsEmpty());
        }
コード例 #47
0
        public void PeekOnEmpty()
        {
            CircularQueue <string> circularQueue = new CircularQueue <string>();

            circularQueue.Peek();
        }
コード例 #48
0
        public void QueueStackCorrectlyReportsItsEmptiness()
        {
            var sut = new CircularQueue <int>();

            Assert.True(sut.IsEmpty);
        }
コード例 #49
0
        public void RemoveOnEmpty()
        {
            CircularQueue <string> circularQueue = new CircularQueue <string>();

            circularQueue.Remove();
        }
コード例 #50
0
        public void PopFromEmptyQueueThrowsAnException()
        {
            var sut = new CircularQueue <int>();

            Assert.Throws <ArgumentException>(() => sut.Dequeue());
        }
コード例 #51
0
 protected void UnLoadInput()
 {
     _circularQueue = new CircularQueue <int>();
 }
コード例 #52
0
        public void CanEnqueueOneElement()
        {
            var Queue = new CircularQueue <string>(10);

            Queue.Enqueue(_elements[0]);
        }
コード例 #53
0
 public void CircularQueueWithCapacity4096Succeeds()
 {
     var sut = new CircularQueue <string>(4096);
 }
コード例 #54
0
        public void ExceptionNullVisitor()
        {
            var circularQueue = new CircularQueue <int>(20);

            circularQueue.AcceptVisitor(null);
        }
コード例 #55
0
 public ExecutionContext()
 {
     ValueStack   = new CircularQueue <byte[]>();
     AltStack     = new CircularQueue <byte[]>();
     ControlStack = new CircularQueue <bool>();
 }
コード例 #56
0
        public MainForm()
        {
            log4net.Config.XmlConfigurator.Configure();
            log.Info("MainForm.MainForm : Application opened as " + PROGRAM_NAME);

            InitializeComponent();
            this.Text    = PROGRAM_NAME;
            isCameraMode = false;

            zibReplayCam1.SetText("");
            zibReplayCam2.SetText("");
            Camera1Display.SetText("");
            Camera2Display.SetText("");

            SwitchDisplayMode();

            guiSem           = new Semaphore(0, 1);
            program_settings = new Settings();
            // see how much memory is available on computer and take 80% of it
            float freeMem = 1000;

            try
            {
                System.Diagnostics.PerformanceCounter ramCounter = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");
                freeMem = ramCounter.NextValue();
            }
            catch (Exception inner)
            {
                log.Error("MainForm.Form1_Load : Unable to retrieve amount of free memory on system, defaulting to 1GB.", inner);
            }
            if (freeMem > 2100)
            {
                freeMem = 2100;
            }

            // each queue takes 6 MB per item in it
            int queueSize = 50;//Convert.ToInt32(freeMem * 0.90) / 32;

            mainQueue = new CircularQueue <QueueElement>("MAIN", queueSize);
            ipQueue1  = new CircularQueue <QueueElement>("IP1", queueSize);
            ipQueue2  = new CircularQueue <QueueElement>("IP2", queueSize);
            saveQueue = new CircularQueue <QueueElement>("save_queue", queueSize);

            // initialize camera and processor 1
            cam1 = new Camera();
            cam1.AddSubscriber(ipQueue1);
            cam1.AddSubscriber(mainQueue);
            imagep1 = new FailureDetector(DEFAULT_IMAGE_PROCESSOR1_NAME, ref cam1);
            imagep1.SetConsumerQueue(ipQueue1);
            imagep1.AddSubscriber(saveQueue);
            imagep1.AddSubscriber(mainQueue);
            imagep1.EnableAutoExposure(true);
            imagep1.EnableAutoROI(false);

            // initialize camera and processor 2
            cam2 = new Camera();
            cam2.AddSubscriber(ipQueue2);
            cam2.AddSubscriber(mainQueue);
            imagep2 = new FailureDetector(DEFAULT_IMAGE_PROCESSOR2_NAME, ref cam2);
            imagep2.SetConsumerQueue(ipQueue2);
            imagep2.AddSubscriber(saveQueue);
            imagep2.AddSubscriber(mainQueue);
            imagep2.EnableAutoExposure(true);
            imagep2.EnableAutoROI(false);

            // sets image queue
            saveEngine = new ImageHistoryBuffer();
            saveEngine.SetConsumerQueue(saveQueue);

            // add thread error handlers
            cam1.ThreadError       += new ThreadErrorHandler(Camera0ThreadError);
            cam2.ThreadError       += new ThreadErrorHandler(Camera1ThreadError);
            imagep1.ThreadError    += new ThreadErrorHandler(ImageProcessor0ThreadError);
            imagep2.ThreadError    += new ThreadErrorHandler(ImageProcessor0ThreadError);
            saveEngine.ThreadError += new ThreadErrorHandler(SaveQueueThreadError);

            // start the cameras
            RefreshCameras();


            // initialize camera and processor periods
            camera1Period  = 0.066;
            camera2Period  = 0.066;
            process1Period = 0.2;
            process2Period = 0.2;

            // need to update comboboxes
            cmboCam1View.Items.Add(DISPLAY_TYPE_NORMAL);
            cmboCam1View.Items.Add(DISPLAY_TYPE_PROCESSED);
            cmboCam1View.SelectedIndex = 0;

            cmboCam2View.Items.Add(DISPLAY_TYPE_NORMAL);
            cmboCam2View.Items.Add(DISPLAY_TYPE_PROCESSED);
            cmboCam2View.SelectedIndex = 0;

            cmbo_DataType.Items.Add(DISPLAY_TYPE_NORMAL);
            cmbo_DataType.Items.Add(DISPLAY_TYPE_PROCESSED);
            cmbo_DataType.SelectedIndex = 1;

            cmbo_VideoType.Items.Add(VIDEO_TYPE_TEST);
            cmbo_VideoType.Items.Add(VIDEO_TYPE_DEBUG);
            cmbo_VideoType.SelectedIndex = 0;

            cmbo_DataType.SelectedIndexChanged  += cmbo_DataType_SelectedIndexChanged;
            cmbo_VideoType.SelectedIndexChanged += cmbo_VideoType_SelectedIndexChanged;

            isReplayManagerValid = false;

            guiSem.Release();
            // setup timer update
            TimerCallback tcb = new TimerCallback(DisplayImage);

            imageUpdateTimer = new System.Threading.Timer(tcb, imageUpdateTimer, Timeout.Infinite, Timeout.Infinite);
            imageUpdateTimer.Change(1, 200);

            // setup garbage collector
            TimerCallback tcb2 = new TimerCallback(GarbageCollector);

            garbageCollector = new System.Threading.Timer(tcb2, garbageCollector, Timeout.Infinite, Timeout.Infinite);
            garbageCollector.Change(1, 100);

            // setup replay feedback
            TimerCallback tcb3 = new TimerCallback(ReplayFeedbackTimer);

            replayFeedbackTimer = new System.Threading.Timer(tcb3, replayFeedbackTimer, Timeout.Infinite, Timeout.Infinite);
        }
コード例 #57
0
 /// <summary>
 /// Retrieves the consumer queue from the Failure Detector.  Add
 /// ImageData to this queue in order to get the image processed.
 /// </summary>
 /// <returns>Consumer Queueu</returns>
 public void SetConsumerQueue(CircularQueue <QueueElement> consumer)
 {
     consumerQueue = consumer;
 }
コード例 #58
0
        public void ExceptionEmpty()
        {
            var circularQueue = new CircularQueue <int>(20);

            circularQueue.Peek();
        }
コード例 #59
0
        public void ExceptionEmpty()
        {
            var circularQueue = new CircularQueue <int>(40);

            circularQueue.Dequeue();
        }
コード例 #60
0
        public void ExceptionNullArray()
        {
            var circularQueue = new CircularQueue <int>(20);

            circularQueue.CopyTo(null, 0);
        }