コード例 #1
0
ファイル: LZW.cs プロジェクト: zzhi/Algs4Net
        /// <summary>
        /// Reads a sequence of 8-bit bytes from standard input; compresses
        /// them using LZW compression with 12-bit codewords; and writes the results
        /// to standard output.</summary>
        ///
        public void Compress()
        {
            string    inputChars = input.ReadString();
            TST <int> st         = new TST <int>();

            for (int i = 0; i < R; i++)
            {
                st.Put("" + (char)i, i);
            }
            int code = R + 1; // R is codeword for EOF

            while (inputChars.Length > 0)
            {
                string s = st.LongestPrefixOf(inputChars); // Find max prefix match s.
                output.Write(st[s], W);                    // Print s's encoding.
                int t = s.Length;
                if (t < inputChars.Length && code < L)     // Add s to symbol table.
                {
                    st.Put(inputChars.Substring(0, t + 1), code++);
                }
                inputChars = inputChars.Substring(t);    // Scan past s in input.
            }
            output.Write(R, W);
            output.Close();
        }
コード例 #2
0
ファイル: TST.cs プロジェクト: zzhi/Algs4Net
        public static void MainTest(string[] args)
        {
            // build symbol table from standard input
            TST <int> st    = new TST <int>();
            TextInput StdIn = new TextInput();

            for (int i = 0; !StdIn.IsEmpty; i++)
            {
                string key = StdIn.ReadString();
                st.Put(key, i);
                //Console.WriteLine("Key, value = {0}, {1} is {2}", key, st[key], st[key] == i);
            }

            // print results
            if (st.Count < 100)
            {
                Console.WriteLine("keys(\"\"):");
                foreach (string key in st.Keys)
                {
                    Console.WriteLine(key + " " + st[key]);
                }
                Console.WriteLine();
            }

            Console.WriteLine("LongestPrefixOf(\"shellsort\"):");
            Console.WriteLine(st.LongestPrefixOf("shellsort"));
            Console.WriteLine();

            Console.WriteLine("LongestPrefixOf(\"quicksort\"):");
            Console.WriteLine(st.LongestPrefixOf("quicksort"));
            Console.WriteLine();

            Console.WriteLine("KeysWithPrefix(\"shor\"):");
            foreach (string s in st.KeysWithPrefix("shor"))
            {
                Console.WriteLine(s);
            }
            Console.WriteLine();

            Console.WriteLine("KeysThatMatch(\".he.l.\"):");
            foreach (string s in st.KeysThatMatch(".he.l."))
            {
                Console.WriteLine(s);
            }
            Console.WriteLine();
        }