logo CodeStepByStep logo

ticketValidation2

Write a method named ticketValidation2 (similar to the previous exercise, ticketValidation) that examines valid tickets to determine which field is which. Your method accepts two parameters: a string representing the name of a file of ticket data, and a field prefix string of interest.

Using the valid ranges for each field, you must determine what order the fields appear on the tickets. The order is consistent between all tickets: if seat is the third field, it is the third field on every ticket, including your ticket.

For example, consider the following ticket data, stored in a file named tickets.txt:

transport class: 0-1 or 4-19
passenger row: 0-5 or 8-19
passenger seat: 0-13 or 16-19

your ticket:
7,1,14

nearby tickets:
7,3,47
40,4,50
55,2,20
38,6,12

Based on the nearby tickets in the above example, the first position must be passenger row, the second position must be transport class, and the third position must be passenger seat. You can conclude that in your ticket, transport class is 12, passenger row is 11, and passenger seat is 13.

Once you work out which field is which, your code should look for the fields on your ticket that start with the given prefix, and return (as a long) the product of multiplying all such values together. In our example, if the prefix were "passenger", you would multiply the values on your ticket for passenger row and passenger seat. So the call of ticketValidation2("tickets.txt", "passenger") would return 11 * 13 or 143.

You may assume that the file exists and is readable, that it follows the format described above, that there will be at least one field, exactly one "your ticket" entry, and at least one "nearby tickets" entry, and that at least one field name will begin with the given prefix.

(This exercise is based on the Advent of Code 2020, day 16.)

Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.