Created
February 23, 2018 19:33
-
-
Save 0x1b-xyz/24f64be79183ea0983b5b0471f2abddb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
import java.util.stream.*; | |
import com.google.common.collect.ImmutableMap; | |
/* | |
Given a list of flights (in any order), construct the trip that this list represents. For example, if we have a flight from San Francisco to Los Angeles and a flight from New York City to San Francisco, the trip is "NYC to SFO to LAX". | |
Assumptions: | |
- A city will only be visited once per trip. (you can't go back to a given city after visiting it). | |
- The list will only represent one single trip. | |
# Flights: | |
# ORD -> DNV | |
# SFO -> NYC | |
# LAX -> SFO | |
# NYC -> ORD | |
# | |
# Trip: | |
# LAX -> SFO -> NYC -> ORD -> DNV | |
flights = [("ORD", "DNV"), ("SFO", "NYC"), ("LAX", "SFO"), ("NYC", "ORD")] | |
*/ | |
class Solution { | |
static Map<String,String> flights = ImmutableMap.of("ORD","DNV","SFO","NYC","LAX","SFO","NYC","ORD"); | |
public static void main(String[] args) { | |
String starting = flights.keySet().stream() | |
.filter(x -> !flights.values().contains(x)) | |
.findFirst().get(); | |
String ending = flights.values().stream() | |
.filter(x -> !flights.keySet().contains(x)) | |
.findFirst().get(); | |
List<String> trip = new ArrayList<String>(); | |
trip.add(starting); | |
String dest = flights.get(starting); | |
while (true) { | |
trip.add(dest); | |
if (dest.equals(ending)) | |
break; | |
dest = flights.get(dest); | |
} | |
System.out.println(trip.stream().collect(Collectors.joining(" -> "))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment