In: Computer Science
Write a function named hasNValues which takes an array and an integer n as arguments. It returns true if all the elements of the array are one of n different values.
If you are writing in Java or C#, the function signature
is
int hasNValues(int[ ] a, int n)
If you are writing in C or C++, the function signature is
int hasNValues(int a[ ], int n, int len) where len is the length of
a
Note that an array argument is passed by reference so that any change you make to the array in your function will be visible when the function returns. Therefore, you must not modify the array in your function! In other words, your function should have no side effects.
Code
Java
import java.util.Arrays;
public class Main {
public static void main(String[] args)
{
int a[]={1, 2, 2, 1};
int b[]={1, 1, 1, 8, 1, 1, 1, 3, 3};
int c[]={1, 1, 1, 8, 1, 1, 1, 3, 3};
System.out.println(Arrays.toString(a)+" has 2 distinc values:
"+hasNValues(a,2));
System.out.println(Arrays.toString(b)+" has 3 distinc values:
"+hasNValues(b,3));
System.out.println(Arrays.toString(c)+" has 2 distinc values:
"+hasNValues(c,2));
}
public static int hasNValues(int[] a, int n)
{
int hasNValues = 1;
int[] uniqueValues = new int[n];
int uniqueindex = 0;
for (int i = 0; i < a.length && hasNValues == 1;
i++)
{
if (isExistInArray(uniqueValues, a[i]) == -1)
{
if (uniqueindex < n)
{
uniqueValues[uniqueindex] = a[i];
uniqueindex++;
}
else
{
hasNValues = 0;
}
}
}
if (uniqueindex != n) hasNValues = 0;
return hasNValues;
}
//helper function to find if numer io in array or not
public static int isExistInArray(int a[],int num)
{
for(int i=0;i<a.length;i++)
if(a[i]==num)
return 1;
return -1;
}
}
output
If you have any query regarding the code please ask me in the
comment i am here for help you. Please do not direct thumbs down
just ask if you have any query. And if you like my work then please
appreciates with up vote. Thank You.