Ivan18113

Алгоритми - Тема 08

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