Salesman's Travel

Instructions

A traveling salesman has to visit clients. He got each client’s address e.g. “432 Main Long Road St. Louisville OH 43071” as a list.
The basic zipcode format usually consists of two capital letters followed by a white space and five digits. The list of clients to visit was given as a string of all addresses, each separated from the others by a comma, e.g. :
“123 Main Street St. Louisville OH 43071,432 Main Long Road St. Louisville OH 43071,786 High Street Pollocksville NY 56432”.
To ease his travel he wants to group the list by zipcode.

Task

The function travel will take two parameters r (addresses’ list of all clients’ as a string) and zipcode and returns a string in the following format:
zipcode:street and town,street and town,…/house number,house number,…
The street numbers must be in the same order as the streets where they belong.
If a given zipcode doesn’t exist in the list of clients’ addresses return “zipcode:/“

Examples

1
2
3
4
5
6
7
r = "123 Main Street St. Louisville OH 43071,432 Main Long Road St. Louisville OH 43071,786 High Street Pollocksville NY 56432"

travel(r, "OH 43071") --> "OH 43071:Main Street St. Louisville,Main Long Road St. Louisville/123,432"

travel(r, "NY 56432") --> "NY 56432:High Street Pollocksville/786"

travel(r, "NY 5643") --> "NY 5643:/"

My Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

public class Travel {

public static String travel(String r, String zipcode) {
List<String> addressList = Arrays.stream(r.split(","))
.filter(address -> zipcode.equals(getZipcode(address)))
.collect(Collectors.toList());

StringBuilder result = new StringBuilder(zipcode + ":");

StringJoiner joiner = new StringJoiner(",");

for (int i = 0, loop = addressList.size(); i < loop; i++) {
joiner.add(getStreetAndTown(addressList.get(i)));
}

result.append(joiner.toString());
result.append("/");

joiner = new StringJoiner(",");

for (int i = 0, loop = addressList.size(); i < loop; i++) {
joiner.add(getHouseNumber(addressList.get(i)));
}

result.append(joiner.toString());

return result.toString();
}

public static String getZipcode(String address) {
String[] addressArray = address.split(" ");
return addressArray[addressArray.length - 2] + " " + addressArray[addressArray.length - 1];
}

public static String getStreetAndTown(String address) {
StringJoiner streetAndTown = new StringJoiner(" ");
String[] addressArray = address.split(" ");

for (int i = 1, loop = addressArray.length; i < loop - 2; i++) {
streetAndTown.add(addressArray[i]);
}

return streetAndTown.toString();
}

public static String getHouseNumber(String address) {
return address.split(" ")[0];
}
}

Better Solution

전부 정규식이라 이해를 못해 첨부를 못함…


Feeling

정규식도 해야되고 자료구조도 해야되고 스프링도 해야되고 바쁘네…

Share