CC-2 : Filter input list of Strings / Search Directory file names by range.
Description:
Given a String array, sort the same alphabetically and then filter the Strings between range of two input Strings and return the result.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| arr1={ "Archie", "Arthur", "Charlie", "Edward", "Freddie", "Noah", "Oliver", "Henry", "Avery", "Leo", "Teddy", "Thomas", "Stephen", "Wallace", "Louis", "Paul", "Logan", "Sonny", "Wilfred"}; Sort above alphabetically and return range of names between “Charlie” (inclusive) and “Teddy” (exclusive). |
Charlie, Edward, Freddie, Henry, Leo, Logan, Louis, Noah, Oliver, Paul, Sonny, Stephen |
| arr1={ "Archie", "Arthur", "Charlie", "Edward", "Freddie", "Noah", "Oliver", "Henry", "Avery", "Leo", "Teddy", "Thomas", "Stephen", "Wallace", "Louis", "Paul", "Logan", "Sonny", "Wilfred"}; Sort above alphabetically and return range of names between “Edward” (Inclusive) and “Leo” (exclusive). |
Edward, Freddie, Henry |
Pseudocode:
| The java method should accept following input parameters: arr (String array), from (start of filter range, inclusive), to(end of filter range, exclusive). |
| Initialize a variable tSet of type TreeSet |
| Using a for loop iterate through arr, using idx as a loop variable with initial value 0 and increment idx till it reaches arr.length-1:
Add arr[idx] to tSet.
|
| At completion of above loop, tSet contains all the unique Strings in arr alphabetically sorted, as TreeSet automatically sorts input elements in their natural order. |
| Use an iterator to access elements from tSet and add the same to String array named retVal. Return retVal. |
Code:
public String[] setSearchDirectory(String[] arr, String from, String to) {
TreeSet<String> tSet=new TreeSet<String>();
for (int idx=0; idx <arr.length; idx++) {
tSet.add(arr[idx]);
}
TreeSet subSet=(TreeSet) tSet.subSet(from, to);
String retVal[]=new String[subSet.size()];
int idx=0;
Iterator<String> itr=subSet.iterator();
while (itr.hasNext()) {
retVal[idx]=itr.next().toString();
idx++;
}
return retVal;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |