Word Potential Sorting Program in Java and Python
Word potential sorting program with algorithm, explanation, Java solution and simple Python solution for ISC students.
Question:
Accept a sentence terminated by period, question mark or exclamation mark. The potential of a word is the sum of alphabet values where A = 1, B = 2, ..., Z = 26. Display each word with its potential and arrange the words in ascending order of potential.
Algorithm:
Step 1: Start.
Step 2: Accept the sentence as a string.
Step 3: Remove punctuation marks from tokenization and extract each word using StringTokenizer.
Step 4: Store each word in a word array.
Step 5: For every word, convert it to uppercase and scan its characters.
Step 6: For each alphabet, add ch - 64 to the potential counter.
Step 7: Store each potential in a parallel integer array.
Step 8: Use nested loops to compare potential values.
Step 9: When potentials are out of order, swap both the potential values and corresponding words.
Step 10: Display the sorted words in their new order.
Step 11: Stop.
Explanation:
The helper method for potential calculation scans one word at a time. Each character is converted to uppercase so that both small and capital letters can be handled by the same ASCII calculation.
The word array and potential array are parallel arrays. The potential stored at index i belongs to the word stored at index i.
During sorting, both arrays must be swapped together. If only the potential values are swapped, the word order would become incorrect.
The nested loop compares every word potential with later potentials. Smaller potential values are moved toward the front, producing ascending order.
The final output uses the sorted word array, not the original sentence. This is why punctuation is removed during tokenization and only clean words are printed.
The program is more than a simple alphabetical sort because every word first receives a numeric potential. The potential is calculated by adding alphabet values of its letters, usually A as 1, B as 2, and so on. Once each word has a potential, sorting is performed on these numeric values. If two words have the same potential, the program may preserve their original order or apply the condition stated in the question. This helps students see how strings can be transformed into numerical keys before sorting.
Java Program:
/**
* The class WordPotential inputs a sentence and arranges the words
* in ascending order of their potential
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
* @ISC Computer Science Practical Specimen Paper - Question 2
*/
import java.util.*;
class WordPotential
{
int findPotential(String s) // Function to find potential of a word
{
s = s.toUpperCase();
int p = 0, l = s.length();
char ch;
for(int i=0; i<l; i++)
{
ch = s.charAt(i);
p = p + (ch-64); // if ch = 'A', then 'A'-64 = ASCII value of 'A' - 64 = 65-64 = 1
}
return p;
}
// Function to sort the words in ascending order of their potential
void sortPotential(String w[], int p[])
{
int n = w.length, t1 = 0;
String t2 = "";
for(int i=0; i<n-1; i++)
{
for(int j=i+1; j<n; j++)
{
if(p[i]>p[j])
{
t1 = p[i];
p[i] = p[j];
p[j] = t1;
t2 = w[i];
w[i] = w[j];
w[j] = t2;
}
}
}
printResult(w,p);
}
void printResult(String w[], int p[]) // Function to print the final result
{
int n = w.length;
String ans = "";
for(int i=0; i<n; i++)
{
ans = ans + " " + w[i];
}
ans = ans.trim();
System.out.println("\nOutput\t\t : \t"+ans);
}
public static void main(String args[])
{
WordPotential ob = new WordPotential();
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence : \t");
String s = sc.nextLine();
StringTokenizer str = new StringTokenizer(s," .,?!");
int n = str.countTokens();
String words[] = new String[n];
int potential[] = new int[n];
for(int i=0; i<n; i++)
{
words[i] = str.nextToken(); // Saving words one by one in an array
potential[i] = ob.findPotential(words[i]); // Saving potential of every word
}
// Printing the words along with their potential
System.out.print("\nPotential\t : \t");
for(int i=0; i<n; i++)
{
System.out.println(words[i]+"\t= "+potential[i]);
System.out.print("\t\t\t");
}
ob.sortPotential(words,potential);
}
}Equivalent Python Program:
# Read the text input and split or scan it according to the question requirement.
# Loops process each word/character and update counters or result strings.
# Display the final text result after sorting, checking or rearranging is complete.
sentence = input("Enter a sentence: ")
clean = ""
for i in range(len(sentence)):
ch = sentence[i]
if ch == '.' or ch == '?' or ch == '!':
clean = clean + " "
else:
clean = clean + ch
words = clean.split()
potential = []
for word in words:
total = 0
upper = word.upper()
for i in range(len(upper)):
ch = upper[i]
if ch >= 'A' and ch <= 'Z':
total = total + ord(ch) - 64
potential.append(total)
print("POTENTIAL:")
for i in range(len(words)):
print(words[i], "=", potential[i])
for i in range(len(words) - 1):
for j in range(i + 1, len(words)):
if potential[i] > potential[j]:
temp = potential[i]; potential[i] = potential[j]; potential[j] = temp
t = words[i]; words[i] = words[j]; words[j] = t
print("OUTPUT:")
for i in range(len(words)):
print(words[i], end=" ")
print()Output:
Leave a Reply
Your email address will not be published. Comments are reviewed before appearing publicly.