Advertisement
asiffff

KnapSackG

Dec 3rd, 2019
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package knapsackgreddy;
  7.  
  8. /**
  9. *
  10. * @author Asif
  11. */
  12. public class KnapSackGreddy {
  13.  
  14. /**
  15. * @param args the command line arguments
  16. */
  17.  
  18. static void maxP(double p[],double w[],double piwi[]) {
  19. int n = p.length;
  20. for(int i = 0;i<n-1;i++) {
  21. for(int j = 0;j<n-i-1;j++) {
  22. if(p[j]<p[j+1]) {
  23. double temp = p[j];
  24. p[j] = p[j+1];
  25. p[j+1] =temp;
  26. double temp1 = w[j];
  27. w[j] = w[j+1];
  28. w[j+1] =temp1;
  29. double temp2 = piwi[j];
  30. piwi[j] = piwi[j+1];
  31. piwi[j+1] =temp2;
  32. }
  33. }
  34. }
  35. }
  36. static void minW(double p[],double w[],double piwi[]) {
  37. int n = p.length;
  38. for(int i = 0;i<n-1;i++) {
  39. for(int j = 0;j<n-i-1;j++) {
  40. if(w[j]>w[j+1]) {
  41. double temp = p[j];
  42. p[j] = p[j+1];
  43. p[j+1] =temp;
  44. double temp1 = w[j];
  45. w[j] = w[j+1];
  46. w[j+1] =temp1;
  47. double temp2 = piwi[j];
  48. piwi[j] = piwi[j+1];
  49. piwi[j+1] =temp2;
  50. }
  51. }
  52. }
  53. }
  54. public static void main(String[] args) {
  55. // TODO code application logic here
  56. double p[] = {25,24,15};
  57. double w[] = {18,15,10};
  58. double piwi[] = new double[p.length];
  59. double m = 20;
  60. double minW[] = new double[p.length];
  61. double minWP = 0;
  62. minW(p, w, piwi);
  63. for(int i=0;i<p.length;i++) {
  64. System.out.println(m);
  65. if(m >0) {
  66. if(w[i] <= m) {
  67. m = m - w[i];
  68. minW[i] = 1;
  69. minWP += p[i];
  70. }else {
  71. double x = m/p[i];
  72. //m = 0;
  73.  
  74. minW[i] = x;
  75. minWP += (m*p[i])/w[i];
  76. m = 0;
  77. }
  78. }
  79. }
  80. for(int i =0;i<p.length;i++) {
  81. System.out.print(minW[i]+" ");
  82. }
  83. System.out.println("");
  84. System.out.println(minWP);
  85.  
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement