Friday, February 27, 2009

Java Problem 19

Here is the solution for Problem number 19.

/*
* 19. Write a Java class called IsPalindrome, which
* defines a main() method that asks the user to enter
* a String s, and displays whether or not s is a
* palindrome. A palindrome is a String which reads the
* same forwards and backwards, such as "laval" or
* "stressed desserts".
*
* Code taken from my previous solution of problem #21
*
* @author obispo
*/

import javax.swing.*;
import java.text.*;
class IsPalindrome {
public static void main( String[] args ) {
String s1, s2;
int result = 0, len, index1, index2;

s1 = JOptionPane.showInputDialog(null, "Enter a string:");

for (index1 = 0, index2 = s1.length() - 1; index1 < index2; index1++, index2--) {
if (s1.charAt(index1) != s1.charAt(index2)) {
result = -1;
break;
}
}

if (result == 0) {
JOptionPane.showMessageDialog(null, "Palindrome !");
} else {
JOptionPane.showMessageDialog(null, "Not Palindrome !");
}
}
}

Java Problem 21

The next problem I tried to solved was problem 21.


/*
* 21. Write a Java class called Equals, which defines a
* main() method that asks the user to enter two Strings s1
* and s2, and displays whether or not s1 and s2 are equal.
* Two Strings are equal if they are of the same length
* and the same characters appear in the same positions.
* You MUST NOT use any of the methods defined in the String
* class other than charAt() and length().
*
* @author obispo
*/

import javax.swing.*;
import java.text.*;
class Equals {
public static void main( String[] args ) {
String s1, s2;
int result = 0, len, index;

s1 = JOptionPane.showInputDialog(null, "Enter first string:");
s2 = JOptionPane.showInputDialog(null, "Enter second string:");

len = s1.length();
if (len != s2.length()) {
result = -1;
} else {
for (index = 0; index < len; index++) {
if (s1.charAt(index) != s2.charAt(index)) {
result = -1;
}
}
}

if (result == 0) {
JOptionPane.showMessageDialog(null, "Equal !\n" +
s1 + " == " + s2);
} else {
JOptionPane.showMessageDialog(null, "Not Equal !\n" +
s1 + " != " + s2);
}
}
}

Java Problem 25

So I picked the last problem first. And here's my take...

/**
* 25.Write a Java class called CountWords, which defines
* a main() method that asks the user to
* enter a String s, and displays the number of words in s.
* A word is delimited by one or many space
* characters. You MUST NOT not use any of the methods defined in
* the String class other than
* charAt() and length(). In addition, you MUST NOT use the
* StringTokenizer class.
*
* @author obispo
*/
import javax.swing.*;
import java.text.*;

class CountWords {
public static void main( String[] args ) {
String s;
int words = 0, index, len, notspace = 0;

s = JOptionPane.showInputDialog(null, "Enter string:");
s += " ";
len = s.length();
for (index = 0; index < len; index++) {
if (s.charAt(index) != ' ') {
notspace = 1;
} else {
if (notspace == 1) words++;
notspace = 0;
}
}

JOptionPane.showMessageDialog(null, "Word Count: " + words);
}
}

Java Problems

I have found these problems being posted from a certain forum. It has been two years or more since I have coded in Java so I gave it a try and shared my solutions at the forum. I'll just post it here too. Here are the problems...

Problems:
1. Write a Java class called Factorial which defines a main() method that asks the user to enter a positive integer n and displays the factorial of n. The factorial of an integer n, denoted n!, is defined as n * (n-1) * (n-2) * ... * 1 (but note that 0! is 1).

2. Write a Java class called Fibonacci which defines a main() method that asks the user to enter a positive integer n, and computes the nth Fibonacci number. The nth Fibonacci number is defined by this formula:
o 0th Fibonacci number: 0
o 1st Fibonnaci number: 1
o nth Fibonacci number (for n >= 2): (n-1)th Fibonacci number + (n-2)th Fibonacci number
3. Write a Java class called CheckPrimality which defines a main() method that asks the user to enter a positive integer n, and displays whether or not n is a prime number. A prime number is an integer which cannot be divided evenly except by 1 and itself.

4. Write a Java class called Power which defines a main() method that asks the user to enter a double base and a positive integer exponent, and displays base to the power of exponent. You may assume that base and exponent are not both 0. You must write the computation yourself; in other words, you MUST NOT use the Math.pow() method.

5. Write a Java class called CountDigits which defines a main() method that asks the user to enter a positive integer n, and displays how many digits are in n.

6. Write a Java class called Contains which defines a main() method that asks the user to enter a String s and a character c, and displays whether or not c occurs in s. You MUST NOT use any methods defined in the String class other than chartAt() and length().

