DavidsInferno

Hitting The Target Number

Feb 1st, 2020
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. void sortDesc(int* niz,int arraySize);
  8. void ispisNiza(int* niz, int arraySize);
  9. int hittingTheTarget(int* niz, int arraySize, int position, int target);
  10.  
  11. int main(void) {
  12. int* niz = NULL;
  13. int arraySize = 0;
  14. int target = 0;
  15. int position = 0;
  16.  
  17.  
  18. int counter = -1;
  19.  
  20. int min = INT_MAX;
  21.  
  22. cout << "Koliko ce velik niz bit: ";
  23. cin >> arraySize;
  24. niz = new int[arraySize];
  25.  
  26. cout << "\nUnesi brojeve u tom nizu: ";
  27. for (int i = 0;i < arraySize;i++) {
  28. cin >> niz[i];
  29. }
  30. sortDesc(niz, arraySize);
  31. cout << "Zeljeni zbroj: ";
  32. cin >> target;
  33.  
  34. for (int i = 0;i < arraySize;i++) {
  35. counter=hittingTheTarget(niz, arraySize, i, target);
  36.  
  37. if (min > counter && counter!=-1)
  38. min = counter;
  39. }
  40.  
  41. if (counter == -1)
  42. cout << "You done fucked it";
  43. else
  44. cout << "\nKolicina je: " << min << endl;
  45.  
  46.  
  47. return 0;
  48. }
  49. void sortDesc(int *niz,int arraySize) {
  50. int i = 0;
  51. int j = 0;
  52. int temp = 0;
  53. for (i = 0;i < arraySize;i++) {
  54. for (j = i + 1;j < arraySize;j++) {
  55. if (niz[i] < niz[j]) {
  56. temp = niz[i];
  57. niz[i] = niz[j];
  58. niz[j] = temp;
  59. }
  60. }
  61. }
  62. }
  63. void ispisNiza(int* niz,int arraySize) {
  64. for (int i = 0;i < arraySize;i++) {
  65. cout << niz[i] << " ";
  66. }
  67. }
  68.  
  69. int hittingTheTarget(int* niz, int arraySize, int position, int target) {
  70.  
  71. int i = 0;
  72. int result = 0;
  73. int counter = 0;
  74. for (i=position;i < arraySize;i++)
  75. {
  76. result += niz[i];
  77. counter++;
  78.  
  79. if (result == target) {
  80. return counter;
  81. }
  82. else if (result > target)
  83. {
  84. result -= niz[i];
  85. counter--;
  86. }
  87. else
  88. i--;
  89.  
  90. }
  91. return -1;
  92. }
Add Comment
Please, Sign In to add comment