Advertisement
Boyan5

Backpack

Nov 26th, 2020
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.19 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class algo {
  4.     static class Topic08 {
  5.         public static void sortWeights(int[] weights){
  6.             for(int i = 1; i < weights.length;i++){
  7.                 int getedEl = weights[i];
  8.                 int lastSorted = i - 1;
  9.                 while(lastSorted >= 0 && weights[lastSorted] < getedEl){
  10.                     weights[lastSorted + 1] = weights[lastSorted];
  11.                     lastSorted --;
  12.                 }
  13.                 weights[lastSorted + 1] = getedEl;
  14.             }
  15.         }
  16.         public static void bagPackageCounterCheck(int capacity, int[] weights){
  17.             int counter = 0;
  18.             int index = 0;
  19.             while(capacity > 0){
  20.                 if(index < weights.length){
  21.                     if(capacity / weights[index] > 0){
  22.                         capacity -= weights[index];
  23.                         counter++;
  24.                         System.out.println("Capacity is " + capacity + " Weight -> " + weights[index] + " Counter -> " + counter );
  25.                     }else{
  26.  
  27.                         index++;
  28.                     }
  29.  
  30.                 }else{
  31.                     System.out.print("The backpack cannot be filled with these packages!Rest is :" + capacity);
  32.                     break;
  33.                 }
  34.             }
  35.  
  36.         }
  37.  
  38.         public static void main(String[] args) {
  39.  
  40.             Scanner scanner = new Scanner(System.in);
  41.  
  42.             System.out.print("Enter backpack capacity --> ");
  43.             int bagCapacity = scanner.nextInt();
  44.             System.out.print("How many items you have for backpack (2-5) --> ");
  45.             int items = scanner.nextInt();
  46.             int[] itemWeight = new int[items];
  47.             while(items < 2 || items > 5 ){
  48.                 System.out.print("Enter valid number -- > ");
  49.                 items = scanner.nextInt();
  50.             }
  51.  
  52.  
  53.             for(int i = 0; i < items;i++){
  54.                 System.out.printf("How many kilograms do the items weight? [%d] :",i);
  55.                 itemWeight[i] = scanner.nextInt();
  56.             }
  57.  
  58.  
  59.  
  60.             sortWeights(itemWeight);
  61.  
  62.             bagPackageCounterCheck(bagCapacity , itemWeight);
  63.  
  64.         }
  65.     }
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement