developing a function that returns number of distinct values that exist in array - c

I want to create a function that can return the number distinct values present in a given array. If for eg the array is
array[5] = { 1 3 4 1 3}, the return value should be 3(3 unique numbers in array).
I've so far only got this:
int NewFucntion(int values[], int numValues){
for (i=0; i<numValues; i++){
Im a new coder/New to C language and im stuck on how to proceed. Any guidance would be much appreciated. Thanks

Add elements from the array to the std::set<T> and since the set is not allowing duplicate elements, you can then only get the number of elements from the set which gives you the number of distinct elements.
For example:
#include<set>
int NewFucntion(int values[], int numValues){
std::set<int> set;
for(int i=0; i<numValues; i++){
set.insert(values[i]);
}
return set.size();
}

int distinct(int arr[], int arr_size){
int count = arr_size;
int current;
int i, j;
for (i = 0; i < arr_size; i++){
current = arr[i];
for (j = i+1; j < arr_size; j++) // checks values after [i]th element.
if (current == arr[j])
--count; // decrease count by 1;
}
if (count >= 0)
return count;
else return 0;
}
Here's the explanation.
The array with its size is passed as an argument.
current stores the element to compare others with.
count is the number that we need finally.
count is assigned the value of size of the array (i.e we assume that all elements are unique).
(It can also be the other way round)
A for loop starts, and the first (0th) element is compared with the elements after it.
If the element reoccurs, i.e. if (current==arr[j]), then the value of count is decremented by 1 (since we expected all elements to be unique, and because it is not unique, the number of unique values is now one less than what it was initially. Hence --count).
The loops go on, and the value is decremented to whatever the number of unique elements is.
In case our array is {1,1,1,1}, then the code will print 0 instead of a negative value.
Hope that helps.
Happy coding. :)

I like wdc's answer, but I am going to give an alternative using only arrays and ints as you seam to be coding in c and wdc's answer is a c++ answer:
To do this thing, what you need to do is to go through your array as you did, and store the new numbers you go over in a different array lets call it repArray where there wont be any repetition; So every time you add something to this array you should check if the number isn't already there.
You need to create it and give it a size so why not numValues as it cannot get any longer than that. And an integers specifying how many of it's indexes are valid, in other words how many you have written to let's say validIndexes. So every time you add a NEW element to repArray you need to increment validIndexes.
In the end validIndexes will be your result.

Related

Fnd max float number in 2d array (whitout knowing the size of it) on C

I am trying to find a solution in a C programming
I have a 2d array, but i dont know its size
I can only access the array with a array view of [11][11]
The main idea is to find the peak of a mountain (max element)
So basically my 2d array is a map where each index is a float number, corresponding to the height of the mountain
I know i am out of the map when my float number is -1
That is what i was thinking to do, but i cant put it onto a code in a proper way
My solution is based on brute force approach
my basic idea was getting one 2d array formed by myview
what would give me a [11][11] array
then get a max value on that [11][11] array and store it.
next step i would generate another myview array using a loop.
i would apply same process here, to get a max value on that new array
then i would compare myfirst Max value with that second Max value
the value who have the biggest value would be stored on my max variable, with the location as well (point x and point y).
then i would run a loop again to create another myview array, and so on.
My plan to run on all possible [11][11]arrays is:
starting from running a loop for all the columns, but always keeping the rows 1-11
i know there is no more columns when all the values inside of my array [11][11] are -1.0
so when i find that array i would jump for next section of rows (12-23) for example
and again run for all columns.
i also could set a max value per set of a row (so at set of rows 1-11 the max value (peak) is 197.15 , then at set of rows 12-23 the max value (peak) is 397.15, for example)
i know will not be more rows when in my first set of columns i get the values inside of my array [11][11] -1.0000
so i would just need to get my biggest value on all set of rows, then i would get my solution.
You mean you have a two-dimensional array with two lines of eleven elements each, as you would get if you ran int array[11][11];? Then you can have two nested loops, one for (int i = 0; i < 2; i++) and for (int j = 0; j < 11; j++) nested inside each other to loop over the individual elements of the two lines. You have a buffer variable that holds the maximum so far. In your loop you compare each element you're looping over against the buffer variable, and the new element becomes the new buffer variable if it's bigger than the existing one:
void main(void) {
int array[11][11];
int buffer = 0;
for (int i = 0; i < 2; i++) {
for (int j = 0; 11 < 2; j++) {
if (array[i][j] > buffer) {buffer = array[i][j];}
}
}
}

Array in JAVA., repeat?

I'm writing a function using java language that takes in a 1D array and the size of the array as inputs to the function. I want to find out how many function values of are in the array. How would I do this?
Approach 1(O(nlogn)):
Sort the array.
Compare the adjacent elements in array
Increment the count whenever the adjacent elements are unequal. Please take care of three consecutive same elements using an extra variable.
Approach 2(O(n) but space complexity of O(n)):
Create a Hash Table for value.
Insert a value if not present in the hash table.
Count and print the values for present in hashtable
#Find unique items from array:
1. Create one new array
2. Take each item from existing array
3. Check if the item is exist in new array
4. **If not exist push the item into new array** else go for next item
5. After iterating all item in array get the length of new array
#include <stdio.h>
int main ()
{
int n[10] = {1,2,5,5,3,4,1,4,5,11};
int count = 0; int i = 0;
for (i=0; i< 10; i++)
{
int j;
for (j=0; j<i; j++)
if (n[i] == n[j])
break;
if (i == j)
count += 1;
}
printf("The counts are: %d distinct elements", count);
return 0;
}

How to compare and replace (int) pointers?

So i have this piece of code:
int* get_lotto_draw() //Returns an array of six random lottery numbers 1-49
{
int min = 1;
int max = 49;
int counter = 0;
srand(time(NULL));
int *arrayPointer = malloc(6 * sizeof(int));
for(counter = 0; counter <= 5; counter++)
{
arrayPointer[counter] = rand()%(max-min)+min;
}
return arrayPointer;
}
This gives me 6 int* but sometimes these int* values can be the same. How can i compare each of them to eachother, so that if they are the same number, it will re-calculate on of the values that are equal ? Thanks for your time.
make a search in the array for same number before storing the number as,
for(counter = 0; counter <= 5; counter++)
{
int x1 = 1;
while(x1)
{
int temp = rand()%(max-min)+min;
for(i = 0; i < counter; i++)
{
if(arrayPointer[i] == temp)
{
break;
}
}
if(i == counter)
{
x1 = 0;
arrayPointer[counter] = temp;
}
}
}
The problem is that random-number generators don't know or care about history (at least, not in the sense that you do--software random number generators use recent results to generate future results). So, your choices are generally to...
Live with the possibility of duplicates. Obviously, that doesn't help you.
Review previous results and discard duplicates by repeating the draw until the value is unique. This has the potential to never end, if your random numbers get stuck in a cycle.
Enumerate the possible values, shuffle them, and pick the values off the list as needed. Obviously, that's not sensible if you have an enormous set of possible values.
In your case, I'd pick the third.
Create an array (int[]) big enough to hold one of every possible value (1-49).
Use a for loop to initialize each array value.
Use another for loop to swap each entry with a random index. If you swap a position with itself, that's fine.
Use the first few (6) elements of the array.
You can combine the second and third steps, if you want, but splitting them seems more readable and less prone to error to me.

C two dimensional array smallest gets biggest instead

I am new to stackoverflow as am new to programming, yet am not really a 'professional and enthusiast programmer'. Enthusiast maybe but not professional...
In a part of some beginner code of mine i have a two dimensional array diff[i][j], where the value is zero wherever i==j. I am trying to get the smallest value in each row but not the zero value...
the part of the code (under construction) that searches the smallest of the first row is:
i=1;
double smallest;
for ( j=1 ; j<=n ; j++ )
{
smallest = diff[i][j];
if ( j!=i && diff[i][j] < smallest )
smallest = diff[i][j];
}
printf("\n %lf\n", smallest);
however, the result is always the biggest number not the smallest. Anyone knows why??
P.S. I'd be thankful for any suggestion or comment of dealing with stackoverflow.com and the way i asked my question, since am new here... thank you in advance...
EDIT
after the answers below, i decided to make the i=1 a special case and make two separate functions for both cases... however, when i try to assign j to other variable i failed... in the previous code:
if (j!=i && diff[i][j]<smallest) {smallest=diff[i][j]; d=j}
declared d previously and everything... when i print d it prints a random number >maybe the memory location content... tried for debugging to assign an initial value - with the declaration - and when printing it came out the initial value... the point is i want d to hold the column where the smallest value is... how can i acheive that??
You never initialize smallest
i=1;
double smallest = diff[1][2]; // initialize it to a non-diagonal element in the column
for (j=1; j<=n; j++)
if (j!=i && diff[i][j]<smallest){
smallest=diff[i][j];
}
printf("\n %lf\n", smallest);
EDIT:
You also seem to have { smallest= diff[i][j]; .. } in your code that overrides the value of smallest each iteration. I removed it in my answer.
First thing, array indexes start from 0 in C, not 1, so you should have j = 0; j < n, assuming n is the size of the array.
Then, you assign to smallest every time around the loop, not just if the new value is smaller. So, what you're seeing is the last value.
Assuming that you really do run one past the end of the row, this "last value" is probably actually the first value in the next row. Or some arbitrary value stored in the memory that just so happens to be past the end of the array, if your array has exactly 2 rows. Anyway, it's Undefined Behavior to read past the end of an array, which is Not Good. Anything is allowed to happen, and what does happen often is more puzzling than you expect.
Careful about your array indexes. In C array indexes start at zero.
For:
double array[10];
you would go through all ten elements with:
int i;
for( i = 0; i < 10; i++ )
printf( "The array value at %d is %g\n", i, array[i] );

How to find a certain number in an Array C Programming?

If I have an array and I need to display how many times the number '12' is created. I'm using a function to go about this. What resources should I look into to find how to exactly tease out this one number and display how many times it is in the array/list? Any help would be greatly appreciated.
You can do it by walking through the array, while keeping a tally.
The tally starts at 0, and every time you reach the number you want to track, add one to it. When you're done, the tally contains the number of times the number appeared.
Your function definition would probably look something like this:
int count_elements(int pElement, int pArray[], size_t pSize);
Simply create a counter variable, and examine each element in the array in a loop, incrementing the counter variable every time an element is equal to 12.
If you have a plain C-array, you have to iterate over all elements in a loop and count yourself with a variable.
int arr[20];
int twelves = 0;
int i;
/* fill here your array */
/* I assume your array is fully filled, otherwise change the sizeof to the real length */
for(i = 0; i < sizeof(arr)/sizeof(int);++i) {
if(arr[i] == 12) ++twelves;
}
After this, the variable twelves will contain the number of twelves in the array.

Resources