7. Write a Java class called CountOccurrences which defines a main() method that asks the user to enter a String s and a character c, and displays the number of times c occurs in s.

8. Write a Java class called CheckDuplicates, which defines a main() method that asks the user to enter a String s, and displays whether or not any character in s occurs more than once.

9. Write a Java class called MostOftenOccurring which takes a String s and displays the character which occurs most often in String s. If there is a tie, display the character which occurs first in s among those which occur most often.

10. Write a Java class called ToUpperCase which defines a main() method that asks the user to enter String s and displays a new String which contains exactly the same characters as s in the same order, except that all lower-case letters occurring in s are replaced by their upper-case equivalents in the result String. You MUST NOT use any methods defined in the String class other than charAt() and length().

11. Write a Java class called IsAlphabetPermutation, which defines a main() method that asks the user to enter a String s and displays whether or not s is a permutation of the upper case letters in the alphabet.

12. Write a Java class called OccursHere, which defines a main() method that asks the user to enter two Strings, superString, and subString, as well as a positive integer position, and displays whether or not subString occurs in superString at position position. You may assume that position is within the range [0, superString.length() - 1]. You MUST NOT use any methods defined in the String class other than charAt() and length().

13. Write a Java class called OccursAnywhere, which defines a main() method that asks the user to enter two Strings, superString and subString, and displays whether or not subString occurs anywhere in superString. You MUST NOT use any method defined in the String class other than chartAt() and length().

14. Write a Java class called Substring, which defines a main() method that asks the user to enter a String s, a positive integer position, and a positive integer number, and displays a new String formed by taking the number characters of s starting at position position. If there are less than number characters between position and the end of s, your main() method should display a new String formed by these characters. You MUST NOT use any methods defined in the String class other than charAt() and length().

15. Write a Java class called RemoveAll, which defines a main() method that asks the user to enter a String s and a character c, and displays a new String consisting of all the characters in s in the order in which they appear in s, but with all occurrences of c removed. You MUST NOT use any of the methods defined in the String class other than charAt() and length().

16. Write a Java class called NumberConsecutiveOccurrences, which defines a main() that asks the user to enter a String s, a character c, and an integer position, and displays the number of occurrences of c starting at position position in s. For example, if s is "abbbbbaaa", c is 'b', and position is 1, then your main() method will display 5, as there are 5 consecutive occurrences of 'b' starting at position 1. You may assume that position is within the range [0, s.length() - 1]. You MUST NOT use any methods defined in the String class other than charAt() and length().

17. Write a Java class called MaxConsecutiveOccurrences, which defines a main() method that asks the user to enter a String s and a character c, and displays the position in s at which the longest series of consecutive occurrences of c occurs. If there is a tie between two positions, you should return the lowest position. You MUST NOT use any of the methods defined in the String class other than charAt() and length().

18. Write a Java class called Reverse, which defines a main() method that asks the user to enter a String s, and displays a new String consisting of the characters in s in the reverse order. You MUST NOT use any methods defined in the String class other than charAt() and length().

19. Write a Java class called IsPalindrome, which defines a main() method that asks the user to enter a String s, and displays whether or not s is a palindrome. A palindrome is a String which reads the same forwards and backwards, such as "laval" or "stressed desserts".

20. Write a Java class called KillWhiteSpace, which defines a main() method that asks the user to enter a String s, and displays a new String consisting of all the characters in s, but with the leading and trailing white space removed. In addition, every sequence of spaces within the String is reduced to one space only. You MUST NOT use any methods defined in the String class other than charAt() and length().

21. Write a Java class called Equals, which defines a main() method that asks the user to enter two Strings s1 and s2, and displays whether or not s1 and s2 are equal. Two Strings are equal if they are of the same length and the same characters appear in the same positions. You MUST NOT use any of the methods defined in the String class other than charAt() and length().

22. Write a Java class called DestroyAllOccurrences, which defines a main() method that asks the user to enter two Strings superString and subString, and displays a new String consisting of all characters in superString with all occurrences of subString deleted. You MUST NOT use any of the methods defined in the String class other than charAt() and length().

23. Write a Java class called SubSet, which defines a main() method that asks the user to enter two Strings superString and subString, and displays whether or not all the characters of subString occur anywhere in superString. You MUST NOT use any of the methods defined in the String class other than charAt() and length().

24. Write a Java class called AppearInOrder(), which defines a main() method that asks the user to enter two Strings subString and superString, and displays whether or not all the characters of subString appear in order in superString. You MUST NOT use any of the methods defined in the String class other than charAt() and length().

25. Write a Java class called CountWords, which defines a main() method that asks the user to enter a String s, and displays the number of words in s. A word is delimited by one or many space characters. You MUST NOT not use any of the methods defined in the String class other than charAt() and length(). In addition, you MUST NOT use the StringTokenizer class.

Monday, November 10, 2008

Perl: Rounding off Decimal Digits


#!/usr/bin/perl
# Filename: kb_converter.pl
# Description: Convert values from Bytes to KiloBytes
use strict;

my $val;
my $argc = @ARGV;
if($argc == 1) {
$val = shift;
} else {
$val = 12345;
}

# 1KB = 1024Bytes
my $val_kb = $val / 1024;
my $val_kb_rounded = sprintf("%.2f", $val / 1024);
print "Not Rounded Answer:\n$val Bytes = $val_kb KB\n";
print "Rounded Answer:\n$val Bytes = $val_kb_rounded KB\n";

Wednesday, August 13, 2008

The Unix/Linux 'search' command

How to find files in Linux or Unix using 'find'


The 'find' command is very effective in searching for files in my Unix or Linux box. Here's how you do it:

# find <path> -name "<filename>" -print

Example 1: Let us search for the file 'sshd' from the root('/') directory.

# find / -name "sshd" -print
./usr/sbin/sshd
./usr/src/etc/pam.d/sshd
./usr/src/etc/rc.d/sshd
./usr/src/secure/usr.sbin/sshd
./etc/pam.d/sshd
./etc/rc.d/sshd
#

So, there it is, the 'sshd' file can be found from those six different locations.

Searching a File containing a particular text string in Unix or Linux


Again, I use the 'find' command for this. The syntax is as follow:

# find <path> -exec grep "<search_string>" '{}' \; -print

Example 2: Let us search for files that contains the string "dhclient_start" from the etc('/etc') directory.

# find /etc -exec grep "dhclient_start" '{}' \; -print
start_cmd="dhclient_start"
dhclient_start()
/etc/rc.d/dhclient
#

The output tells us that it has only found one file that contains the string we were looking for. It can be found inside the file '/etc/rc.d/dhclient'.

This is my simplified 'search' command


I tried to simplify the find command by creating a shell script which will accept only three parameters:

# search <search_path> <search_type> <search_string>

Where:
search_path:
ex. /usr/local
search_type:
file - search for a file/directory
content - search for a file content
search_string:
- the filename or the file content you want to search

Example 3: Let us search for the file 'sshd' from the root('/') directory.

# search / file "sshd"
./usr/sbin/sshd
./usr/src/etc/pam.d/sshd
./usr/src/etc/rc.d/sshd
./usr/src/secure/usr.sbin/sshd
./etc/pam.d/sshd
./etc/rc.d/sshd
#

The output is the same with Example 1 but as you notice we only have three parameters in our command which makes is simpler to understand.

Example 4: Let us search for files that contains the string "dhclient_start" from the etc('/etc') directory.

# search /etc content "dhclient_start"
start_cmd="dhclient_start"
dhclient_start()
/etc/rc.d/dhclient
#

The output is also the same with Example 2 and again the command only take three parameters.

Here is the script, you can copy and paste this script and save it to a file named 'search'. After saving the file, change the permission of the file to '+x' and copy it to '/usr/local/bin'.

#!/bin/sh
# Filename: search
# Description: A simplified find command
# Author: Obispo

searchPath=""
searchType=""
searchString=""
findcmd="/usr/bin/find"
scriptUsage="
Usage:
${0} <search_path> <search_type> <search_string>
search_path:
ex. /usr/local
search_type:
file - search for a file/directory
content - search for a file content
search_string:
- the filename or the file content you want to search
"

# Script Usage
display_usage()
{
echo "${scriptUsage}"
exit 1
}

if [ "${1}" = "" ]; then
display_usage
elif [ "${2}" = "" ]; then
display_usage
elif [ "${3}" = "" ]; then
display_usage
else
searchPath=${1}
searchType=${2}
searchString=${3}
fi

case "${searchType}" in
file)
${findcmd} ${searchPath} -name "${searchString}" -print
;;
content)
${findcmd} ${searchPath} -exec grep "${searchString}" '{}' \; -print
;;
*)
display_usage
;;
esac

exit 0


Enjoy!


Thursday, July 24, 2008

English to Bisaya Language Translator

Hmmm... I have successfully created an English to Bisaya Language Translator about 3 years ago, as a project in my Natural Language Processing (NLP) subject and I developed it using Visual Basic 6. Luckily last weekend, as I tried to clear some trash in my room, I found the Object Schema documentation of my project!

This leads me to an idea of creating an online English to Bisaya Language Translator project using PHP... Do you think this is a great idea? I have seen that the number of tourist people here in Cebu and in some parts of the Philippines is growing and I think this online language translator can help them learn about our Bisayan or Cebuano language.