public static byte[] Decompress(byte[] data) { byte[] dhf = HuffmanCoding.Decode(data); byte[] imtf = MoveToFrontCoding.Decode(dhf); byte[] ibw = BurrowsWheelerTransform.InverseTransform(imtf); return(ibw); }
public void Run(string[] args) { string inputFileName = "../../Data/Project02/" + args[0]; string encodedFileName = "../../Data/Project02/" + args[1]; string decodedFileName = "../../Data/Project02/" + args[2]; // load input data Vector <char> inputData = null; DataSerializer <char> .LoadVectorFromTextFile(inputFileName, ref inputData); // create a coder HuffmanCoding coder = new HuffmanCoding(); // encode input data Vector <string> encodedData = null; encodedData = coder.Encode(inputData); // write the encoded data to file DataSerializer <string> .SaveVectorToTextFile(encodedFileName, encodedData); // reload the encoded data from file DataSerializer <string> .LoadVectorFromTextFile(encodedFileName, ref encodedData); // decode the encoded data Vector <char> decodedData = null; decodedData = coder.Decode(encodedData); // write the decoded data to file DataSerializer <char> .SaveVectorToTextFile(decodedFileName, decodedData); // reload the decodedData from file DataSerializer <char> .LoadVectorFromTextFile(decodedFileName, ref decodedData); // validating the coding result, i.e. checking whether inputData = decodedData if (inputData.Count != decodedData.Count) { Console.WriteLine("Input data is not identical to decoded data -- Coding method does not work accurately!"); } else { int i; for (i = 0; i < inputData.Count; i++) { if (!inputData[i].Equals(decodedData[i])) { Console.WriteLine("Input data is not identical to decoded data -- Coding method does not work accurately!"); break; } } if (i == inputData.Count) { Console.WriteLine("Coding method works accurately!"); } } Console.Read(); }
public ActionResult HuffmanEncode(string toEncode, int?basis) { if (toEncode.Length == 0) { ViewData["ArgumentException"] = "Пустая строка, пожалуйста введите что-нибудь."; return(View()); } if (basis == null || basis < 2) { basis = 2; } toEncode = toEncode.Replace("\r\n", "\n"); try { ViewData["Encoded"] = new HuffmanCoding((int)basis).Encode(toEncode, out double compressionRatio); ViewData["CompressionDegree"] = string.Format("{0:0.##}", compressionRatio); } catch (Exception e) { ViewData["Error"] = "Пожалуйста, проверьте соответствие введенных данных нужному формату."; } ViewData["UploadedText"] = toEncode; return(View()); }
public static byte[] Compress(byte[] Data) { byte[] bw = BurrowsWheelerTransform.Transform(Data); byte[] mtf = MoveToFrontCoding.Encode(bw); byte[] hf = HuffmanCoding.Encode(mtf); return(hf); }
public void HuffmanCoding_Test() { var encoder = new HuffmanCoding <char>(); var compressed = encoder .Compress("abcasdasdasdcaaaaaadqwerdasd".ToCharArray()); Assert.AreEqual(compressed['a'].Length, 1); }
public void TestDecode() { byte[] encoded1 = BitStringToByteArray(ENCODED1); byte[] decoded1 = HuffmanCoding.Decode(encoded1); CollectionAssert.AreEqual(DECODED1, decoded1); byte[] encoded2 = BitStringToByteArray(ENCODED2); byte[] decoded2 = HuffmanCoding.Decode(encoded2); CollectionAssert.AreEqual(DECODED2, decoded2); }
public void TestEncode() { byte[] output1 = HuffmanCoding.Encode(DECODED1); byte[] expoutput1 = BitStringToByteArray(ENCODED1); CollectionAssert.AreEqual(expoutput1, output1); byte[] output2 = HuffmanCoding.Encode(DECODED2); byte[] expoutput2 = BitStringToByteArray(ENCODED2); CollectionAssert.AreEqual(expoutput2, output2); }
public void TestCompression() { string content = "dabdccadadad"; byte[] file = Encoding.UTF8.GetBytes(content); var huffman = new HuffmanCoding(); var compressed = huffman.Compress(file); var bits = new BitArray(compressed.BitsTrimmed()); Assert.AreEqual("0111000101101110110110", bits.PrintArray()); }
public byte[] DecompressFile(CompressedFile compressedFile) { ICompressor compressor; if (compressedFile.Queue != null) { compressor = new HuffmanCoding(); } else { compressor = new RunLengthEncodingCompressor(); } return(compressor.Decompress(compressedFile)); }
public void TestDecompression() { string content = "The quick Brown Fox jumps over the Lazy Dog"; byte[] file = Encoding.UTF8.GetBytes(content); var huffman = new HuffmanCoding(); var compressed = huffman.Compress(file); var decompressed = huffman.Decompress(compressed); string decompressedContent = Encoding.UTF8.GetString(decompressed); Assert.AreEqual(content, decompressedContent); }
private void calculate(object sender, RoutedEventArgs e) { List <HuffmanNode> nodeList = getList(); HuffmanCoding huffmanCoding = new HuffmanCoding(); huffmanCoding.getTreeFromList(nodeList); huffmanCoding.setCodeToTheTree("", nodeList[0]); while (nodeList.Count > 1) { HuffmanNode node1 = nodeList[0]; nodeList.RemoveAt(0); HuffmanNode node2 = nodeList[0]; nodeList.RemoveAt(0); nodeList.Add(new HuffmanNode(node1, node2)); nodeList.Sort(); } resultGrid.Children.Clear(); i = 0; showTree(0, nodeList[0]); resultGrid.Width = i * 50; drawLines(nodeList[0]); treeScrollViewer.Visibility = Visibility.Visible; treeScrollViewer.Opacity = 0; treeScrollViewer.OpacityTransition = new ScalarTransition() { Duration = new TimeSpan(0, 0, 0, 0, 500) }; treeScrollViewer.Opacity = 1; codingTable.Visibility = Visibility.Visible; codingTable.Opacity = 0; codingTable.OpacityTransition = new ScalarTransition() { Duration = new TimeSpan(0, 0, 0, 0, 500) }; codingTable.Opacity = 1; codingTable.Children.Clear(); showCodeInList(nodeList[0]); }
private async void panelFile_DragDrop(object sender, DragEventArgs e) { string[] files = e.Data.GetData(DataFormats.FileDrop, false) as string[]; ICompressor compressor; if (comboBoxAlgorithm.Text.Equals("Huffman")) { compressor = new HuffmanCoding(); } else { compressor = new RunLengthEncodingCompressor(); } var file = File.ReadAllBytes(@files.First()); try { pictureBox.Hide(); panelFile.BackgroundImage = Image.FromFile(@files.First()); } catch { pictureBox.Show(); panelFile.BackgroundImage = null; } var stopWatch = new Stopwatch(); stopWatch.Start(); var task = Task.Run(() => { return(compressor.Compress(file)); }); compressedFile = await Task.Run(() => { var writeStatus = new WriteStatusDelegate(WriteStatus); int i = 0; while (!task.IsCompleted) { if (i == 500) { labelStatus.Invoke(writeStatus, $"Status: {compressor.Percentage.ToString("0.00")} % processado"); } i = (i + 1) % 501; } labelStatus.Invoke(writeStatus, $"Status: 100 % processado"); var f = task.Result; f.Name = Path.GetFileName(files.First()); return(f); }); stopWatch.Stop(); var compressionPercentage = compressedFile.Data.Length * 100M / file.Length; labelTempo.Text = stopWatch.Elapsed.ToString(@"hh\:mm\:ss\.ffff"); labelTamanho.Text = (compressedFile.Data.LongLength / 1024M).ToString("0.000") + " kb"; labelCompressionPercent.Text = $"{compressionPercentage.ToString("0.00")} %"; }
static void Main(string[] args) { // StringProblems //Test calls for Reverse string string input = "jacob"; Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray()))); input = "jake"; Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray()))); input = ""; Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray()))); input = "jdshjdh@#$%^&)"; Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray()))); ReplaceSpaces.TestReplaceSpacesInplace(); Anagrams.TestIsAnagramAlgo(); StringRotation.TestIsThisRotatedString(); RemoveDuplicates.TestRemoveDuplicatesFromString(); StringToLongConverter.TestStringToLong(); RegexMatching.TestMatch(); SumOfTwoNumbersInArray.TestSumOfTwoNumbersInArray(); SumOfThreeNumbersInArray.TestSumOfThreeNumbersInArray(); PairInSortedArrayClosestToAParticularValue.TestPairInSortedArrayClosestToAParticularValue(); PalindromeInStringPermutation.TestPalindromeInStringPermutation(); EditDistanceBetweenStrings.TestEditDistanceBetweenStrings(); AnagramIsPalindrome.TestAnagramIsPalindrome(); GreatestPalindrome.TestGreatestPalindrome(); ReverseStringWithoutVowels.TestReverseStringWithoutVowels(); LongestSubstringWithKDistinctChars.TestLongestSubstringWithKDistinctChars(); // Pattern Matching NativePatternMatching.TestNativePatternMatching(); KMPPatternMatching.TestKMPPatternMatching(); BoyerMoorePatternMatching.TestPatternMatching(); RabinKarp.TestRabinKarp(); //Console.ReadLine(); //Array Problems ArrayOfNumsIncrement.TestIncrementArrayOfNumbers(); MajorityElement.TestFindMajorityElement(); Merge2SortedArrays.TestMergeSortedArrays(); MaxDistanceInArray.TestMaxDistanceInArray(); MovingAverage.TestMovingAverage(); TotalAverage.TestTotalAverage(); ArrayWithGreaterElementToRight.TestArrayWithGreaterElementToRight(); WaterCollectedInPuddleShownByHistogram.TestWaterCollectedInPuddleShownByHistogram(); CountOfPairsWhichSumUpToGivenSum.TestCountOfPairsWhichSumUpToGivenSum(); //Median.TestGetMedianOf2SortedArray(); // Sorting Problems SelectionSort.TestSorting(); BubbleSort.TestSorting(); InsertionSort.TestSorting(); ShellSort.TestSorting(); MergeSort.TestMergeSort(); QuickSort.TestQuickSort(); HeapSortTester.TestHeapSort(); CountingSort.TestSorting(); RadixSort.TestRadixSort(); DutchNationalFlag.TestDutchNationalFlag(); SortedSquares.TestSortedSquares(); // Matrix Problem Rotate_Matrix_90_degree.TestRotateMatrix(); Matrix_Column_Rows_0.TestMakeRowColZero1(); Matrix_Column_Rows_0.TestMakeRowColZero2(); RotateMatrix180.TestRotateMatrix180(); SumOfMatrixElementsFormedByRectangleWithCoordinates.TestSumOfMatrixElements(); SortedArrayFromSortedMatrix.TestSortedArrayFromSortedMatrix(); SearchWordInMatrix.TestSearchWordInMatrix(); MaxOnesInRow.TestMaxOnesInRow(); MatrixAsTriangle.TestMatrixAsTriangle(); MinRangeInMatrix.TestMinRangeInMatrix(); PrintMatrixAsSnake.TestPrintMatrixAsSnake(); PrintMatrixInSpiral.TestPrintMatrixInSpiral(); MaxSqAreaInBinaryMatrix.TestMaxRectAreaInBinaryMatrix(); TicTacToeWinner.TestTicTacToeWinner(); WaterfallCreation.TestWaterfallCreation(); // Linked list Problems DeleteLinkedListNode.TestDeleteFirstNode(); DeleteDuplicatesFromLinkedList.TestDeleteDuplicates(); NthLastElementOfLinkedList.TestNthLastNodeOfLinkedList(); DeleteNodeWithDirectReference.TestDeleteNode(); AddNumbers.TestAddNumbersRepresentedByLinkedList(); CopyLinkedListWithRandomNode.TestGetCopiedLinkedListWithRandomNode(); CommonElementInTwoLinkedList.TestCommonElement(); ReverseAdjacentNodesInLinkedList.TestReverseAdjacentNodes(); MergeSortedLinkedList.TestMerge(); CycleInLinkedList.TestStartOfCycleInLinkedList(); MedianForCircularLinkedList.TestGetMedian(); ReverseLinkedList.TestReverseLinkedList(); SortedCircularLinkedList.TestCircularLinkedList(); // stack and queue problem ThreeStackWithOneArray.TestThreeStackWithOneArray(); StackWithMinElement.TestStackWithMinElement(); StackOfPlates.TestStackOfPlates(); SortAStack.TestSortAStackAscending(); WellFormedExpression.TestWellFormedExpression(); QueueVia2Stack.TestQueueVia2Stack(); LRUCache.TestLRUCache(); EvaluatePrefixNotation.TestGetPrefixNotationResult(); EvaluateInflixNotation.TestGetInflixNotationResults(); EvaluatePostfixNotation.TestGetPostfixNotationResult(); TestCircularQueue.TestCircularQueueWithDifferentCases(); LargestAreaInHistogram.TestLargestAreaInHistogram(); TextEditerWithUndo.TestTextEditerWithUndo(); //Recursion Problem TowerOfHanoi.TestTowerOfHanoi(); MaxSumOfConsecutiveNums.TestMaxSumOfConsecutiveNums(); // Back tracking problems Sudoku.TestSudokuSolver(); HamiltonianCycle.TestHamiltonianCycle(); GraphColoringWithMColors.TestGraphColoringWithMColors(); MakeLargestIsland.TestMakeLargestIsland(); //Misc Problem MinNumOfCoins.TestMinNumOfCoins(); IsPrime.TestCheckPrime(); SquareRoot.TestCalculateSquareRoot(); CreditCardCheck.TestLuhnAlgo(); ExcelFirstRowConversion.TestCovertExcelColumnToLong(); Skyline.TestSkyline(); SumOfSquaresWithoutMultiplication.TestSumOfSquares(); MergeIntervals.TestMergeIntervals(); WidthOfCalendar.TestWidthOfCalendar(); JosephusProblem.TestJosephusProblem(); // Permutation and Combination problem ShuffleAList.TestFisherYatesAlgo(); CombinationsOfBinaryString.TestCombinationsOfBinaryString(); AllCombinationsOfString.TestAllCombinationsOfString(); AllPermutationsOfString.TestAllPermutationsOfString(); PhoneNumberToWords.TestPhoneNumberToWords(); AllNumbersInRangeWithDifferentDigits.TestAllNumbersInRangeWithDifferentDigits(); DivideSetIntoTwoEqualSetsWithMinSumDiff.TestDivideSetIntoTwoEqualSetsWithMinSumDiff(); PowerSet.TestPowerSet(); AllCombinationsOfParenthesis.TestAllCombinationsOfParenthesis(); GoodDiceRoll.TestGoodDiceRoll(); PermutationsOfValidTime.TestPermutationsOfValidTime(); // Tree Problems TreeFromExpression.TestCreateTreeFromExpression(); TestBinarySearchTree.TestDifferentOperationsOnBST(); AncestorOfTwoNodesInBST.TestAncestorOfTwoNodesInBST(); CheckBTisBST.TestCheckBTisBST(); MaxSumOnTreeBranch.TestMaxSum(); WalkTheTree.TestWalkTheTree(); SkewedBSTToCompleteBST.TestConvertSkewedBSTToCompleteBST(); CheckIfTheTreeIsBalanced.TestIsTreeBalanced(); LinkedListOfTreeNodesAtEachDepth.TestCreateLinkedListOfTreeNodesAtEachDepth(); PrintBinaryTreeNodeAtEachLevel.TestPrintBinaryTreeNodeAtEachLevel(); PrintBinaryTreeNodeAtEachLevelSpirally.TestPrintBinaryTreeNodeAtEachLevelSpirally(); TreeSubtreeOfAnother.TestMatchTree(); AncestorOfTwoNodesInBT.TestGetAncestorOfTwoNodesInBT(); AncestorOfMultiNodesInBT.TestAncestorOfMultiNodesInBT(); LinkedListFromLeavesOfBT.TestLinkedListFromLeavesOfBT(); ExteriorOfBT.TestPrintExteriorOfBT(); DepthOfTree.TestGetDepthOfTree(); TreeToColumns.TestTreeToColumns(); KthSmallestElementFromBST.TestKthSmallestElementFromBST(); MakeBSTFromPreOrder.TestMakeBSTFromPreOrder(); MirrorATree.TestMirrorATree(); CloneABTWithRandPointer.TestCloneABTWithRandPointer(); TreeWithInorderAndPreorder.TestTreeWithInorderAndPreorder(); TreeWithInorderAndPostorder.TestTreeWithInorderAndPostorder(); TreePathSumsToValue.TestTreePathSumsToValue(); AllPathInNArayTree.TestAllPathInNArayTree(); SerializeDeserializeBinaryTree.TestSerializeDeserializeBinaryTree(); SerializeDeserializeAnNaryTree.TestSerializeDeserializeAnNaryTree(); AncestorOfTwoNodesInNaryTree.TestAncestorOfTwoNodesInNaryTree(); AbsOfMaxAndSecondMaxDepthInBT.TestGetAbsOfMaxAndSecondMaxDepthInBT(); // Trie problems CreateAndSearchSimpleTrie.TestCreateAndSearchSimpleTrie(); // ToDo: have a problem of suffix trees ShortestPrefix.TestGetShortestPrefixNotPresentInStringSet(); // Dynamic Programming problems LongestCommonSubsequence.TestGetLongestCommonSubsequence(); LongestPalindromeSubString.TestGetLongestPalindromeSubString(); LongestPalindromicSubsequence.TestGetLongestPalindromicSubsequence(); MaximumAs.TestGetMaximumAs(); MinNumberOfJumps.TestGetMinimumNumberOfJumps(); LongestCommonSubString.TestGetLongestCommonSubString(); KnapSackProblem.TestGetTheMaximumValueWithLimitedWeight(); TreeCuttingProblem.TestGetTreeCuttingToMaximizeProfits(); WordBreaking.TestBreakTheWords(); DistanceOfWords.TestDistanceOfWords(); LongestIncreasingSubSequence.TestLongestIncreasingSubSequence(); MinCostPath.TestMinCostPath(); DifferentWaysForCoinChange.TestDifferentWaysForCoinChange(); MatrixMultiplication.TestMatrixMultiplication(); BinomialCoefficient.TestBinomialCoefficient(); BoxStacking.TestBoxStacking(); WordWrapping.TestWordWrapping(); MaxSubMatrixWithAllOnes.TestMaxSubMatrixWithAllOnes(); LongestSubStringWithEqualSum.TestLongestSubStringWithEqualSum(); PartitionArrayIntoEqualSumSets.TestPartitionArrayIntoEqualSumSets(); MaxSumRectangle.TestMaxSumRectangle(); RegularExpressionMatch.TestRegularExpressionMatch(); NumRepresentedByPerfectSquares.TestNumRepresentedByPerfectSquares(); LongestCommonSubsequenceInSameString.TestLongestCommonSubsequenceInSameString(); StringDecodeAsAlphabets.TestStringDecodeAsAlphabets(); BalloonBursting.TestBalloonBursting(); TravellingSalesmanProblem.TestTravellingSalesmanProblem(); MaxSumWithoutAdjacentElements.TestMaxSumWithoutAdjacentElements(); MaxPathThroughMatrix.TestMaxPathThroughMatrix(); BrickLaying.TestBrickLaying(); JobSchedullingWithConstraints.TestJobSchedullingWithConstraints(); EggDropMinTrials.TestEggDropMinTrials(); // Graph Problems ShortestPath.TestGetShortestPathBetween2Vertex(); CycleInDirectedGraph.TestIsCycleInDirectedGraph(); CycleInUnDirectedGraph.TestIsCycleInUnDirectedGraph(); SolveAMaze.TestSolveAMaze(); AllPathsGivenStartEndVertex.TestGetAllPathsInGraphFromStartVertexToEndVertex(); AllPaths.TestGetAllPathsInGraphFromStartVertex(); ColorVertices.TestColorVerticesWithDifferentColor(); CheckBipartiteGraph.TestCheckBipartiteGraph(); TransformOneWordToAnother.TestGetTransformation(); ConstraintsVerification.TestConstraintsVerification(); ExtendedContactsInSocialNetwork.TestComputeExtendedContacts(); CourseScheduling.TestCourseScheduling(); SnakeAndLadder.TestSnakeAndLadder(); IsGraphATree.TestIsGraphATree(); ReverseGraph.TestReverseGraph(); StronglyConnectedGraph.TestStronglyConnectedGraph(); ConnectedComponents.TestConnectedComponents(); ContinentalDivide.TestContinentalDivide(); CloneGraph.TestCloneGraph(); Wordament.TestWordament(); // ShortestPathAlgo FloydWarshall.TestFloydWarshall(); DijkstraAlgorithm.TestDijkstraAlgorithm(); BellmanFord.TestBellmanFord(); TravelFromLeftToRightInMatrix.TestTravelFromLeftToRightInMatrix(); HeuristicSearch.TestHeuristicSearch(); AStar.TestAStar(); ShortestPathWhenObstaclesRemoved.TestShortestPathWhenObstaclesRemoved(); ShortestDistanceFromRoomsToGates.TestShortestDistanceFromRoomsToGates(); //MaxFlow FordFulkersonEdmondKarp.TestFordFulkersonEdmondKarp(); MinCut.TestMinCut(); MaximumBipartiteMatching.TestMaximumBipartiteMatching(); //Minimum Spanning Tree KruskalAlgorithm.TestKruskalAlgorithm(); PrimsAlgorithm.TestPrimsAlgorithm(); //Heap problems BasicMaxHeap.TestMaxHeap(); BasicMinHeap.TestMinHeap(); TestMinHeapMap.DoTest(); TestPriorityQueue.Run(); MedianForAStreamOfNumbers.TestMedianForAStreamOfNumbers(); //DisjointSets TestingDisjointSet.Run(); //TestWeightedDisjointSetsWithPathCompression.Run(); // this runs slow, hence commenting it //Geometry ClosestPairOfPoints.TestClosestPairOfPoints(); RectangleIntersection.TestRectangleIntersection(); LineSegmentIntersection.TestLineSegmentIntersection(); ConvexHull.TestConvexHull(); KClosestPointToOrigin.TestKClosestPointToOrigin(); //Greedy Algorithm HuffmanCoding.TestHuffmanCoding(); //Randomized Algorithm RandomGeneration.TestRandomGeneration(); // Bit Algorithms IntHaveOppositeSigns.TestIntHaveOppositeSigns(); Parity.TestParity(); //Math Problem ZerosInFactorial.TestZerosInFactorial(); GetAllPrimeFactors.TestGetAllPrimeFactors(); NumberOfFactors.TestNumberOfFactors(); AllFactors.TestAllFactors(); MultiplyLongNumbers.TestMultiplyLongNumbers(); NextLargestPermutation.TestNextLargestPermutation(); AllPrimesTillN.TestAllPrimesTillN(); PascalsTriangle.TestPascalsTriangle(); SubtractLongNumbers.TestSubtractLongNumbers(); //Search problems SearchInSortedRotatedArray.TestSearchInSortedRotatedArray(); KClosestElementInArray.TestKClosestElementInArray(); SearchInSortedMatrix.TestSearchInSortedMatrix(); BinarySearchUnbounded.TestBinarySearchUnbounded(); LinkedListSublistSearch.TestLinkedListSublistSearch(); NoOfOccuranceInSortedArray.TestNoOfOccuranceInSortedArray(); GetSmallestInSortedRotatedArray.TestGetSmallestInSortedRotatedArray(); //Distributed algorithms KWayMerge.TestKWayMerge(); Console.ReadLine(); }