Esempio n. 1
0
        private static void FastThreeSumCalc(string[] args)
        {
            if (args.Length == 0)
            {
                System.Console.WriteLine("需要在参数中指定问题规模! \n放弃计算...");
                return;
            }
            int count = int.Parse(args[0]);

            for (int i = 1; i <= 5; i++)
            {
                int size  = count * Convert.ToInt32(Math.Pow(2, i));
                var arr   = ThreeSum.GetRandomArray(size);
                var watch = new Stopwatch();
                watch.Start();
                var result = FastThreeSum.Count(arr);
                watch.Stop();
                var ts = watch.Elapsed;
                System.Console.WriteLine();
                System.Console.WriteLine($"快速-消耗时间: {ts.TotalMilliseconds} ms ({ts.TotalSeconds} s)");
                System.Console.WriteLine($"快速-问题规模: {arr.Length}");
                System.Console.WriteLine($"快速-求解结果(三个数和为 0 的个数): {result}");
                System.Console.WriteLine();
            }
        }
Esempio n. 2
0
        private static void TestThreeSum(int[] nums, IList <IList <int> > expected)
        {
            ThreeSum             threeSum = new ThreeSum();
            IList <IList <int> > actual   = threeSum.GetThreeSum(nums);

            Assert.AreEqual(expected, actual);
        }
Esempio n. 3
0
        public void threeSumTest()
        {
            foreach (ThreeSumTestData testData in TestDataList)
            {
                Console.WriteLine("Testing => Input: [{0}]", string.Join(", ", testData.InputArray));


                IList <IList <int> > result = ThreeSum.threeSum(testData.InputArray);

                int i = 0;
                while ((testData.OutputList.Count == result.Count) && (i < result.Count) && (i < testData.OutputList.Count))
                {
                    Console.WriteLine("Result set " + (i + 1) + " :");
                    Console.Write("Expected output: ");
                    foreach (var output in testData.OutputList[i])
                    {
                        Console.Write(output + ", ");
                    }
                    Console.WriteLine();

                    Console.Write("Actual output: ");
                    foreach (var output in result[i])
                    {
                        Console.Write(output + ", ");
                    }
                    Console.WriteLine();

                    CollectionAssert.AreEqual((List <int>)result[i], (List <int>)testData.OutputList[i],
                                              "result sets are not equal");
                    i++;
                }
            }
        }
Esempio n. 4
0
        public void TestThreeSum()
        {
            var threeSumSolver = new ThreeSum();

            int[] nums   = new int[] { -1, 0, 1, 2, -1, -4 };
            var   result = threeSumSolver.CalculateThreeSum(nums);
        }
Esempio n. 5
0
        public void FirstTry_Basic_Test()
        {
            int[] nums = new int[] { 30, -40, -20, -10, 40, 0, 10, 5 };

            List <int[]> result = new ThreeSum().FirstTry(nums);

            Assert.Equal(4, result.Count);
        }
Esempio n. 6
0
        public void FirstTry_Null_Test()
        {
            int[] nums = null;

            List <int[]> result = new ThreeSum().FirstTry(nums);

            Assert.Empty(result);
        }
Esempio n. 7
0
        // 将 a[i] + a[j] + a[k] 改为 (long)a[i] + a[j] + a[k] 即可。
        // 此时整个式子将按照精度最高(也就是 long)的标准计算。
        static void Main(string[] args)
        {
            int[] a = new int[4];
            a[0] = int.MaxValue;
            a[1] = int.MaxValue;
            a[2] = int.MinValue;
            a[3] = 1;

            Console.WriteLine(ThreeSum.Count(a));//2
        }
Esempio n. 8
0
 public void AllZeros()
 {
     Assert.AreEqual(
         new List <IList <int> >
     {
         new List <int> {
             0, 0, 0
         }
     }
         , ThreeSum.FindAll(new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }));
 }
