Advertisement
TsetsoP

tema 08

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