patternjavaMinor
Checking an array for duplicate values
Viewed 0 times
arrayduplicatecheckingforvalues
Problem
This function checks an array for duplicated values. If it finds a duplicate value, it increments the variable name
Are there any improvements that can be made to the function? I am thinking about making it into a recursive function. Is that feasible?
repeatedTime and then if repeatedTime is greater than 1 it calls a randomize function which produce different values in the array that was passed to the function. It repeats these steps until a duplicated value free array is produced and then notDuplicate becomes true and the function ends. Are there any improvements that can be made to the function? I am thinking about making it into a recursive function. Is that feasible?
private void CheckForDuplicates(int[] selectedWordIds, List answersTempId) {
boolean notDuplicate = false;
while(notDuplicate != true){
int repeatedTime = 0;
for(int x = 0; x 1)
{
notDuplicate = false;
RandomizeFunction(selectedWordIds, answersTempId);
}
else{
notDuplicate = true;
}
}
}Solution
I suggest you use a
This is much simpler that what you have.
Here:
The assignment
About recursion: It is possible. With it, here is the final code:
Set when checking for duplicates:Set set = new HashSet<>();
for(int i : selectedWordIds) {
if(!set.add(i)) {
repeatedTime++;
}
}This is much simpler that what you have.
Here:
if(repeatedTime > 1)
{
notDuplicate = false;
RandomizeFunction(selectedWordIds, answersTempId);
}The assignment
notDuplicate = false is not necessary because notDuplicate is already false.About recursion: It is possible. With it, here is the final code:
private void CheckForDuplicates(int[] selectedWordIds,
List answersTempId) {
int repeatedTime = 0;
Set set = new HashSet<>();
for(int i : selectedWordIds) {
if(!set.add(i)) {
repeatedTime++;
}
}
if (repeatedTime > 1) {
RandomizeFunction(selectedWordIds, answersTempId);
CheckForDuplicates(selectedWordIds, answersTempId);
}
}Code Snippets
Set<Integer> set = new HashSet<>();
for(int i : selectedWordIds) {
if(!set.add(i)) {
repeatedTime++;
}
}if(repeatedTime > 1)
{
notDuplicate = false;
RandomizeFunction(selectedWordIds, answersTempId);
}private void CheckForDuplicates(int[] selectedWordIds,
List<Integer> answersTempId) {
int repeatedTime = 0;
Set<Integer> set = new HashSet<>();
for(int i : selectedWordIds) {
if(!set.add(i)) {
repeatedTime++;
}
}
if (repeatedTime > 1) {
RandomizeFunction(selectedWordIds, answersTempId);
CheckForDuplicates(selectedWordIds, answersTempId);
}
}Context
StackExchange Code Review Q#75072, answer score: 5
Revisions (0)
No revisions yet.