Guest User

Untitled

a guest
Mar 23rd, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int do_findArrayQuadruplet(int *arr, int *out, size_t arrLength, int s, int i, int j, int k, int l)
  5. {
  6. int sum, ret = 0;
  7.  
  8. if (arrLength < 4)
  9. return 0;
  10.  
  11. if (!arr || !out)
  12. return 0;
  13.  
  14. sum = arr[i]+arr[j]+arr[k]+arr[l];
  15.  
  16. if (sum == s) { // Sort out
  17. out[0] = arr[i];
  18. out[1] = arr[j];
  19. out[2] = arr[k];
  20. out[3] = arr[l];
  21. return 1;
  22. }
  23.  
  24. if (i < arrLength)
  25. ret = do_findArrayQuadruplet(arr, out, arrLength, s, i+1, j, k, l); // i, j, k, l
  26.  
  27. if (!ret && j < arrLength)
  28. ret = do_findArrayQuadruplet(arr, out, arrLength, s, i, j+1, k, l);
  29.  
  30. if (!ret && k < arrLength)
  31. ret = do_findArrayQuadruplet(arr, out, arrLength, s, i, j, k+1, l);
  32.  
  33. if (!ret && l < arrLength)
  34. ret = do_findArrayQuadruplet(arr, out, arrLength, s, i, j, k, l+1);
  35.  
  36. return ret;
  37. }
  38.  
  39. void findArrayQuadruplet(int const *arr, int* out, size_t arrLength, int s) {
  40. // your code goes here
  41. /*
  42. take first 4 no check if sum is s
  43. idx_1, idx_2 , idx_3 idx_4
  44. */
  45. if (arrLength < 4)
  46. return;
  47.  
  48. if (!arr || !out)
  49. return;
  50.  
  51. if (do_findArrayQuadruplet(arr, out, arrLength, s, 0, 1, 2, 3))
  52. sort(out, 4);
  53. }
  54.  
  55. int main() {
  56. return 0;
  57. }
  58.  
  59. // sort the array ascending order
  60. sort(arr);
  61.  
  62. // four for loops -> O(n^3) -> brute force first two numbers, first <= second
  63. // last two numbers with given sum, 4sum - first two number's
  64. // two sum -> two pointer technique , line 27 spent O(n^2), line 28, O(n), in total O(n^3)
  65. // 1, 2, 3, 4, 5, 6, 7, 8, 9
  66. // find two numbers with given 11,
  67. // 1, 9 = 10 < 11
  68. // 1 -> 2, 9 = 11 > 10
  69. for(int i = 0; i < len; i++)
  70. for(int j = i + 1; j < len; j++)
  71. for(int k = j + 1; k < len; k++)
  72. for(int l = k + 1; l < len; l++)
Add Comment
Please, Sign In to add comment