Harder, Better, Faster, Stronger please!
Looking for some voodoo to optimize these snippets...
Find Unique Elements in One Array
function int[] unique_elements (int arr[]) {
int _arr[] = sort(arr);
for (int i=0; i<len(_arr); i++) {
while(_arr[i] == _arr[i+1]) pop(_arr,i);
}
return _arr;
}
Get Duped Elements in One Array
function int[] duped_elements (int arr[]) {
int _arr[] = sort(arr);
int result[] = {};
int dupe;
for (int i=0; i<len(_arr); i++) {
while(_arr[i] == _arr[i+1]) {
dupe = pop(_arr,i);
}
append(result, dupe);
}
return result;
}
Find Common Elements in Two Arrays
function int[] common_elements (int arr1[]; int arr2[]) {
int result[];
foreach (int i; unique_elements(arr1)) {
foreach (int j; unique_elements(arr2)) {
if (i==j) push(result,j);
}
}
return result;
}
Find Different Elements in Two Arrays
function int[] different_elements (int arr1[]; int arr2[]) {
int result[];
int _arr1[] = unique_elements(arr1);
int _arr2[] = unique_elements(arr2);
foreach(int i; _arr1) {
if(find(_arr2,i)<0) append(result,i);
}
foreach(int j; _arr2) {
if(find(_arr1,j)<0) append(result,j);
}
return result;
}
Swap Arrays
function int[] swap (int arr1[]; int arr2[]) {
int temp[] = arr1;
arr1 = arr2;
arr2 = temp;
return {1};
}
Here's some of what I was using to test it... these are all based on arrays of integers but could be tweaked obviously for other types.
i[]@arr1 = {3, 2, 15, 27, 1, 3};
i[]@arr2 = {3, 2, 3, 15, 41, 41, 1, 2, 2};
i[]@arr_comm = common_elements (@arr1, @arr2);
i[]@arr_diff = different_elements (@arr1, @arr2);
i[]@arr_uniq = unique_elements (@arr1);
i[]@arr_dupe = duped_elements (@arr2);