Another programming question

SkyHog

Touchdown! Greaser!
Joined
Feb 23, 2005
Messages
18,433
Location
Castle Rock, CO
Display Name

Display name:
Everything Offends Me
Techies:

I have been given an assignment, and I can't even fathom a way to figure it out. Basically, I need to take a string, and determine whether or not each character is a consonant or a vowel.

I don't want code, please, PLEASE don't give me code. I'm just looking for a starting point...I am completely lost.

edit: disregard, I just thought of a way - I'll just compare each letter to a series of constants within a loop to determine if the letter is a vowel. If its not, it must be a consonant.
 
Last edited:
Nick,

How about 2 constant strings one of all the consonants one with all the vowels.

Pick out each letter one at a time and see if it is in either string and count it.

Joe

edit: Another option is to test if the character is a letter and then just have the vowel string (it's shorter)
 
Hey - that will work better, Joe. That will help determine if its an illegal character too!

We were on similar thought patterns tho.

Now time to go to school and see how badly I bombed my precalc test last Tuesday. :(
 
Areeda said:
Nick,

How about 2 constant strings one of all the consonants one with all the vowels.

Pick out each letter one at a time and see if it is in either string and count it.

Joe

edit: Another option is to test if the character is a letter and then just have the vowel string (it's shorter)
That will work but it is not nearly as efficient as simply testing the smaller group. (By a factor of up to 20 times less efficient)

You have 1 set of letters A-Z with two subsets, Constanants (20 members) and vowels (6 members) (if you include Y).

There is no need to test for inclusion in constanants - non-inclusion in vowels means mandatory inclusion in constanants.

So you iterate thru the characters in the string and test for inclusion against 6 characters only. Don't forget to break out of the vowel test when a match is found.
 
Oops, sorry, I misread what you're saying - you're talking about using an InStr function against a string of consts or vowels. I agree, easier code - but again you still only need to test for vowel inclusion.
 
define an array of vowels a e i o u (don't know how to handle the sometimes "y" without more thought and grammatic rules which might determine when "y" is a vowel

parse your string and compare each letter to the vowel array.

if Character x = vowel array element, then vowel, else not_vowel, and either assume it's a consonant, or create consonant array to check against to eliminate punctuation

or ... load up an ascii chart, build truth tables for vowels and consonants. Compare the ascii value of each character in your string against your table
 
Greebo said:
Oops, sorry, I misread what you're saying - you're talking about using an InStr function against a string of consts or vowels. I agree, easier code - but again you still only need to test for vowel inclusion.
If you assume input only contains alphabetic characters. I always give extra points for error checking.

As an old assembly language programmer I used to care about efficiency but Microsoft proved that's not necessary for successful programming:dunno:

OK Nick post your code when it's done and we can pick holes in it for fun.

Joe
 
Areeda said:
If you assume input only contains alphabetic characters. I always give extra points for error checking.
Fair point...fair point...

As an old assembly language programmer I used to care about efficiency but Microsoft proved that's not necessary for successful programming:dunno:
Fair point...fair point...

OK Nick post your code when it's done and we can pick holes in it for fun.
Fun fun! :)
 
Code will be written at work tonight, its my new way to pass time. For fun, if anyone else wants to do it (please, please don't post the code until after I do, so that it at least looks like I'm not cheating ;)) here's the assignment, it might be fun for everyone to pick apart each other's code :D:

HAHA - I just reread it, and he gives the way away. I'm an idiot.

teacher said:
Write a class called StringMethods that contains a method called "toRovarSprak" which takes a String parameter and translates it to a type of Swedish piglatin that follows these simple rules:

* If a letter in the input is anything else than a consonant, that letter (character) is just copied to the output.
* If a character is determined to be a consonant, that letter is copied to the output, then immediately followed by an 'o', and another copy of the original character.

So an example translation of the String "hello there", would be "hohelollolo tothoherore", and "andree" is "anondodroree". You can use the following method to determine if a character is a consonant or not:
Code:
  public static boolean isConsonant ( char ch ) {
    String _vowels = "aoueiy";
    return Character.isLetter ( ch )
	&& _vowels.indexOf ( Character.toLowerCase ( ch ) ) == -1;
  }
The main method should only contain the code to ask the user for an input string, and then pass that string to your toRovarSprak method for a translation. Here's an example output of my program running:

Rövarspråk - Translator
Please enter a text to translate: how come this assignment is so easy?
Translated: hohowow cocomome tothohisos
asossosigognonmomenontot isos soso easosy?

Note that your program only needs to deal with lower case input letters.
Cool
In ancient time (well, at least before the fall of the roman empire), Julius Caesar used a cipher to send encrypted messages to his generals in the field to minimize the risk that some uninvited spy would find out what the message was. The caesar cipher (so named for obvious reasons) is a very simple cipher, that basically takes the alphabet and rotates it with a certain number of letters. Here's an example:

ABCDEFGHIJKLMNOPQRSTUVWXYZ - Original Alphabet
DEFGHIJKLMNOPQRSTUVWXYZABC - "Encrypted alphabet"

Using the above keys, I can translate the a message, say for example "HELP", by using the corresponding character in the lower alphabet hence getting the encoded string "KHOS". Your job is to write a method named "CasesarEncryption", that takes a String to apply the encryption on, and returns the encrypted string to teh calling method.
 
SkyHog said:
For fun, if anyone else wants to do it (please, please don't post the code until after I do, so that it at least looks like I'm not cheating ;))

What language are you using, Nick? For fun, I propose this: let's get posts from the other programmers out here of source code to do your little assignment in as many programming languages as possible. ;-) php, python, assember, T-SQL, pascal, cobol, assembler, fortran, RPG, perl, etc.
 
Troy Whistman said:
What language are you using, Nick? For fun, I propose this: let's get posts from the other programmers out here of source code to do your little assignment in as many programming languages as possible. ;-) php, python, assember, T-SQL, pascal, cobol, assembler, fortran, RPG, perl, etc.

RPG:hairraise: cobol:rofl: Boy you are older than I thought. What about APL, Algol, or SNOBOL (three of my all time favorites) Hey wait I must be older than I thought too.

Joe
 
I'm using Java for this project. Sounds like fun, a mini coding challenge :D
 
SkyHog said:
I'm using Java for this project. Sounds like fun, a mini coding challenge :D

Here's my entry, in C# .NET. Heavily commented for readability.

Code:
using System;

namespace NicksApp
{
	class StringMethods
	{


		public static bool isConsonant( Char ch ) 
		{
			String vowels = "aoueiy";
			return vowels.IndexOf( ch ) == -1 && Char.IsLetter(ch);
		}

		// Swedish pig-latin conversion
		public static string toRovarSprak( string s ) 
		{
			string outString = "";

			foreach(char c in s)
			{
				if( isConsonant(c)) 
				{
					outString += c + "o" + c;
				}
				else
				{
					outString += c;
				}
			}
			return outString;
		}

		// I know this is named wrong, but the professor said, and I quote:
		// 'Your job is to write a method named "CasesarEncryption", that takes a String'...
		// I don't want to flunk for not following instructions and product specs correctly!  :-)
		public static string CasesarEncryption( String s ) 
		{
			int cypherOffset = 3; // to reproduce the professor's output
			// convert the input, convert to char array, as strings are immutable (can't be changed).
			char[] cypher = s.ToUpper().ToCharArray();
			
			for(int i=0; i <= cypher.GetUpperBound(0); i++) 
			{ // for each letter
				if( Char.IsLetter(cypher[i]) ) // is it a letter?
				{
					// convert to a new ascii value based on offset
					cypher[i] = Convert.ToChar( cypher[i] + cypherOffset );
					// did we 'roll around the top of the alphabet'?
					if( cypher[i] > Convert.ToChar('Z') ) 
					{ // if we rolled around the top, wrap back around to the beginning.
					  	cypher[i] = Convert.ToChar( cypher[i] - 26 );
					}
				}
			}

			return new String( cypher ); // rebuild the char array into a string and return it
		}

		// The main entry point for the application.
		[STAThread]
		static void Main(string[] args)
		{
			string input;
			
			Console.WriteLine( "Rovarsprak Translator" );
			Console.Write("Please enter text to translate: ");
			input = Console.ReadLine();
			Console.WriteLine( "Translated: " + toRovarSprak( input ) );

			Console.WriteLine("\n\nCaesar Encryptor");
			Console.Write("Please enter text to encrypt: ");
			input = Console.ReadLine();
			Console.WriteLine( "Encrypted: " + CasesarEncryption( input )); 

			Console.WriteLine("\n\nPress ENTER to quit...");
			Console.ReadLine();
		}
	}
}
 
here it is in Java, do your worst to me.

I'm gonna write it in BASIC methinks too.
Code:
/*Written by Nick Brennan for CS152 at UNM
 * 
 * This program will convert to PigSweedish.  After a consonant, the letter
 * "o" will be added and then the consonant again.  After vowels and numbers
 * the output will remain the original input
 */
import java.util.Scanner;
public class StringMethods {
	
	
	//andrees code, with different variables, and a constant instead of a variable
	public static boolean testForVowel (char chLetter) {
		final String strVowels = "aeiou";
		return Character.isLetter(chLetter) && strVowels.indexOf (Character.toLowerCase (chLetter)) == -1;
			
	}
	
	public static void main (String[] args){
		Scanner inputScn = new Scanner (System.in);
		String strEnglish;
		String strOutputText = "";
		boolean bLetterCheck;
		
		System.out.println ("Welcome to the Sweedish Translator (sort of)");
		System.out.print ("Please enter an English Phrase: ");
		strEnglish = inputScn.nextLine();
		
		//loop to check to see if each letter is a letter, and if its a vowel.
		for (int x = 0; x < strEnglish.length(); x++){
			bLetterCheck = testForVowel(strEnglish.charAt(x));
			if (!bLetterCheck) {
				strOutputText += (strEnglish.charAt(x));
							}  else {
				strOutputText += (strEnglish.charAt(x)) + "o" + strEnglish.charAt(x);
							}
			
		}
		System.out.println(strOutputText + "bork bork bork!"); //hehe
				
	}

}

edit: oops - forgot about the "Casesar Encryption." doing that now.
 
Last edited:
Troy Whistman said:
Code:
	char[] cypher = s.ToUpper().ToCharArray();

lol - using arrays when they haven't been taught yet! I like it :D
 
The professor's spec doesn't mention what to do with non-letter characters, but it is very specific about what you do with constanants. Your test will assume that if a character is not a vowel, it must be a constanant, but it might not be a letter at all. If I enter:
"There are 123 apples." and get back Tothoherore arore 1o12o23o3 apoppoplolesos" or something like that, the question in my mind is 1o12o23o3 the correct processing?

Were I writing it, I would move the isLetter test out of the testforvowel function, and probably throw an error saying, "Nobody told you to enter non-alphabetic characters!!" ;)
 
Greebo said:
The professor's spec doesn't mention what to do with non-letter characters, but it is very specific about what you do with constanants. Your test will assume that if a character is not a vowel, it must be a constanant, but it might not be a letter at all. If I enter:
"There are 123 apples." and get back Tothoherore arore 1o12o23o3 apoppoplolesos" or something like that, the question in my mind is 1o12o23o3 the correct processing?

Were I writing it, I would move the isLetter test out of the testforvowel function, and probably throw an error saying, "Nobody told you to enter non-alphabetic characters!!" ;)

Well, since it tests to see if its a letter, if someone enters 123, it returns 123.

"Hi 123" returns:
"hohi 123"

But I like error trapping, so I think I'll implement something to yell at the loser.
 
I don't see where you are checking for upper/lower case. Wouldn't your example of "Hi 123" return "HoHi 123". I suggest your strVowels = "aeiouAEIOU" and when you repeat a consonant you convert it to lower case so "Hi 123 Peggy" yields "Hohi 123 Popegoggogyoy" not "HoHi 123 PoPegoggogyoy"
- Aunontot Popegoggogyoy
 
you are correct Aunt Peggy. I had added that to the TODO list, stuff I'll work on throughout the day. Thanks!
 
Greebo said:
My bad, I misread the main logic test.