Esempio n. 9
0
        public void intput__2_0_0_2_2_shouldReturn_1set()
        {
            var       inputNum   = new int[] { -2, 0, 0, 2, 2 };
            ArrayList targetList = new ArrayList();

            targetList.Add(new int[] { -2, 0, 2 });
            var actual   = ThreeSum.calThreeSum(inputNum);
            var comparer = Comparer <object> .Create((a, b) => ((int[])a).SequenceEqual((int[])b)? 0 : 1);

            CollectionAssert.AreEqual(targetList, actual, comparer);
        }
Esempio n. 10
0
        public void Given_an_array_when_call_three_sum_then_return_all_unique_triplets_that_sum_is_zero()
        {
            var solution = new ThreeSum();
            var result   = solution.Sum(_numbers);

            Assert.Equal(_expected, result);

            var result1 = solution.Sums(_numbers);

            Assert.Equal(_expected, result1);
        }
        public void ThreeSumTest5()
        {
            //Arrange
            var sut  = new ThreeSum(); //sut: system under test
            var nums = new int[] { 82597, -9243, 62390, 83030, -97960, -26521, -61011, 83390, -38677, 12333, 75987, 46091, 83794, 19355, -71037, -6242, -28801, 324, 1202, -90885, -2989, -95597, -34333, 35528, 5680, 89093, -90606, 50360, -29393, -27012, 53313, 65213, 99818, -82405, -41661, -3333, -51952, 72135, -1523, 26377, 74685, 96992, 92263, 15929, 5467, -99555, -43348, -41689, -60383, -3990, 32165, 65265, -72973, -58372, 12741, -48568, -46596, 72419, -1859, 34153, 62937, 81310, -61823, -96770, -54944, 8845, -91184, 24208, -29078, 31495, 65258, 14198, 85395, 70506, -40908, 56740, -12228, -40072, 32429, 93001, 68445, -73927, 25731, -91859, -24150, 10093, -60271, -81683, -18126, 51055, 48189, -6468, 25057, 81194, -58628, 74042, 66158, -14452, -49851, -43667, 11092, 39189, -17025, -79173, 13606, 83172, 92647, -59741, 19343, -26644, -57607, 82908, -20655, 1637, 80060, 98994, 39331, -31274, -61523, 91225, -72953, 13211, -75116, -98421, -41571, -69074, 99587, 39345, 42151, -2460, 98236, 15690, -52507, -95803, -48935, -46492, -45606, -79254, -99851, 52533, 73486, 39948, -7240, 71815, -585, -96252, 90990, -93815, 93340, -71848, 58733, -14859, -83082, -75794, -82082, -24871, -1 };

            //Act
            var result = sut.GetThreeSum(nums);

            //Assert
            Assert.Equal(3, result.Count);
        }
        public void ThreeSumTest4()
        {
            //Arrange
            var sut  = new ThreeSum(); //sut: system under test
            var nums = new int[] { 34, 55, 79, 28, 46, 33, 2, 48, 31, -3, 84, 71, 52, -3, 93, 15, 21, -43, 57, -6, 86, 56, 94, 74, 83, -14, 28, -66, 46, -49, 62, -11, 43, 65, 77, 12, 47, 61, 26, 1, 13, 29, 55, -82, 76, 26, 15, -29, 36, -29, 10, -70, 69, 17, 49 };

            //Act
            var result = sut.GetThreeSum(nums);

            //Assert
            Assert.Equal(43, result.Count);
        }
        public void ThreeSumTest1()
        {
            //Arrange
            var sut  = new ThreeSum(); //sut: system under test
            var nums = new int[] { -1, 0, 1, 2, -1, -4 };

            //Act
            var result = sut.GetThreeSum(nums);

            //Assert
            Assert.Equal(2, result.Count);
        }
Esempio n. 14
0
        public void GetThreeSum_ShouldReturn_ThreeSum(
            int[] nums,
            int expectedThreeSumCount)
        {
            // Arrange
            var threeSum = new ThreeSum();

            // Act
            var result = threeSum.GetThreeSum(nums);

            // Assert
            result.Count.Should().Be(expectedThreeSumCount);
        }
Esempio n. 15
0
        public void Case1()
        {
            var nums    = new int[] { -1, 0, 1, 2, -1, -4 };
            var results = new ThreeSum().Go(nums);

            Assert.AreEqual(2, results.Count);
            CollectionAssert.AreEqual(new List <int> {
                -1, 0, 1
            }, results[0].ToList());
            CollectionAssert.AreEqual(new List <int> {
                -1, -1, 2
            }, results[1].ToList());
        }
Esempio n. 16
0
        public void ThreeSum_four_zero()
        {
            int[] nums = new[] { 0, 0, 0, 0 };

            var result = new List <List <int> >()
            {
                new List <int>()
                {
                    0, 0, 0
                },
            };

            Assert.AreEqual(result, ThreeSum.ThreeSumFunc(nums));
        }
Esempio n. 17
0
    /// <summary>
    /// 返回对 n 个随机整数的数组进行一次 ThreeSum 所需的时间。
    /// </summary>
    /// <param name="n">随机数组的长度。</param>
    /// <returns>运行时间,单位为毫秒。</returns>
    public static double TimeTrial(int n)
    {
        var a      = new int[n];
        var random = new Random(DateTime.Now.Millisecond);

        for (var i = 0; i < n; i++)
        {
            a[i] = random.Next(-MaximumInteger, MaximumInteger);
        }
        var timer = new Stopwatch();

        ThreeSum.Count(a);
        return(timer.ElapsedTime());
    }
Esempio n. 18
0
        public static double timeTrial(int i)
        {
            int num = 1000000;

            int[] array = new int[i];
            for (int j = 0; j < i; j++)
            {
                array[j] = StdRandom.uniform(-num, num);
            }
            Stopwatch stopwatch = new Stopwatch();

            ThreeSum.count(array);
            return(stopwatch.elapsedTime());
        }
Esempio n. 19
0
 public void NormalCases()
 {
     Assert.AreEqual(
         new List <IList <int> >
     {
         new List <int> {
             -1, -1, 2
         },
         new List <int> {
             -1, 0, 1
         },
     }
         , ThreeSum.FindAll(new int[] { -1, 0, 1, 2, -1, -4 }));
 }
Esempio n. 20
0
        private static void ThreeSumCalc(int count)
        {
            var arr   = ThreeSum.GetRandomArray(count);
            var watch = new Stopwatch();

            watch.Start();
            var result = ThreeSum.Count(arr);

            watch.Stop();
            var ts = watch.Elapsed;

            System.Console.WriteLine();
            System.Console.WriteLine($"消耗时间: {ts.TotalMilliseconds} ms ({ts.TotalSeconds} s)");
            System.Console.WriteLine($"问题规模: {arr.Length}");
            System.Console.WriteLine($"求解结果(三个数和为 0 的个数): {result}");
            System.Console.WriteLine();
        }
 // 由于数组已经排序(从小到大),负数在左侧,正数在右侧。
 // TwoSumFaster
 // 设最左侧下标为 lo,最右侧下标为 hi。
 // 如果 a[lo] + a[hi] > 0, 说明正数太大,hi--。
 // 如果 a[lo] + a[hi] < 0,说明负数太小,lo++。
 // 否则就找到了一对和为零的整数对,lo++, hi--。
 //
 // ThreeSumFaster
 // 对于数组中的每一个数 a,ThreeSum 问题就等于求剩余数组中所有和为 -a 的 TwoSum 问题。
 // 只要在 TwoSumFaster 外层再套一个循环即可。
 static void Main(string[] args)
 {
     char[] split = new char[1] {
         '\n'
     };
     string[] testCases = TestCase.Properties.Resources._1Kints.Split(split, StringSplitOptions.RemoveEmptyEntries);
     int[]    a         = new int[testCases.Length];
     for (int i = 0; i < testCases.Length; i++)
     {
         a[i] = int.Parse(testCases[i]);
     }
     Array.Sort(a);
     Console.WriteLine(TwoSum.Count(a));
     Console.WriteLine(TwoSumFaster(a));
     Console.WriteLine(ThreeSum.Count(a));
     Console.WriteLine(ThreeSumFaster(a));
 }
        /// <summary>
        /// 返回对 n 个随机整数的数组进行一次 ThreeSum 所需的时间。
        /// </summary>
        /// <param name="n">随机数组的长度。</param>
        /// <param name="repeatTimes">重复测试的次数。</param>
        /// <returns></returns>
        public static double TimeTrial(int n, int repeatTimes)
        {
            int[]  a      = new int[n];
            double sum    = 0;
            Random random = new Random(DateTime.Now.Millisecond);

            for (int i = 0; i < n; i++)
            {
                a[i] = random.Next(-MAXIMUM_INTEGER, MAXIMUM_INTEGER);
            }
            for (int i = 0; i < repeatTimes; i++)
            {
                Stopwatch timer = new Stopwatch();
                ThreeSum.Count(a);
                sum += timer.ElapsedTime();
            }
            return(sum / repeatTimes);
        }
Esempio n. 23
0
    /// <summary>
    /// 返回对 n 个随机整数的数组进行一次 ThreeSum 所需的时间。
    /// </summary>
    /// <param name="n">随机数组的长度。</param>
    /// <param name="repeatTimes">重复测试的次数。</param>
    /// <returns></returns>
    public static double TimeTrial(int n, int repeatTimes)
    {
        var    a      = new int[n];
        double sum    = 0;
        var    random = new Random(DateTime.Now.Millisecond);

        for (var i = 0; i < n; i++)
        {
            a[i] = random.Next(-MaximumInteger, MaximumInteger);
        }
        for (var i = 0; i < repeatTimes; i++)
        {
            var timer = new Stopwatch();
            ThreeSum.Count(a);
            sum += timer.ElapsedTime();
        }
        return(sum / repeatTimes);
    }
Esempio n. 24
0
        public void ThreeSum_Test()
        {
            int[] nums = new[] { -1, 0, 1, 2, -1, -4 };

            var result = new List <List <int> >()
            {
                new List <int>()
                {
                    -1, -1, 2
                },
                new List <int>()
                {
                    -1, 0, 1
                }
            };

            Assert.AreEqual(result, ThreeSum.ThreeSumFunc(nums));
        }
Esempio n. 25
0
        public void Test3Sum()
        {
            var target   = new ThreeSum();
            var expected = new List <List <int> >()
            {
                new List <int> {
                    1, 0, -1
                },
                new List <int> {
                    1, 1, -2
                }
            };
            var inputs = new [] { 1, 0, 1 - 2, -1 };


            var actual = target.GetThreeSum(inputs);

            Assert.AreEqual(expected, actual);
        }
Esempio n. 26
0
        private static void FastTwoSumCalc(string[] args)
        {
            if (args.Length == 0)
            {
                System.Console.WriteLine("需要在参数中指定问题规模! \n放弃计算...");
                return;
            }
            int count = int.Parse(args[0]);
            var arr   = ThreeSum.GetRandomArray(count);
            var watch = new Stopwatch();

            watch.Start();
            var result = FastTwoSum.Count(arr);

            watch.Stop();
            var ts = watch.Elapsed;

            System.Console.WriteLine($"快速两数相加: {result}, 耗时: {ts.TotalSeconds} S");
        }
