I have 2 arrays, in parallel:
defenders = {1,5,7,9,12,18};
attackers = {3,10,14,15,17,18};
Both are sorted, what I am trying to do is rearrange the defending array's values so that they win more games (defender[i] > attacker[i]) but I am having issues on how to swap the values in the defenders array. So in reality we are only working with the defenders array with respect to the attackers.
I have this but if anything it isn't shifting much and Im pretty sure I'm not doing it right. Its suppose to be a brute force method.
void rearrange(int* attackers, int* defenders, int size){
int i, c, j;
int temp;
for(i = 0; i<size; i++){
c = 0;
j = 0;
if(defenders[c]<attackers[j]){
temp = defenders[c+1];
defenders[c+1] = defenders[c];
defenders[c] = temp;
c++;
j++;
}
else
c++;
j++;
}
}
Edit: I did ask this question before, but I feel as if I worded it terribly, and didn't know how to "bump" the older post.
To be honest, I didn't look at your code, since I have to wake up in less than 2.30 hours to go to work, hope you won't have hard feelings for me.. :)
I implemented the algorithm proposed by Eugene Sh. Some links you may want to read first, before digging into the code:
qsort in C
qsort and structs
shortcircuiting
My approach:
Create merged array by scanning both att and def.
Sort merged array.
Refill def with values that satisfy the ad pattern.
Complete refilling def with the remaining values (that are
defeats)*.
*Steps 3 and 4 require two passes in my approach, maybe it can get better.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char c; // a for att and d for def
int v;
} pair;
void print(pair* array, int N);
void print_int_array(int* array, int N);
// function to be used by qsort()
int compar(const void* a, const void* b) {
pair *pair_a = (pair *)a;
pair *pair_b = (pair *)b;
if(pair_a->v == pair_b->v)
return pair_b->c - pair_a->c; // d has highest priority
return pair_a->v - pair_b->v;
}
int main(void) {
const int N = 6;
int def[] = {1, 5, 7, 9, 12, 18};
int att[] = {3, 10, 14, 15, 17, 18};
int i, j = 0;
// let's construct the merged array
pair merged_ar[2*N];
// scan the def array
for(i = 0; i < N; ++i) {
merged_ar[i].c = 'd';
merged_ar[i].v = def[i];
}
// scan the att array
for(i = N; i < 2 * N; ++i) {
merged_ar[i].c = 'a';
merged_ar[i].v = att[j++]; // watch out for the pointers
// 'merged_ar' is bigger than 'att'
}
// sort the merged array
qsort(merged_ar, 2 * N, sizeof(pair), compar);
print(merged_ar, 2 * N);
// scan the merged array
// to collect the patterns
j = 0;
// first pass to collect the patterns ad
for(i = 0; i < 2 * N; ++i) {
// if pattern found
if(merged_ar[i].c == 'a' && // first letter of pattern
i < 2 * N - 1 && // check that I am not the last element
merged_ar[i + 1].c == 'd') { // second letter of the pattern
def[j++] = merged_ar[i + 1].v; // fill-in `def` array
merged_ar[i + 1].c = 'u'; // mark that value as used
}
}
// second pass to collect the cases were 'def' loses
for(i = 0; i < 2 * N; ++i) {
// 'a' is for the 'att' and 'u' is already in 'def'
if(merged_ar[i].c == 'd') {
def[j++] = merged_ar[i].v;
}
}
print_int_array(def, N);
return 0;
}
void print_int_array(int* array, int N) {
int i;
for(i = 0; i < N; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}
void print(pair* array, int N) {
int i;
for(i = 0; i < N; ++i) {
printf("%c %d\n", array[i].c, array[i].v);
}
}
Output:
gsamaras#gsamaras:~$ gcc -Wall px.c
gsamaras#gsamaras:~$ ./a.out
d 1
a 3
d 5
d 7
d 9
a 10
d 12
a 14
a 15
a 17
d 18
a 18
5 12 18 1 7 9
The problem is that you are resetting c and j to zero on each iteration of the loop. Consequently, you are only ever comparing the first value in each array.
Another problem is that you will read one past the end of the defenders array in the case that the last value of defenders array is less than last value of attackers array.
Another problem or maybe just oddity is that you are incrementing both c and j in both branches of the if-statement. If this is what you actually want, then c and j are useless and you can just use i.
I would offer you some updated code, but there is not a good enough description of what you are trying to achieve; I can only point out the problems that are apparent.
Related
this question been asked a few times but cannot find anything specific, the topic is I'm trying to perform a merge sort using 2 threads for sorting each sub list, each thread taking a half, and a third thread to merge the two lists afterwards,
but I'm having difficulty, understanding the merge sort, (first time trying to write a sort algorithm in
c)
i know i need to lets say take "apart" the merge sort and perform only each half in two separate functions, that I can pass into the thread, then perform the final merging process, but lets say I have lists
list1 11 22 1 6 9
list2 99 33 4 5 7
I know I could write a simple sort algorithm to put each in order, but the merging process is throwing me for a loop soheres what im thinking or visualizing the error, and what i am lost on, say i sort the two lists with their different thread functions
list1 1 6 9 11 22
list2 4 5 7 33 99
I keep thinking this will be the result if I go ahead and merge them at this stage
1 6 9 11 22 4 5 7 33 99
that isn't exactly in order is it?
and if I sort them in the final merger using a sort, I mean what was the point of sorting them initially? that kind of just makes the point of sorting them in the two subthreads pointess, when my goal is to use the 2 threads and 2 threads only, then use the final thread to merge like a merge sort would sort each array
can anyone help me visualize this better, either with code, or pseudocode?, assume that in my code I already have the array split and ready to be passed into the functions in my main(void) function, with pointers named first_half, second_half, the starter array is constructed, by taking a user input and passing that into a malloc function, and filled using random limited to 0-99
The way merge sort is working is by comparing the sorted element of each list together, it does not concatenate one array after another, see example code below (singlethreaded):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define _DEBUG 1
void insertion_sort(int n, int a[n])
{
int i, tmp, j;
for (i = 1; i < n; i++) {
tmp = a[i];
j = i - 1;
while (j >= 0 && a[j] > tmp) {
a[j + 1] = a[j];
--j;
}
a[j + 1] = tmp;
}
#ifdef _DEBUG
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
putchar('\n');
#endif
}
void merge_sort(int n, int a[n], int x, int b[x], int y, int c[y])
{
for (int i = 0; i < x; i++) // split values of a into two arrays
b[i] = a[i];
for (int i = 0; i < y; i++)
c[i] = a[i+x];
insertion_sort(x, b); // sort each of the sub arrays, you multithread this part.
insertion_sort(y, c);
int i = 0;
int j = 0;
int k = 0;
while (i < n) {
if (b[j] < c[k]) // you add to a the smallest between b and c.
a[i++] = b[j++];
else
a[i++] = c[k++];
if (x == j) { // if all the elements of b have filled a:
do {
a[i++] = c[k++]; // we proceed to fill a with c
} while (y != k);
break ; // the merge sorting is completed.
}
else if (y == k) {
do {
a[i++] = b[j++];
} while (x != j);
break ;
}
}
#ifdef _DEBUG
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
putchar('\n');
#endif
}
int main(void) {
srand ( time(NULL) );
const int n = 100;
int a[n];
int b[n/2];
int c[(n+1)/2];
for (int i = 0; i < n; i++) // initialize with random values
a[i] = rand() % 1000;
merge_sort(n, a, n/2, b, (n+1)/2, c);
}
I created an array called elements_n which has the elements 0 to N-1 where N is 2. The below numbers are the elements of the array called elements_n:
0 1
I have another array called Arr which has the following elements:
0 1 3 1 2 4
If any of the first 3 elements of the array Arr are equal to the first element of elements_n which is 0, I would like to delete that element from the array called Arr. I then repeat the same process for the next 3 elements of the array Arr. So to explain myself better, I will use the following example:
Compare the first 3 elements of array Arr which are 0, 1, 3 to the first element of elements_n which is 0. Since Arr[0] == elements_n[0]. I delete Arr[0] from the array Arr.
Compare the next 3 elements of array Arr which are 1, 2, 4 to the second element of elements_n which is 1. Since Arr[3] == elements_n[1]. I delete Arr[3] from the array Arr. So the elements that should be left in the array Arr are:
1 3 2 4
When I implemented it myself in C programming with the code found below the end result is coming:
1 3 3 2 2 4
Rather than:
1 3 2 4
This is the code I implemented:
#include <stdio.h>
#include <stdlib.h>
#define N 2
int main() {
unsigned *elements_n = malloc(N * sizeof(unsigned));
for (int i = 0; i < N; i++) {
elements_n[i] = i; //Created an array which has the elements 0 to N-1
}
printf("\n");
unsigned Arr[6] = { 0, 1, 3, 1, 2, 4 };
unsigned position_indices[2] = { 3, 3 }; //Moving every 3 elements in the Arr array.
int count = 0;
int index = 0;
unsigned *ptr_Arr = &Arr[0];
do {
for (int i = 0; i < position_indices[count]; i++) {
if (ptr_Arr[i] == elements_n[count]) {
index = i + 1; //Index of the Arr element that has the same value as the element in the array elements_n
for (int j = index - 1; j < position_indices[count] - 1; j++) {
ptr_Arr[j] = ptr_Arr[j + 1];
}
}
}
printf("\n");
ptr_Arr += position_indices[count] - 1;
count++;
} while (count < 2);
for (int i = 0; i < 6; i++) {
printf("%d\t", Arr[i]);
}
printf("\n");
free(elements_n);
return 0;
}
You might try something like this (not tested).
#include <stdio.h>
#include <stdlib.h>
#define N 2
int main()
{
unsigned *elements_n = malloc(N * sizeof(unsigned));
for (int i = 0; i < N; i++)
{
elements_n[i] = i; //Created an array which has the elements 0 to N-1
}
unsigned Arr[6] = { 0, 1, 3, 1, 2, 4 };
int dest_index = 0;
int src_index = 0;
int count = sizeof(Arr)/sizeof(Arr[0]);
for ( ; src_index < count; src_index++)
{
int group = src_index / 3;
if (Arr[src_index] != elements_n[group])
{
Arr[dest_index++] = Arr[src_index];
}
}
for (int i = 0; i < dest_index; i++)
{
printf("%d\t", Arr[i]);
}
printf("\n");
free(elements_n);
return 0;
}
You need to keep track of how many elements you removed from the array.
My solution:
#include <stdio.h>
#include <stddef.h>
#include <assert.h>
#include <string.h>
size_t fancy_delete_3(const int elems[], size_t elemssize, int arr[], size_t arrsize)
{
assert(elems != NULL);
assert(arr != NULL);
assert(arrsize%3 == 0);
assert(elemssize*3 == arrsize);
// we need to count the removed elements, to know how much we need to shift left
size_t removed = 0;
// for each element in elems
for (size_t i = 0; i < elemssize; ++i) {
// check the three correponding elements in arr
for (size_t j = i*3; j < (i+1)*3; ++j) {
assert(j >= removed);
const size_t pos = j - removed;
// if elems[i] matches any of the corresponding element in arr
if (elems[i] == arr[pos]) {
// remove element at position pos
assert(arrsize >= pos + 1);
// I don't think this can ever overflow
memmove(&arr[pos], &arr[pos + 1], (arrsize - pos - 1) * sizeof(int));
++removed;
// array is one element shorter, so we can just decrease the array size
assert(arrsize > 0);
--arrsize;
}
}
}
// we return the new size of the array
return arrsize;
}
#define __arraycount(x) sizeof(x)/sizeof(x[0])
int main()
{
int elements_n[] = {0,1};
int arr[] = {0,1,3, 1,2,4};
size_t newsize = fancy_delete_3(elements_n, __arraycount(elements_n), arr, __arraycount(arr));
printf("arr size=%zu {", newsize);
for (size_t i = 0; i < newsize; ++i)
printf("%d,", arr[i]);
printf("}\n");
return 0;
}
You have several related problems around how you perform deletions. In the first place, it's not clear that you understand that you cannot actually delete anything from a C array. The closest you can come is to overwrite it with something else. Often, pseudo-deletion from an array is implemented by moving each of the elements following the deleted one one position forward, and reducing the logical length of the array.* You seem to have chosen this alternative, but (problem 1) you miss maintaining or updating a logical array length.
Your problem is made a bit more complicated by the fact that you logically subdivide your array into segments, and you seem not to appreciate that your segments are variable-length in that, as described, they shrink when you delete an element. This follows from the fact that deleting an element from one group does not change the assignments of elements to other groups. You do have a mechanism in position_groups that apparently serves to track the sizes of the groups, and in that sense its name seems ill-fitting. In the same way that you need to track and update the logical length of the overall array, you'll need to track and update the lengths of the groups.
Finally, you appear to have an off-by-one error here:
for (int j = index - 1; j < position_indices[count]-1; j++)
that would be clearer if position_indices were better named (see above), but recognizing that what it actually contains is the size of each group, and that index and j represent indices within the group, it follows that the boundary condition for the iteration should instead be just j < position_indices[count]. That's moot, however, because you're going to need a somewhat different approach here anyway.
Suggestion, then:
When you delete an element from a group, move up the entire tail of the array, not just the tail of the group.
In service to that, update both group size and logical array size when you perform a deletion, remembering that that affects also where each subsequent group starts.
When you examine or output the result, remember to disregard array elements past the logical end of the array.
* "Logical array size" means the number of (leading) elements that contain meaningful data. In your case, the logical array size is initially the same as the physical array size, but each time you delete an element (and therefore move up the tail) you reduce the logical size by one.
You never really "deleted" any element, you just shifted-down the
second and third elements from each 3-group. And then, when
printing, you iterated over the whole array.
Arrays are just continuous blocks of memory, so you need a
different strategy. You could traverse the original array with
two indexes, one as the general index counter and other as
the index for the shifted slot. If the current element is
different from the corresponding elements_n item, copy it to
the secondary index and increase it.
In case nothing is equal to the elements_n item, you would just
reassign the array elements to themselves. However, as soon as
one is equal you will be shifting them with the advantage of
keeping track of the new size.
Also, calculating the corresponding elements_n item is a simple
matter of dividing the current index by 3, so you don't even need
an extra variable to that.
#include <stdio.h>
#define N 2
int main()
{
unsigned elements_n[N] = { 0, 1 };
unsigned Arr[N*3] = { 0, 1, 3, 1, 2, 4 };
int i, j;
for (i = 0, j = 0; i < N*3; i++)
if (Arr[i] != elements_n[i/3])
Arr[j++] = Arr[i];
for (i = 0; i < j; i++)
printf(" %d", Arr[i]);
printf("\n");
return 0;
}
I have an integer pointer array b_members that contains something like the following values:
1 2 4
I want to find the values of b_members that are not equal to a specific value inside a loop and store them in another integer pointer array i_p.
For example, inside my loop at index 0 I want to find and store the two values in b_members not equal to 1, (i.e. 2 and 4). So for the first iteration
ip = 2 4
In the second iteration I want to store 1 and 4 in ip so
ip = 1 4
And in the third iteration I want to store 1 and 2 in ip so
ip = 1 2
I can do this in Matlab using the code below but I want to be able to do this in C.
b_members = [1 2 4];
for i = b_members
ip = b_members(b_members ~=i);
end
Heres what I have in C so far:
int *b_members;
int *i_p;
b_members = Get_b_members(B,j); // fills b_members with array like [1 2 4]
for(int i=0;i<B->Columns;++i){ // going through all of b_members
printf("%d ",b_members[i]);
// Finding b_members not equal to b_members[i]
for(int i2=0;i2<B->Columns;++i2){
if (b_members[i2] != b_members[i])
i_p = &b_members[i2];
}
} // End b_members for loop
I can't seem to get it to work the right way, i_p just keeps getting longer as the loop progresses and I only want it to contain the two integers at a time. Is there a way to do this like the Matlab code I provided above? Any help would be appreciated.
Update:
Using Saurav Sahu's suggestion this worked:
int **i_p = (int **)malloc(B->Columns * sizeof(int*));
int tmp;
for(int i=0;i<B->Columns;i++)
{
// Need to find b_members excluding b_members(i)
i_p[i] = (int *)malloc((B->Columns-1) * sizeof(int));
int idx = 0;
for(int jj=0;jj<=B->Columns;jj++)
{
if(i==jj) continue;
if(b_members[i] != b_members[jj])
{
i_p[i][idx++] = b_members[jj];
}
}
tmp = i;
}
for(int ii=0;ii<=tmp;++ii)
{
printf("\ti_p[%d] = ",ii);
for(int it=0;it<(B->Columns)-1;++it)
{
printf("%d ",i_p[ii][it]);
}
printf("\n");
}
printf("\n");
You can create pointer of integer pointers like this. Assign enough size to each integer pointers to store array_size-1 integers.
int a[] = {1, 2, 4};
int aSize = sizeof(a)/sizeof(a[0]);
int **b = (int **)malloc(aSize * sizeof(int*));;
for(int i = 0; i < aSize; i++){
b[i] = (int *)malloc((aSize-1) * sizeof(int));
int idx = 0;
for(int j = 0; j < aSize; j++){
if(i == j) continue;
if(a[i] != a[j]) {
b[i][idx++] = a[j];
}
}
}
It works perfectly.
I am successfully storing the calculated subsets in a 2-D array matrix in C language.Now I want to print the subsets in an order desired.
For eg.
2-D array matrix is
10 7 3 2 1
10 7 5 1
7 6 5 3 2
10 6 5 2
10 7 6
Desired Output
10 7 6
10 7 5 1
10 7 3 2 1
10 6 5 2
7 6 5 3 2
How quick sort can be applied to sort/order these rows?
As #chqrlie noted, this can be easily solved with qsort.
Depending on the way the matrix is declared (is it an array of pointers to arrays of ints? do all arrays have the same length? is it a global array of fixed size?) the code will have to do slightly different things.
So, assuming the array is a global variable and all rows have same length (padded with 0s):
MWE:
#include <stdio.h>
#include <stdlib.h>
/*
Compare 2 integers
returns:
-1 if *i1 < *i2
+1 if *i1 > *i2
0 if *i1 == *i2
*/
int intcmp(const int *i1, const int *i2)
{
return (*i2 < *i1) - (*i1 < *i2);
}
#define ROWS 5
#define COLS 5
/*
Assumes rows already sorted in descending order
NOTE: qsort calls the comparison function with pointers to elements
so this function has to be tweaked in case the matrix is an array of
pointers. In that case the function's declaration would be:
int rowcmp(int **pr1, int **pr2)
{
const int *r1 = *pr1;
const int *r2 = *pr2;
// the rest is the same
}
*/
int rowcmp(const int *r1, const int *r2)
{
int i = 0, cmp;
do {
cmp = intcmp(&r1[i], &r2[i]);
i++;
} while (i < COLS && cmp == 0);
return -cmp; /* return -cmp to sort in descending order */
}
int data[5][5] = {
{10,7,3,2,1},
{10,7,5,1,0},
{ 7,6,5,3,2},
{10,6,5,2,0},
{10,7,6,0,0}
};
void printmatrix()
{
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
printf("%d ", data[i][j]); /* leaves a trailing space in each row */
}
printf("\n");
}
}
int main()
{
printmatrix();
qsort(data, 5, sizeof(data[0]), (int (*)(const void *, const void *))rowcmp);
printf("\n");
printmatrix();
return 0;
}
For the most flexible solution, I would define
struct row {
size_t len;
int *elems;
};
struct matrix {
struct row *rows;
size_t nrows;
};
and change the code accordingly.
NOTE: code not thoroughly tested, use with caution ;)
First of all, are you sure that the 1 on row 3,col 5 should be there and not on the last line?
Anyway, an efficient way to achieve what you want is:
compute the frequency array
declare a new matrix
go from the highest element (10 in your case) from frequency array and put in your matrix using your desired format.
It is time-efficient because you don't use any sorting algorithm, thus you don't waste time there.
It is NOT space-efficient because you use 2 matrices and 1 array, instead of only 1 matrix as suggested in other posts, but this should not be a problem, unless you use matrices of millions of rows and columns
C code for frequency array:
int freq[11] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
for(int i=0; i<NO_ROWS; i++) {
for(int j=0; j<NO_COLS; j++) {
if(MATRIX[i][j]!=null && MATRIX[i][j]>0 && MATRIX[i][j]<11) {
freq[MATRIX[i][j]]++;
}
}
}
C code for computing the new matrix dimensions
(assuming you want to keep the number of rows)
OUTPUT_MATRIX[100][100] /*I declared it statically, but I would advise to make it dinamically */
/* first, compute the number columns.
To do so, we need the number of elements
(we get them by simply summing up frequency array's elements) */
int s=0;
for(int i=0; i<11; i++) {
s+=frequency[i];
}
int addOne = 0 /* boolean value to check if we will have to add one extra column for safety */
if(s % NO_ROWS) {
addOne = 1; /* division is not even, so we will have to add extra column */
}
NO_COLS = s/NO_ROWS + addOne;
Now, final part, assigning the values from frequency array to the OUTPUT_MATRIX
int k=0;
int currentNumber = 10; /* assigning starts from 10 */
for(int i=0; i<NO_ROWS; i++) {
for(int j=0; j<NO_COLS; j++) {
if(currentNumber>0) {
if(frequency[currentNumber]==0 || k>=frequency[currentNumber]) {
currentNumber--;
k=0;
}
OUTPUT_MATRIX[i][j] = frequency[currentNumber];
k++;
} else {/*here, you can assign the rest of the value with whatever you want
I will just put 0's */
OUTPUTMATRIX[i][j] = 0;
}
}
}
Hope this helps!
This is what I do in C++ to reorder a matrix:
// b is the matrix and p is an array of integer containing the desired order of rows
for(i=0; i<n; i++){
if( p[i]==i )
continue;
b[i].swap(b[p[i]]);
j = p[i]; // New row i position
// Update row i position to new one
for(int k=i+1; k<n; k++){
if( p[k] == i )
p[k] = j;
}
printRow( b[i] );
}
You need to define an array of pointers of the data type you use and then you can reorder your matrix.
for example your matrix is: arr[5][10], and you want to print line 4 before line 3:
int *[5] arr2;
arr2[0] = &arr[0][0];
arr2[1] = &arr[1][0];
arr2[2] = &arr[2][0];
arr2[3] = &arr[4][0];
arr2[4] = &arr[3][0];
in regard to how will the ordering algorithm work, i would suggest placing a header in the start of each array in the matrix which will tell you how many elements it has(basically the first element of each array can be a counter of the total elements) afterwards you can order the strings by comparing the header, and if it is equal comparing the first element and so on. this can be done in a loop that iterates as many times as there are elements in the array, when the elements are not equal, break out of the loop.
hope this helps.
We have an array and it is unsorted. We know the range is [0,n].
We want to remove duplicates but we cannot use extra arrays and it must run in linear time.
Any ideas? Just to clarify, this is not for homework!
If the integers are limited 0 to n, you can move through the array, placing numbers by their indices. Every time you replace a number, take the value that used to be there and move it to where it should be. For instance, let's say we have an array of size 8:
-----------------
|3|6|3|4|5|1|7|7|
-----------------
S
Where S is our starting point, and we'll use C to keep track of our "current" index below.
We start with index 0, and move 3 to the 3 index spot, where 4 is. Save 4 in a temp var.
-----------------
|X|6|3|3|5|1|7|7| Saved 4
-----------------
S C
We then put 4 in the index 4, saving what used to be there, 5.
-----------------
|X|6|3|3|4|1|7|7| Saved 5
-----------------
S C
Keep going
-----------------
|X|6|3|3|4|5|7|7| Saved 1
-----------------
S C
-----------------
|X|1|3|3|4|5|7|7| Saved 6
-----------------
S C
-----------------
|X|1|3|3|4|5|6|7| Saved 7
-----------------
S C
When we try to replace 7, we see a conflict, so we simply don't place it. We then continue from the starting index S, increment it by 1:
-----------------
|X|1|3|3|4|5|6|7|
-----------------
S
1 is fine here, 3 needs to move
-----------------
|X|1|X|3|4|5|6|7|
-----------------
S
But 3 is a duplicate, so we throw it away and keep iterating through the rest of the array.
So basically, we move each entry at most 1 time, and iterate through the entire array. That's O(2n) = O(n)
void printRepeating(int arr[], int size)
{
int i;
printf("The repeating elements are: \n");
for(i = 0; i < size; i++)
{
if(arr[abs(arr[i])] >= 0)
arr[abs(arr[i])] = -arr[abs(arr[i])];
else
printf(" %d ", abs(arr[i]));
}
}
Assume int a[n] is an array of integers in the range [0,n-1]. Note that this differs slightly from the stated problem, but I make this assumption to make clear how the algorithm works. The algorithm can be patched up to work for integers in the range [0,n].
for (int i=0; i<n; i++)
{
if (a[i] != i)
{
j = a[i];
k = a[j];
a[j] = j; // Swap a[j] and a[i]
a[i] = k;
}
}
for (int i=0; i<n; i++)
{
if (a[i] == i)
{
printf("%d\n", i);
}
}
Can you sort? Sort with Radix Sort - http://en.wikipedia.org/wiki/Radix_sort with complexity O(arraySize) for given case and then remove duplicates from sorted array O(arraySize).
Walk through the array assign array[array[i]] = -array[array[i]]; if not negative; if its already negative then its duplicate, this will work since all values are within 0 and n.
Extending #Joel Lee's code for completion.
#include <iostream>
void remove_duplicates(int *a, int size)
{
int i, j, k;
bool swap = true;
while(swap){
swap = false;
for (i=0; i<size; i++){
if(a[i] != i && a[i] != a[a[i]]){
j = a[i];
k = a[j];
a[i] = k;
a[j] = j;
swap = true;
}
}
}
}
int main()
{
int i;
//int array[8] = {3,6,3,4,5,1,7,7};
int array[8] = {7,4,6,3,5,4,6,2};
remove_duplicates(array, sizeof(array)/sizeof(int));
for (int i=0; i<8; i++)
if(array[i] == i)
std::cout << array[i] << " ";
return 0;
}
With ES6 I think this can be solved with only a few lines reducing the array into an object and then using object.keys to get array without duplicates. This probably takes more memory. I'm not sure.
I did it like this:
var obj = array.reduce(function (acc, elem) {
acc[elem] = true;
return acc;
},{});
var uniqueArray = Object.keys(obj);
This has the added bonus (or disadvantage) of sorting the array. It works with strings too.
Use the array a a container with negative sign as an indicator, this will corrupt the input though.