Skip to content

Instantly share code, notes, and snippets.

@leosabbir
Last active July 24, 2019 17:47
Show Gist options
  • Save leosabbir/baf2aaccc98477dbb8d3b0193520194b to your computer and use it in GitHub Desktop.
Save leosabbir/baf2aaccc98477dbb8d3b0193520194b to your computer and use it in GitHub Desktop.
Minimum number of boats required to save population
/* File: Boats.java
* Created: 7/24/2019
* Author: Sabbir Manandhar
*
* Copyright (c) 2019 Hogwart Inc.
*/
import java.util.Arrays;
import java.util.Collections;
//=======================================================================================
/**
* @author Sabbir Manandhar
* @version 1.0
*/
public class Boats {
/**
* Driver method
*/
public static void main(String[] args) {
System.out.println(compute(new Integer[]{100, 200, 150, 80}, 200) + " == " + 3);
System.out.println(compute(new Integer[]{30, 40, 70, 100, 200, 150, 80}, 200) + " == " + 4);
System.out.println(compute(new Integer[]{}, 1) + " == " + 0);
System.out.println(compute(new Integer[]{100}, 200) + " == " + 1);
System.out.println(compute(new Integer[]{200, 10, 200, 200}, 200) + " == " + 4);
System.out.println(compute(new Integer[]{200, 200, 10, 200, 200}, 200) + " == " + 5);
System.out.println(compute(new Integer[]{170, 160, 30, 90}, 200) + " == " + 3);
System.out.println(compute(new Integer[]{150, 150, 150, 30}, 200) + " == " + 3);
} // main
//-----------------------------------------------------------------------------------------------
/**
* Computes number of boats required
* @param weights array of weights of population
* @param limit weight limit of each boat
* @return number of boats needed
*
*/
public static int compute(Integer[] weights, int limit) {
if(weights.length == 0) return 0;
Arrays.sort(weights, Collections.reverseOrder());
boolean[] used = new boolean[weights.length];
int boats = 0;
for(int idx = 0; idx < weights.length; idx++) {
if (used[idx]) continue;
if (weights[idx] == limit) {
boats++;
continue;
}
int pair = findPair(weights, used, limit - weights[idx], idx+1, weights.length-1);
if (pair > -1) {
used[pair] = true;
}
boats++;
}
return boats;
} // compute
/**
* Find pairing for the limit provided
* @param weights
* @param used
* @param limit
* @param lo
* @param hi
* @return
*/
private static int findPair(Integer[] weights, boolean[] used, int limit, int lo, int hi) {
int lastValid = -1;
for (int i = hi; i >= lo; i--) {
if (!used[i]) {
if (weights[i] == limit) {
return i;
} else if (weights[i] < limit) {
lastValid = i;
} else {
return lastValid;
}
} else {
continue;
}
}
return lastValid;
} // findPair
} // Boats
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment