Python

anagram_test.py

~cpp 

import unittest
import StringIO
from anagram import *

class AnagramTest( unittest.TestCase ):
    def testSortChar( self ):
        a = Anagram()
        self.assertEquals ( 'abc', a.sortChar( 'abc' ) )
        self.assertEquals ( 'abc', a.sortChar( 'cba' ) )

    def testAddWord( self ):
        a = Anagram()
        a.addWord( 'abc' )
        self.assertEquals ( { 'abc' : ['abc'] }, a.getDictionary() )
        a.addWord( 'cba' )
        self.assertEquals ( { 'abc' : ['abc', 'cba'] }, a.getDictionary() )

    def testPrintAnagram( self ):
        a = Anagram()
        a.addWord( 'ab' )
        a.addWord( 'ba' )
        a.addWord( 'abc' )

        outStr = StringIO.StringIO()
        a.printAnagram( output = outStr )
        outStr.pos = 0

        self.assertEquals( """ab ba
abc
""", outStr.read() )

    def testMainFunc( self ):
        inStr = StringIO.StringIO()
        outStr = StringIO.StringIO()

        inStr.write( """ab
ba
abc""" )

        inStr.pos = 0
        a = Anagram()
        a.main( input = inStr, output = outStr )
        outStr.pos = 0

        self.assertEquals( """ab ba
abc
""", outStr.read() )


if __name__ == '__main__':
    unittest.main()

anagram.py

~cpp 

import string
import sys

#from psyco.classes import *
class Anagram:

    def __init__ ( self ):
        self.dictionary = {}

    def sortChar( self, word ):
        lst = list( word )
        lst.sort()
        return string.join( lst, '' ).replace( ' ', '' )

    def addWord( self, word ):
        self.dictionary.setdefault( self.sortChar( word ) ,[]).append( word )

    def getDictionary( self ):
        return self.dictionary

    def printAnagram( self, output = sys.stdout ):
        for list in self.dictionary.values():
            for word in list:
                output.write( word )
                output.write( ' ' )
            output.write( '\n' )

    def main( self, input = sys.stdin, output = sys.stdout ):
        for line in input.readlines():
            self.addWord( line.replace( '\n', '' ) )
        self.printAnagram( output = output )

import time

if __name__ == '__main__':
    a = Anagram()
    before = time.time()
    a.main()
    sys.stderr.write( "Elapsed: " +  str( time.time() - before ) + "\n" )

C#


AnagramTest.cs

~cpp 
using System;
using NUnit.Framework;

namespace AnagramCSharp
{
	/// <summary>
	/// Summary description for AnagramTest.
	/// </summary>
	[TestFixture]
	public class AnagramTest 
	{

		[Test]
		public void Sample() 
		{
			Assertion.AssertEquals( "abc", "abc" );
		}

		[Test]
		public void TestSortWord() 
		{
			Anagram anagram = new Anagram();
			Assertion.AssertEquals( "abc", anagram.SortWord( "cba" ) );
			Assertion.AssertEquals( "ab", anagram.SortWord( "ba" ) );
			Assertion.AssertEquals( "aa", anagram.SortWord( "aa" ) );
		}

		[Test]
		public void TestAddWord() 
		{
			Anagram anagram = new Anagram(); 
			anagram.AddWord( "abc" );
			Assertion.AssertEquals( "-abc add abc", anagram.GetLog() ); 
			anagram.AddWord( "cba" );
			Assertion.AssertEquals( "-abc add abc-cba append abc", anagram.GetLog() ); 
			anagram.AddWord( "aa" );
			Assertion.AssertEquals( "-abc add abc-cba append abc-aa add aa", anagram.GetLog() ); 
		}
	}
}

Anagram.cs

~cpp 
using System;
using System.Collections;
using System.IO;


namespace AnagramCSharp
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class Anagram
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			DateTime start = DateTime.Now;
			Anagram anagram = new Anagram();
			String line = Console.ReadLine();
			while ( null != line ) 
			{
				anagram.AddWord( line );
				line = Console.ReadLine();
			}

			anagram.printDictionary();
			TimeSpan elapsed = DateTime.Now.Subtract( start );

			Console.Error.Write( "Elapsed: " );
			Console.Error.Write( elapsed.Seconds );
			Console.Error.Write( "." );
			Console.Error.WriteLine( elapsed.Milliseconds );

		}

		public Anagram() 
		{
			m_log = new StringWriter();
			m_dictionary = new Hashtable();
		}

		public String SortWord( String word ) 
		{
			//SortedList list = new SortedList();
			ArrayList list = new ArrayList();
			for ( int i = 0; i < word.Length; i++ ) 
			{
				//list.Add( word.Substring( i, 1 ), null );
				list.Add( word.Substring( i, 1 ) );
			}
			list.Sort();

			StringWriter writer = new StringWriter();
			System.Collections.IEnumerator myEnumerator = list.GetEnumerator();
			while ( myEnumerator.MoveNext() )
				writer.Write( myEnumerator.Current );

			return writer.ToString();
		}

		public void AddWord(  String word ) 
		{
			String sortedWord = SortWord( word );
			ArrayList list = (ArrayList) m_dictionary[ sortedWord ];
			
			if ( null == list )
			{
				m_log.Write( "-" + word + " add " + sortedWord );

				list = new ArrayList();
				m_dictionary.Add( sortedWord, list );
			} 
			else 
			{
				m_log.Write( "-" + word + " append " + sortedWord );
			}

			list.Add( word );
			
		}

		public String GetLog() 
		{

			return m_log.ToString();
		}

		public void printDictionary() 
		{
			IDictionaryEnumerator de = m_dictionary.GetEnumerator();
			while( de.MoveNext() )
			{
				ArrayList list = (ArrayList) de.Value;
				IEnumerator le = list.GetEnumerator();
				le.MoveNext();
				Console.Write( (String) le.Current );
				while( le.MoveNext() ) 
				{
					Console.Write( " " );
					Console.Write( (String) le.Current );

				}
				Console.WriteLine();
				
			}
		}

		internal StringWriter m_log;
		internal Hashtable m_dictionary;
	}
}

Java

AnagramTest.java

~cpp 
/*
 * Created by IntelliJ IDEA.
 * User: Jaewoo Kim
 * Date: 2002. 9. 30.
 * Time: 오전 11:24:26
 * To change template for new class use 
 * Code Style | Class Templates options (Tools | IDE Options).
 */
package anagram;

import junit.framework.TestCase;

public class AnagramTest extends TestCase {
    public AnagramTest( String name ) {
        super( name );
    }

    public void testSortWord() {
        Anagram anagram = new Anagram();
        assertEquals(  "ab", anagram.sortWord( "ba" ) );
        assertEquals(  "abc", anagram.sortWord( "bca" ) );
        assertEquals(  "aac", anagram.sortWord( "aca" ) );
    }

    public void testAddToDictionary() {
        Anagram anagram = new Anagram();
        anagram.addToDictionary( "ba" );
        assertEquals( "{ab=[ba]}", anagram.getDictionaryStr() );
        anagram.addToDictionary( "ab" );
        assertEquals( "{ab=[ba, ab]}", anagram.getDictionaryStr() );
        anagram.addToDictionary( "dc" );
        assertEquals( "{ab=[ba, ab], cd=[dc]}", anagram.getDictionaryStr() );
    }

} 

Anagram.java

~cpp 
/*
 * Created by IntelliJ IDEA.
 * User: Jaewoo Kim
 * Date: 2002. 9. 30.
 * Time: 오전 11:31:21
 * To change template for new class use
 * Code Style | Class Templates options (Tools | IDE Options).
 */
package anagram;

import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Anagram {
    private Map m_dictionary;

    public Anagram() {
        m_dictionary = new HashMap();
    }

    public String sortWord( String source ) {
        StringBuffer strBuf = new StringBuffer();
//        if ( "ba".equals( source ) )
//            output = "ab";
//        else if ( "bca".equals( source ) )
//            output =  "abc";

        List characterList = new ArrayList();
        for( int i = 0; i < source.length(); i++ ) {
            characterList.add( source.substring( i, i + 1 ) );
        }
        Collections.sort( characterList );
        for( Iterator i = characterList.iterator(); i.hasNext(); ) {
            String s = (String) i.next();
            strBuf.append( s );
        }

        return strBuf.toString();
    }

    public void addToDictionary( String word ) {
        String sortedWord = this.sortWord( word );
        List list = (List) m_dictionary.get( sortedWord );

        if( null == list ) {
            list = new ArrayList();
            m_dictionary.put( sortedWord, list );
        }

        list.add( word );
    }

    public String getDictionaryStr() {
        return m_dictionary.toString();
    }

    public void printResult() {
        for( Iterator i = m_dictionary.values().iterator(); i.hasNext(); ) {
            List list = (List) i.next();
            boolean first = true;
            for( Iterator listIterator = list.iterator(); listIterator.hasNext(); ) {
                if ( !first ) {
                    System.out.print( "," );
                }
                String word = (String) listIterator.next();
                System.out.print( word );
                first = false;
            }
            System.out.println( "" );
        }
    }

    public static void main( String args[] ) {
        long start = System.currentTimeMillis();
        BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) );
        Anagram anagram = new Anagram();
        try {
            String word = reader.readLine();
            while( null != word && !"".equals( word ) ) {
                anagram.addToDictionary( word );
                word = reader.readLine();
            }
        } catch( IOException e ) {
            e.printStackTrace();  //To change body of catch statement use Options | File Templates.
        }
        System.err.println( "Elapsed: " + String.valueOf( System.currentTimeMillis() - start ) );
        anagram.printResult();
    }
} 
Retrieved from http://wiki.zeropage.org/wiki.php/ClassifyByAnagram/김재우
last modified 2021-02-07 05:22:53