Changing Gender

July 26, 2016

The culture wars have my head spinning so fast that I need a computer to help me out. One day I might say “He is my brother.” and the very next day, speaking about the same person, say “She is my sister.”

Your task is to write a program that changes the gender of the words in a string. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Advertisement

Pages: 1 2

One Response to “Changing Gender”

  1. Similar solution to yours but in Perl… I create the map in three parts – for those words for which you can only map one way (actually they have an alternative mapping elsewhere) – those words for which I can pluralise with “s” and those I can’t…
    By extending the map with the ucfirst and uc versions of the strings – I can then just use a “join map split” to do the translation.

    my %map = qw(
      aunty   uncle  aunties uncles miss    mr     mrs     mr
      dame    sir    lord    lady   lords   ladies);
    
    ## Entries for which we can just add an "s" to pluralize
    my @map_plural_s = qw(
      boy       girl      boyfriend girlfriend father    mother    husband   wife
      son       daughter  brother   sister     sir       madam     uncle     aunt
      male      female    widower   widow
    );
    ## Make all 4 mappings...
    while( my($a,$b) = splice @map_plural_s, 0, 2 ) {
      $map{$a}=$b;
      $map{$b}=$a;
      $map{$a.'s'}=$b.'s';
      $map{$b.'s'}=$a.'s';
    }
    
    ## Entries for which we can't just add an S to make them plural
    my @map_no_plural = qw(
      man woman men women gentleman lady gentlemen ladies his her
    );
    ## Make both mappings...
    while( my($a,$b) = splice @map_no_plural, 0, 2 ) {
      $map{$a}=$b;
      $map{$b}=$a;
    }
    
    ## Now add the ucfirst and uc versions of the words...
    $map{ucfirst $_} = ucfirst $map{$_} foreach keys %map;
    $map{uc $_     } = uc      $map{$_} foreach keys %map;
    
    sub r {
      return join q(), map { $map{$_}||$_ } split m{\b}, shift;
    }
    
    print r( "My Brother's girlfriend is taking HER sister to the movies." );
    

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: