CC-14 : Make file names unique.
Description:
Given a String array with filenames, make the file names unique by appending numbers to duplicate filenames.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| files={"file","folder","file","file","files"}; | Unique Filenames list : file,folder,file(1),file(2),files |
| files={"file","folder","file","file(2)","file"} | Unique Filenames list : file,folder,file(1),file(2),file(3) |
| files={"file","folder","Image","audio","video"}; | Unique Filenames list : file,folder,Image,audio,video |
Pseudocode:
| The java method should accept following input parameters: filenames(String array). |
| Initialize a variable fileNamesMap of type HashMap |
| Initialize a variable fNameIdx=1, we will use this variable to create and append unique numbers to end of duplicate filenames. |
| Initialize a variable foundfNameIdx=false, we will use this variable to check if we have found a unique name for files with duplicate names. |
| Iterate through filenames using a for loop with idx as a loop variable with initial value 0 and increment idx till it reaches filenames.length-1:
Set foundfNameIdx to false.
If fileNamesMap does not contain key filenames[idx], then put key-value pair filenames[idx] and 1 to fileNamesMap.
Else If fileNamesMap does contain key filenames[idx]:
Append fNameIdx to filenames[idx] and store this value to tempFileName.
If the tempFileName name is not present as key in fileNamesMap:
Put key-value pair tempFileName and 1 to fileNamesMap.
Set filenames[idx] to tempFileName.
Set foundfNameIdx to true.
Else:
Increment fNameIdx by 1.
|
| After above loop completes, filenames contains unique filenames. Return filenames. |
Code:
public String[] hashMapakeFileMamesUnique(String[] fileNames) throws Exception{
HashMap<String,Integer> fileNamesMap=new HashMap<String, Integer>();
int fNameIdx=1; boolean foundfNameIdx=false;
String tempFileName;
for (int idx=0; idx < fileNames.length; idx++) {
foundfNameIdx=false;
if (!fileNamesMap.containsKey(fileNames[idx])) {
fileNamesMap.put(fileNames[idx], 1);
}else {
while (foundfNameIdx==false) {
tempFileName=fileNames[idx]+"("+fNameIdx+")";
if (!fileNamesMap.containsKey(tempFileName)) {
fileNamesMap.put(tempFileName, 1);
fileNames[idx]=tempFileName;
foundfNameIdx=true;
}else {
fNameIdx++;
}
}
}
}
return fileNames;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |