THINK FIRST·CODE LATER

← All labs

Three ways to find a duplicate

Problem

Does an array contain a repeated value? Write DuplicateCheck with three methods that answer the question and count their basic steps:

  • byPairs — compare every pair (count the comparisons; stop at the first duplicate);
  • bySorting — sort a copy, then compare neighbours (count the neighbour comparisons);
  • byHashing — add each value to a HashSet and stop when add returns false (count the set operations).

Input: n d. Build a[i] = 2i + 1; if 0 < d < n, set a[d] = a[0] so that position d repeats the first value (d = −1 means no duplicate).

For the input

1000 -1

the program prints

pairs:   false after 499500 comparisons
sorting: false after 999 neighbour comparisons (plus the sort)
hashing: false after 1000 set operations
All three agree: true
Worst case for pairs with n = 1000: 499500

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d6-6-data-1.txt

1000 -1
What your program must print for d6-6-data-1.txt
pairs:   false after 499500 comparisons
sorting: false after 999 neighbour comparisons (plus the sort)
hashing: false after 1000 set operations
All three agree: true
Worst case for pairs with n = 1000: 499500

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d6-6-data-1.txt

Windows PowerShell does not understand <:

Get-Content d6-6-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.