Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package knapsackgreddy;
- /**
- *
- * @author Asif
- */
- public class KnapSackGreddy {
- /**
- * @param args the command line arguments
- */
- static void maxP(double p[],double w[],double piwi[]) {
- int n = p.length;
- for(int i = 0;i<n-1;i++) {
- for(int j = 0;j<n-i-1;j++) {
- if(p[j]<p[j+1]) {
- double temp = p[j];
- p[j] = p[j+1];
- p[j+1] =temp;
- double temp1 = w[j];
- w[j] = w[j+1];
- w[j+1] =temp1;
- double temp2 = piwi[j];
- piwi[j] = piwi[j+1];
- piwi[j+1] =temp2;
- }
- }
- }
- }
- static void minW(double p[],double w[],double piwi[]) {
- int n = p.length;
- for(int i = 0;i<n-1;i++) {
- for(int j = 0;j<n-i-1;j++) {
- if(w[j]>w[j+1]) {
- double temp = p[j];
- p[j] = p[j+1];
- p[j+1] =temp;
- double temp1 = w[j];
- w[j] = w[j+1];
- w[j+1] =temp1;
- double temp2 = piwi[j];
- piwi[j] = piwi[j+1];
- piwi[j+1] =temp2;
- }
- }
- }
- }
- public static void main(String[] args) {
- // TODO code application logic here
- double p[] = {25,24,15};
- double w[] = {18,15,10};
- double piwi[] = new double[p.length];
- double m = 20;
- double minW[] = new double[p.length];
- double minWP = 0;
- minW(p, w, piwi);
- for(int i=0;i<p.length;i++) {
- System.out.println(m);
- if(m >0) {
- if(w[i] <= m) {
- m = m - w[i];
- minW[i] = 1;
- minWP += p[i];
- }else {
- double x = m/p[i];
- //m = 0;
- minW[i] = x;
- minWP += (m*p[i])/w[i];
- m = 0;
- }
- }
- }
- for(int i =0;i<p.length;i++) {
- System.out.print(minW[i]+" ");
- }
- System.out.println("");
- System.out.println(minWP);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement