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;
}
Related
I want to write a C program that removes repeated values in an array and keep only the last occurrence.
For example I have to arrays:
char vals[6]={'a','b','c','a','f','b'};
int pos[6]={1,2,3,4,5,6};
I want to write a function so that the elements in the array after would be:
char vals[4]={'c','a','f','b'};
int pos[4]={3,4,5,6};
I know how to delete elements in general but in this case I am looking for a way where I could also delete the values in the pos array (associated with the Vals array)
Overwriting duplicate elements, per se, isn't particularly complicated. But right here you have the additional constraint of wanting the last index of each element you find. This can be solved easily when you search for duplicates:
unsigned remove_duplicates (char * restrict array,
unsigned * restrict positions, unsigned count) {
// assume positions is uninitialized
unsigned current, insert = 0;
for (current = 0; current < count; current ++) {
// first, see if the value is already in the array
unsigned search;
for (search = 0; search < current; search ++)
if (array[current] == array[search]) break;
if (search < current)
// if we found it, we just have a new position for it
positions[search] = current + 1; // +1 because your positions are 1-based
else {
// otherwise, write it into the array and store its position
// insert tracks the insertion pointer (i.e., the new end of the array)
array[insert] = array[current];
positions[insert] = current + 1;
insert ++;
}
}
// at this point we're done; insert will have tracked the number of
// unique elements, which we can return as the new array size
// the positions won't be sorted; you can sort both arrays if you want
return insert;
}
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.
There are N integers in an array.If you select element at index "i",then you get array[i] value in your packet, and array[i],array[i-1] and array[i+1] becomes zero, after selecting array[i] (i.e You can't take these elements any more in next selections). What is the maximum sum you can make in your packet by selecting array elements before all elements become zero ?
For each i we can either take that item or ignore it. We do the one which yields better result. Following is the dp approach:
const int N=10;
int a[]={1,2,3,4,5,6,7,8,9,10};
int dp[N];
int main() {
dp[0]=a[0];
dp[1]=max(a[0],a[1]);
for(int i=2;i<N;i++) {
dp[i]=max(dp[i-2]+a[i],dp[i-1]);
// dp[i-2]+a[i] is we include item i, hence we cannot take item i-1
// dp[i-1] is we don't take item i
}
cout<<dp[N-1];
return 0;
}
i'm a beginner in c, i have attempted to insert a value into an array as i scan another array for a value higher than a threshold, if a value is over the set threshold in the array being searched then insert a number into the other array...
for (i = 0; i<lines[i][1]; i++) {
if (lines[i][1] > 6500) {
array[];
}
so what i mean is, if there is a value in lines[i][1] higher than 6500, then insert number "1" into array[].
However, with previous attempts it just overwrites the array rather than stacks on top of previous values.. i have another for loop attempting to do the same thing while searching another array.
for (i = 0; i<lines[i][0]; i++) {
if (lines[i][0] > 6500) {
array[];
}
The ideal output would be something like: 1 for values higher than in lines[i][0] and 2 for values higher than in lines[i][1], "array[] = {1,1,1,2,2,2,2,1,1,1,};"
and the values are inserted into the array as arrays are being scanned.
Please help... thank you
Just start a counter to keep track of the position where you last inserted the item on the destination array. For example:
int destPosition=0;
for (i = 0; i<lines[i][0]; i++) {
if (lines[i][0] > 6500) {
array[destPosition]=1;
destPosition++;
}
}
I have three one-dimensional arrays. The task is to store the numbers which exist in each of the three arrays in a forth array. Here is my solution which as you see isn't correct. I'm also interested in a faster algorithm if possible because it's O(N3) difficulty.
#include <stdio.h>
main(){
int a[5]={1,3,6,7,8};
int b[5]={2,5,8,7,3};
int c[5]={4,7,1,3,6};
int i,j,k;
int n=0;
int d[5];
for(k=0; k<5; k++){
for(j=0; j<5; j++){
for(i=0; i<5; i++){
if(a[i]==b[j] && b[j]==c[k])
{d[n]=a[i];
n++;}
else
d[n]=0;
}}}
//Iterate over the new array
for(n=0;n<5;n++)
printf("%d\n",d[n]);
return 0;
}
One way to improve to O(n log n) is to sort all three arrays first.
Then use three pointers one for each array. You always move the one that points to the lowest value and after every such move check whether the three values are the same.
To improve even further you can use hashtable.
Iterate through the first array and put it's values in a hashtable as keys.
Then iterate through the second array and every time when the value exists as a key in the first hashtable, put it in a second one.
Finally iterate over the third array and if a value exists in the second hashtable as a key store it in the forth array. This is O(n) assuming the hashtable operations are O(1).
Your mistake is that you're using one of your three nested counters (which are being used to index the input arrays) as the index into the output array. You need to have a fourth index (let's call it n), which starts at zero, only increments every time a satisfactory value has been found.
Sort second and third arrays beforehand and use binary search on them to determine is some element is present.
If element is present in all of your arrays - it will present in the first. So, go through first (unsorted) array and check if its element is in second and third.
If you take the shortest array as the first - it will make algorithm slightly faster too.
You did't store them on d[] the right way.
Once found you can skip the rest of a[] and b[] for that element of c[].
#include <stdio.h>
main(){
int a[5]={1,3,6,7,8};
int b[5]={2,5,8,7,3};
int c[5]={4,7,1,3,6};
int i,j,k;
int n=0;
int found;
int d[5];
for(k=0; k<5; k++){
found=0;
for(j=0; j<5 && !found; j++){
if (b[j]==c[k]) {
for(i=0; i<5 && !found; i++){
if(a[i]==b[j]) {
d[n++]=c[k];
found=1;
}
}
}}}
//Iterate over the new array
for(i=0;i<5;i++)
printf("%d\n",d[i]);
return 0;
}