SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Program Logic And Indefinite Loops
Exercise:
Exercises
Question:14 | ISBN:9780136091813 | Edition: 2

Question

Write a method named numUnique that takes three integers as parameters and returns the number of unique integers among the three. For example, the call numUnique(18, 3, 4) should return 3 because the parameters have three different values. By contrast, the call numUnique(6, 7, 6) should return 2 because there are only two unique numbers among the three parameters: 6 and 7.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

// package indefinite_loops;

public class UniqueNumber {

    public static int numUnique(int a, int b, int c) {

        int[] arr = new int[3];

        arr[0] = a;
        arr[1] = b;
        arr[2] = c;
        // loop over the elements by taking j as initial index and k as next index
        int uniques = 0;
        for (int j = 0; j < arr.length; j++) {

            for (int k = j + 1; k < arr.length; k++) {

                // if values in index j and index k are same we change default value to be
                // false;

                if (k != j && arr[k] != arr[j])
                    uniques++;

            }
        }

        return uniques;

    }

    public static void main(String args[]) {

        System.out.println("number of unique values are: " + numUnique(4, 4, 8));

    }

}
Output:

number of unique values are: 2

 

0 0

Discussions

Post the discussion to improve the above solution.