Its ok - I confused myself writing it a bit. Negative logic screws me up everytime.
 
in c:

#include <stdio.h>

int main( void ){
char c;
while((c=getchar())!='\n'){
putchar(c);
if((a<='c' && c<='z') &&
!(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='y')){
putchar('o');
putchar(c);
}
}
return 0;
}
 
-5 points for everybody who is sequentially comparing against 'a', then 'e', then 'i', etc...

+5 points for whomever hinted above that you should build a table for all ascii values (e.g. an array of boolean, or whatever fits your target language, indexed by ascii code), and set the table values to true/false as appropriate for each ascii code. Then an evaluation of a letter to determine whether it's a vowel or consonant is just a single lookup in this table.

Of course, it depends on whether you're optimizing for performance, storage, or maintainability!
-harry
 
Last edited:
...and this is why I am glad not to be doing Java anymore. In Ruby:

Code:
def toRovarSprak(s)
  vowels = %w(a o u e i y)
  s.scan(/./m) do |c|
    if c == ' ' || vowels.include?(c.downcase)
      print(c)
    else
      print("#{c}o#{c}")
    end
  end
end

Much easier to read, much less time to write...

-Felix
 
wow, I forgot about this thread. This was a fun beginning project. Now I'm all immersed in PilotFreeStuff coding (and have been for much longer than I thought I'd be)....
 
