Sunday, October 23, 2011

Code from 10/18

Palindrome

public class Pal {
public static void main(String[] args) {
String word = "Racecar";
word = word.toLowerCase();
boolean ok = true;
for (int n=0; n<=word.length()-1; n++) {
if (word.charAt(n) == word.charAt(word.length() - n - 1)) {
}
else {
ok = false;
break;
}
}
if (ok) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
}
view raw Pal.java hosted with ❤ by GitHub

Anagrams...

So we didn't finish this one in recitation and on reflection it's really way too long... Here's a solution someone emailed me (sorry I forgot to ask you if you were OK with me sharing this if you mind I'll take it down) (also I reformatted a little)
public class Anagram {
public static void main(String[] args) {
String a = IO.readString();
String b = IO.readString();
boolean anagram = true;
int count = 0;
if (a.length()==b.length()) {
for ( int i = 0 ; i < a.length() ; i++) {
char x = a.charAt(i);
for ( int j = 0 ; j < b.length() ; j++ ) {
if (x==b.charAt(j)) {
count++;
}
if (x==a.charAt(j)) {
count--;
}
}
if (count!=0) {
anagram = false;
}
}
} else {
anagram = false;
}
System.out.println(anagram);
}
}
view raw Anagram.java hosted with ❤ by GitHub
See you Tuesday!

No comments:

Post a Comment