Created
November 7, 2012 22:31
-
-
Save nicotaing/4034961 to your computer and use it in GitHub Desktop.
Find same integers of 2 arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| a1 = [8, 2, 1, 5, 9, 10] | |
| a2 = [7, 14, 2, 8, 1, 6, 3, 10] | |
| # Sort arrays | |
| a1.sort!; a2.sort! | |
| i,j = 0,0 | |
| while i <= a1.size - 1 && j <= a2.size - 1 | |
| result ||= [] | |
| if a1[i] == a2[j] | |
| result << a1[i] | |
| i += 1; j += 1 | |
| else | |
| # increment array's index which has the smallest value and keep other one | |
| a1[i] > a2[j] ? j += 1 : i += 1 | |
| end | |
| end | |
| puts "RESULT" | |
| p result | |
| puts "EXCPETED" | |
| p expected = a1 & a2 | |
| msg = result == expected ? 'Success' : 'Fail' | |
| puts msg |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment