Part III: Are You a Permutation? (3 points) A permutation of a list or string is
ID: 3802483 • Letter: P
Question
Part III: Are You a Permutation? (3 points)
A permutation of a list or string is a rearrangement of the elements in the list or string. For example, given the list [1,2,3,4], permutations would include [2,4,1,3], [4,3,1,2] and [3,2,4,1]. Likewise, given the string ’dome’, permutations would include ’edom’, ’emod’ and ’mode’.
Write a function permutations() that takes a string argument, opens the file words.txt (provided on Blackboard) and returns a list consisting of all permutations of the string argument found in the file (if any). The original word should not be included in the returned list. The function may return the words in any order inside the list.
Examples:
Function Call
Return Value
[’add’]
[]
Function Call
Return Value
permutations(’veil’)
[’evil’, ’levi’, ’live’, ’vile’]
permutations(’tori’)
[’riot’, ’trio’]
permutations(’dad’)
[’add’]
permutations(’ado’)
[]
Explanation / Answer
COde is as below written in java
public class clsPermutation
{
private void permute(String str, int l, int r)
{
if (l == r)
System.out.println(str);
else
{
for (int i = l; i <= r; i++)
{
str = swap(str,l,i);
permute(str, l+1, r);
str = swap(str,l,i);
}
}
}
public String swap(String a, int i, int j)
{
char temp;
char[] arr = a.toCharArray();
temp = arr[i] ;
arr[i] = arr[j];
arr[j] = temp;
return String.valueOf(arr);
}
}