Esempio n. 27
0
        static void Main(string[] args)
        {
            var       ints  = In.ReadInts("1Kints.txt").ToArray();
            Stopwatch watch = new Stopwatch();

            watch.Start();
            var triplets = ThreeSum.Count(ints);

            watch.Stop();
            Console.WriteLine(String.Format("The number of zero sum triplets is {0} for 1Kints, process performed in {1} seconds.", triplets, watch.Elapsed));

            ints  = In.ReadInts("2Kints.txt").ToArray();
            watch = new Stopwatch();
            watch.Start();
            triplets = ThreeSum.Count(ints);
            watch.Stop();
            Console.WriteLine(String.Format("The number of zero sum triplets is {0} for 2Kints, process performed in {1} seconds.", triplets, watch.Elapsed));

            ints  = In.ReadInts("4Kints.txt").ToArray();
            watch = new Stopwatch();
            watch.Start();
            triplets = ThreeSum.Count(ints);
            watch.Stop();
            Console.WriteLine(String.Format("The number of zero sum triplets is {0} for 4Kints, process performed in {1} seconds.", triplets, watch.Elapsed));

            ints  = In.ReadInts("8Kints.txt").ToArray();
            watch = new Stopwatch();
            watch.Start();
            triplets = ThreeSum.Count(ints);
            watch.Stop();
            Console.WriteLine(String.Format("The number of zero sum triplets is {0} for 8Kints, process performed in {1} seconds.", triplets, watch.Elapsed));

            ints  = In.ReadInts("16Kints.txt").ToArray();
            watch = new Stopwatch();
            watch.Start();
            triplets = ThreeSum.Count(ints);
            watch.Stop();
            Console.WriteLine(String.Format("The number of zero sum triplets is {0} for 16Kints, process performed in {1} seconds.", triplets, watch.Elapsed));


            Console.ReadLine();
        }
Esempio n. 28
0
        public void FastVsSlow(string file, int expectedCount, int timeoutInSeconds)
        {
            string actualFilePath = $"../../data/{file}";

            if (!File.Exists(actualFilePath))
            {
                throw new InvalidOperationException(file);
            }

            int[] intArray = File.ReadAllLines(actualFilePath).Select(s => int.Parse(s)).ToArray();

            var fast = Helper.Time(() => ThreeSumFast.Count(intArray), "3SumFast");

            Assert.Equal(expectedCount, fast.Item1);

            var slow = Helper.Time(() => ThreeSum.Count(intArray), "3SumSlow");

            Assert.Equal(expectedCount, slow.Item1);

            Assert.True(fast.Item2 < slow.Item2);
            Assert.True(fast.Item2 + slow.Item2 < timeoutInSeconds * 1000);
        }
Esempio n. 29
0
        private static void ThreeSumTest()
        {
            Console.WriteLine("\n3 Sum question:");

            ThreeSum threeSum = new ThreeSum();

            IList <int[]> testNumberArrays = new List <int[]> {
                new int[] { -1, 0, 1, 2, -1, -4 }
            };

            foreach (int[] array in testNumberArrays)
            {
                Console.WriteLine("[{0}] -> [", string.Join(", ", array));

                IList <IList <int> > solution = threeSum.ThreeSumOne(array);
                foreach (List <int> set in solution)
                {
                    Console.WriteLine("[{0}],", string.Join(", ", set));
                }

                Console.WriteLine("]");
            }
        }
Esempio n. 30
0
        // самые первые занятия, когда показывался подсчет времени
        private static void TestTimeComplexityOnKints()
        {
            /// 1 => 160ms
            /// 2 => 1.35s
            /// 4 => 10.26s
            /// 8 => 1m20s
            ///
            var ints = In.ReadInts("4Kints.txt").ToArray();

            var watch = new Stopwatch();

            watch.Start();

            var triplets = ThreeSum.Count(ints);

            watch.Stop();

            Console.WriteLine($"The number of \"zero-triplets\" : {triplets}");
            Console.WriteLine($"Time taken: {watch.Elapsed:g}");


            Console.Read();
        }