Click here to Skip to main content
15,892,072 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have 2 arrays of natural numbers and 1 integer lets call it 'd'.
I need to find 2 numbers from 2 different arrays lets say 'x' and 'y' that fulfills a condition x-y=d or y-x=d.

I need the most efficient way.

What I have tried:

C
int i, j, flag = 1;
for (i = 0; i < size_a; i++)
	for (j = 0; j < size_b; j++)
		if (abs(a[i] - b[j]) == num)
		return 1;
return 0;


It works but its not that efficien, if you guys have any better idea I'll be glad to hear it.

Thanks in advance,
Nick
Posted
Updated 14-Jan-18 22:38pm
v2
Comments
CPallini 15-Jan-18 2:46am    
If the arrays are not ordered I see no way to improve that.

1 solution

CPallini is right, so ordering could improve the speed of your loop because your can stop the looping when the diff gets greater than num. Think about dropping some comparison if the numbers are smaller than num. Maybe only if alway greater than zero.

If you need to find the numbers you also must store them for output.

C++
if (abs(a[i] - b[j]) == num)
  {
    result1 = a[i];//store in variable with greater scope
    result2 = b[i];
    return 1;
}
What about multiple solutions in the array?

But speed isnt the primary problem on that simple task. Such "optimization" often leads to complex and bizarre code which results in strange bugs and problems.

So anything you missed to mention?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900