-5 points for everybody who is sequentially comparing against 'a', then 'e', then 'i', etc...

+5 points for whomever hinted above that you should build a table for all ascii values (e.g. an array of boolean, or whatever fits your target language, indexed by ascii code), and set the table values to true/false as appropriate for each ascii code. Then an evaluation of a letter to determine whether it's a vowel or consonant is just a single lookup in this table.

Of course, it depends on whether you're optimizing for performance, storage, or maintainability!
-harry
I guess that's where my XP background shows. Code for readability, test drive your code, and then you can optimize and refactor later if it turns out to be necessary. A lot of optimization ends up being unnecessary.

So, to offset Harry's -5 points, I'll offer +5 for whomever does not build an obscure truth table and instead produces the most readable code :p

-Felix
 
I guess that's where my XP background shows. Code for readability, test drive your code, and then you can optimize and refactor later if it turns out to be necessary. A lot of optimization ends up being unnecessary.

So, to offset Harry's -5 points, I'll offer +5 for whomever does not build an obscure truth table and instead produces the most readable code :p

-Felix


Most readable code:
Code:
//The infinite truth loop:

WHILE 7 > 6
  PRINT "This is true"
WEND
 
I guess that's where my XP background shows.
Just because you write software for the Windows environment doesn't mean that you can't write good code. It's non-traditional, but still technically possible. I think. :)
-harry
 
-5 points for everybody who is sequentially comparing against 'a', then 'e', then 'i', etc...

+5 points for whomever hinted above that you should build a table for all ascii values (e.g. an array of boolean, or whatever fits your target language, indexed by ascii code), and set the table values to true/false as appropriate for each ascii code. Then an evaluation of a letter to determine whether it's a vowel or consonant is just a single lookup in this table.

Of course, it depends on whether you're optimizing for performance, storage, or maintainability!
-harry
+10 points for meeting the needs of the user.

skyhog said:
//The infinite truth loop:

WHILE TRUE
PRINT "This is true"
WEND

While true, is not useful and really doesn't impart knowledge.
 
Just because you write software for the Windows environment doesn't mean that you can't write good code. It's non-traditional, but still technically possible. I think. :)
-harry

I am sure he means Extreme Programming (XP). Not Windows XP.
 
Well, here's my C version, including the truth table:
Code:
#include <stdio.h>
#include <ctype.h>

int isvoweltbl[256];

void initvoweltbl() {
  isvoweltbl['a'] = isvoweltbl['e'] = isvoweltbl['i'] = 1;
  isvoweltbl['o'] = isvoweltbl['u'] = isvoweltbl['y'] = 1;
}

#define ISVOWEL(c) (isvoweltbl[c])

int main() {
  int ch;

  initvoweltbl();
  while ((ch = getchar()) != EOF) {
    if (isalpha(ch) && !ISVOWEL((unsigned char) ch)) {
      putchar(ch);
      putchar('o');
    }
    putchar(ch);
  }
}
It's easier to do in sed, though:
Code:
sed -e 's/[b-df-hj-np-tv-xz]/&o&/g'
-harry
 
I like Harry's approach, much nicer, especially if you are not in an O-O language with a gazillion string handling functions. I think Java supports regular expressions, however, I don't remember how off the top of my head.

A friend of mine recently had an assignment to convert HEX to Decimal in C without using any libraries other than stdio. Took a little thinking, but there is and elegant solution.

~ Christopher
 
in vb..

Select Case
Case a, e, i, o, u

Case Else

End Select
 
in vb..

Select Case
Case a, e, i, o, u

Case Else

End Select

Close...you forgot to define variables a, e, i, o, and u.

Unless you meant:
Case "a", "e", "i", "o", "u"

And IIRC, string comparisons in vb are case sensitive.
 
Yeah, but in most systems, in my experience, the "big" string functions (i.e. the ones that do really cool stuff) are also extremely poor performance wise.

~ Christopher
 
Close...you forgot to define variables a, e, i, o, and u.

Unless you meant:
Case "a", "e", "i", "o", "u"

And IIRC, string comparisons in vb are case sensitive.

Yeah, need quotes and caps, so it's...

Case "A", "a",...
 
Back
Top