Algorithm to see how many variables are the same ...
I finished my final unit for Java last week. In the examination there was a question that asked for a method to be written to check to see how many elements in an array contained the same values. Given that there were only 3 elements in the array, the most obvious solution would be to resort to the humble 3-bit truth table and implement an IF statement containing ANDs / ORs. But I wanted to do things differently, I thought outside the square, this is what I came up with ...
Code:
public int getObjectsAtSameDistance()
{
int ObjectsSameDistance;
// Scan thru array and see how many objs are at the same distance
for (int j = 0, j < 2, j++)
{
for (int i = j + 1, i < 2, i++)
{
if (distances[j] == distances[i])
{
objectsSameDistance ++;
break;
}
}
}
if (objectsSameDistance > 0)
objectsSameDistance ++;
return objectsSameDistance;
}
The more traditional approach for something like that would be this ...
Code:
public int getObjectsAtSameDistance()
{
int ObjectsSameDistance;
if (distances[0] == distances[1] && distances[2] == distances[0])
{
objectsSameDistance = 3;
}
elseif (distances[0] == distances[1] || distances[1] == distances[2] || distances[0] == distances[2])
{
objectsSameDistance = 2;
}
}
Doing things like can quickly become unmanagable when there's lots of elements in the array.
The truth table below supports the solution, whereas a = the first element in the array and c is the last ...
abc
000
001
010
011
100
101
110
111
I'm fully aware that this is a PBP forum and not Java, so I have ported the code to PBP below for those who wish to give it a whirl ..
Code:
Main:
objectsSameDistance var byte
// Scan thru array and see how many objs are at the same distance
for j = 0 to 2
for i = j + 1 to 2
if distances[j] = distances[i] then
objectsSameDistance = objectsSameDistance + 1
exit for
end if
next
next
Best Regards,
Trent Jackson
Bookmarks