Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Please update this java code so 1. A scanner can be used to import the files. Then compute and test with a randomly generated array

Please update this java code so 1. A scanner can be used to import the files. Then compute and test with a randomly generated array instead of a file. Compute all possible distinctive pair of values from an an array. [A,B,C, A]

A,B

A,C

B,C

- i.e. (A,B)==(B,A)

(A, A) is not valid

hint: sort the array first

Example: input [1, 2, 3, 2, 3, 4, 3] result 4 (with distinct pairs) and 8 (with symmetric pairs import java.util.Arrays; import java.util.HashMap; import java.util.Map;

public class Exercise8 {

public static void main(String[] args) { In in = new In(args[0]); int[] values = in.readAllInts(); StdOut.println(countNumberOfPairs(values));

// Tests int[] values1 = {1, 2, 4, 1, 2, 1, 2, 4, 5, 1, 2, 4, 5, 1, 2 ,5, 6, 7, 7, 8, 2, 1, 2, 4, 5}; StdOut.println("Equal pairs 1: " + countNumberOfPairs(values1) + " Expected: 49");

int[] values2 = {1, 1, 1}; StdOut.println("Equal pairs 2: " + countNumberOfPairs(values2) + " Expected: 3"); }

// O(n lg n) solution private static int countNumberOfPairs(int[] values) { Arrays.sort(values);

int count = 0; int currentFrequency = 1;

for (int i = 1; i < values.length; i++) { if (values[i] == values[i - 1]) { currentFrequency++; } else { if (currentFrequency > 1) { count += (currentFrequency - 1) * currentFrequency / 2; currentFrequency = 1; } } }

if (currentFrequency > 1) { count += (currentFrequency - 1) * currentFrequency / 2; }

return count; }

// O(n) solution private static int countNumberOfPairs2(int[] values) {

Map valuesMap = new HashMap<>(); int equalNumbersCount = 0;

for(int i = 0; i < values.length; i++) { int count = 0; if (valuesMap.containsKey(values[i])) { count = valuesMap.get(values[i]); } count++; valuesMap.put(values[i], count); }

for(int numberKey : valuesMap.keySet()) { if (valuesMap.get(numberKey) > 1) { int n = valuesMap.get(numberKey); equalNumbersCount += (n - 1) * n / 2; } }

return equalNumbersCount; }

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Fundamentals Of Database Systems

Authors: Ramez Elmasri, Sham Navathe

4th Edition

0321122267, 978-0321122261

More Books

Students also viewed these Databases questions

Question

2. Do the same for your favorite female film character.

Answered: 1 week ago