Reputation: 787
I am loading an array in a RPGLE program based on a business logic which may result in duplicate data in the array.
I want to know firstly how can I detect the duplication.
And finally I would like to know how can I remove the duplication in the array.
Upvotes: 1
Views: 1419
Reputation: 1088
detecting duplicate entries in arrays is quite simple:
0.) sort the array
1.) loop through the array and check if the current item matches the previous item
2.) if so, then remove the current item or
or you can
0.) create a temporary array
1.) loop through the original array and check if the current item is already contained in the temp arrayitem
2.) if not, then copy the current item into the temp array
3.) clear the original array and copy them from the temp to the oiginal array
Here you have a SO question regarding the topic in general: Array remove duplicate elements And here is a thread about doing this in RPGLE: https://code400.com/forum/forum/iseries-programming-languages/rpg-rpgle/7270-check-for-duplicates-in-array-of-size-50
If the order of entries in the original array has to be the same after removing the duplicate items, then the second approach would be better
Edit: Made a mistake, second approach does not need any sorting (removed this point)
Upvotes: 4
Reputation: 3674
You could use %LOOKUP to see if the entry is already in the array before you add it.
if %lookup(newValue : array : 1 : numElems) = 0;
// the element is not in the array yet
numElems += 1;
array(numElems) = newValue;
endif;
Upvotes: 7