Skip to content

Commit

Permalink
Shortest Distance Between Words
Browse files Browse the repository at this point in the history
Shortest Distance Between Words HarshCasper#1685
  • Loading branch information
ErzaTitania-2001 authored and JayantGoel001 committed Dec 31, 2020
1 parent 5cc40d7 commit 977d553
Showing 1 changed file with 86 additions and 0 deletions.
86 changes: 86 additions & 0 deletions Java/cp/GC2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/* Given a list of words and two words word1 and word2, find the shortest distance between those two words from the list.
*/
import java.util.*;
class GC2 {
static List < String > arr;
public static void main(String args[]) {
int t = 0;

Scanner sc = new Scanner(System.in);
System.out.println("Enter the list of words " + "\n" + "Words = ");
arr = new ArrayList < > ();

arr.add(sc.nextLine());
while (sc.hasNext()) {
arr.add(sc.nextLine());
if (sc.hasNextInt()) {
t = sc.nextInt();
break;
}

}

List < String > wd = new ArrayList(arr);
while (t > 0) {
String wd1 = sc.next();
String wd2 = sc.next();
System.out.println(" The shortest Distance between " + wd1 + " and " + wd2 + " is : " + shortest_dist(wd, wd1, wd2));
wd = new ArrayList(arr);

t--;
}

}
public static int shortest_dist(List < String > wd, String wd1, String wd2) {
int dist = -1;
List < String > wdcopy = new ArrayList(wd);
List < Integer > ind1 = new ArrayList < > ();
List < Integer > ind2 = new ArrayList < > ();

while (wd.contains(wd1)) {
ind1.add(wd.indexOf(wd1));
//
wd.add(wd.indexOf(wd1), "0");
wd.remove(wd.indexOf(wd1));

}

while (wdcopy.contains(wd2)) {
ind2.add(wdcopy.indexOf(wd2));

wdcopy.add(wdcopy.indexOf(wd2), "0");
wdcopy.remove(wdcopy.indexOf(wd2));
}

for (int i = 0; i < ind1.size(); i++) {
for (int j = 0; j < ind2.size(); j++) {
int d = (int) Math.abs(ind1.get(i) - ind2.get(j));
if (dist == -1)
dist = d;
else if ((dist != -1) && (d < dist))
dist = d;
}
}
return dist;

}
}
/*Sample Input And Output :
* Enter the list of words
Words =
practice
makes
perfect
coding
makes
2
practice
coding
The shortest Distance between practice and coding is : 3
coding
makes
The shortest Distance between coding and makes is : 1
Timple Complexity : O(n)
Space Complexity : O(1)
*/

0 comments on commit 977d553

Please sign in to comment.