Reputation: 323
need another hint from you:
I have a list with system-paths in it :
C:\System\local\something\anything
C:\System\local\anywhere\somewhere
C:\System\local\
C:\System\
C:\something\somewhere
My reference path is :
C:\System\local\test\anything\
Now i am looking for the most similar system path, the result should be
Result from the list :
C:\System\local\
So what's to do ?
Upvotes: 0
Views: 232
Reputation: 718678
Well your example is actually showing that the answer is the longest system path that the given path starts with. This can be computed as follows:
String[] systemPaths = ...
String path = ...
String bestMatch = null;
for (String candidate : systemPaths) {
if (path.startsWith(candidate) &&
(bestMatch == null || bestMatch.length() < candidate.length())) {
bestMatch = candidate;
}
}
This assumes that the system paths all end with a file separator, and that you want to do the matching case sensitively. If not, the adjustments should be obvious.
Upvotes: 0
Reputation: 44439
A possible solution:
Loop trough your list of paths, split them on the backslash character and then loop trough every value of the resulting array. See how long it equals the values of your reference path and give them a score accordingly. My example is a little rough, but you can adjust it accordingly.
public class PathScore {
public String Path;
public int Score;
}
public class Systempaths {
public static void main(String[] args) {
new Systempaths();
}
public Systempaths() {
String[] paths = new String[5];
paths[0] = "C:\\System\\local\\something\\anything";
paths[1] = "C:\\System\\local\\anywhere\\somewhere";
paths[2] = "C:\\System\\local";
paths[3] = "C:\\System\\";
paths[4] = "C:\\something\\somewhere";
String ref = "C:\\System\\local\\test\\anything";
String[] reference = ref.split("\\\\");
List<PathScore> scores = new ArrayList<>();
for (String s : paths) {
String[] exploded = s.split("\\\\");
PathScore current = new PathScore();
current.Path = s;
for (int i = 0; i < exploded.length; i++) {
if (exploded[i].equals(reference[i])) {
current.Score = i + 1;
} else {
// Punishment for paths that exceed the reference path (1)
current.Score = i - 1;
break;
}
}
scores.add(current);
}
for (PathScore ps : scores) {
System.out.printf("%s:\t%d\n", ps.Path, ps.Score);
}
}
}
Outputs:
C:\System\local\something\anything: 2
C:\System\local\anywhere\somewhere: 2
C:\System\local: 3
C:\System\: 2
C:\something\somewhere: 0
(1):
I add a small punishment for paths (like C:\System\local\something\anything
) that are too specific and go further than the reference path ("C:\System\local\test\anything"
) allows.
Upvotes: 1
Reputation: 147
Since you have a list of system-paths which is predefined and now you have got a reference path where you need to find out the most similar system path from the list,my take would be a match between the reference path and against each item on the system-path list. Regex based comparisons would be easier.
Upvotes: 0