ISC practical papers › ISC 2005 › Question 3
Anagrams
ISC 2005 Computer Science Practical, Question 3 · Strings, Recursion
The question
We would like to generate all possible anagrams of a word. For example if the given word is ‘TOP’, there will be 6 possible anagrams:
TOP TPO OTP OPT POT PTO
An anagram must be printed only once. You may output the anagrams in any order.
Also, output the total number of anagrams.
You may assume that the number of letters, N, in the word will be 7 at most, i.e. N < 7
Test your program for the given data and some random data.
SAMPLE DATA:
INPUT: TO OUTPUT: TO OT Total number of anagrams=2
INPUT: LEAN OUTPUT: LEAN LENA LAEN LANE LNAE LNEA ELAN ELNA EALN EANL ENAL ENLA AELN AENL ALEN ALNE ANLE ANEL NEAL NELA NAEL NALE NLAE NLEA Total number of anagrams = 24
Question: ISC 2005 Computer Science Paper 2 (Practical), Question 3, set by the Council for the Indian School Certificate Examinations (CISCE). Solution and video: Vinay Singh.
Java solution
import java.util.*;
class Anagram {
private String word, output;
private int count;
public Anagram(String word) {
this.word = word;
char s[] = word.toCharArray();
output = "";
count = 0;
permute(s, 0);
}
public void permute(char s[], int k) {
if (k == s.length - 1) {
output += new String(s) + "\n";
count++;
} else {
char temp;
for (int i = k; i < s.length; i++) {
if (s[i] == s[k] && i != k)
continue;
temp = s[k];
s[k] = s[i];
s[i] = temp;
permute(s, k + 1);
temp = s[k];
s[k] = s[i];
s[i] = temp;
}
}
}
public String toString() {
return output;
}
public int length() {
return count;
}
}
class ISC2012Q1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("INPUT:");
String word = in.next();
Anagram obj = new Anagram(word);
System.out.println("OUTPUT:\n" + obj);
System.out.println("Total number of anagrams=" + obj.length());
in.close();
}
}
All these solutions in one free book
Pragmatic Solutions to ISC Computer Science Practical Problems collects every program from 2004 to 2021 in a 202-page PDF.