Balance server capacity

By | December 25, 2014
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

Problem description:
There are at most eight servers in a data center. Each server has got a capacity/memory limit. There can be at most 8 tasks that need to be scheduled on those servers. Each task requires certain capacity/memory to run, and each server can handle multiple tasks as long as the capacity limit is not hit. Write a program to see if all of the given tasks can be scheduled or not on the servers?

Ex:
Servers capacity limits: 8, 16, 8, 32
Tasks capacity needs: 18, 4, 8, 4, 6, 6, 8, 8
For this example, the program should say ‘true’.

Ex2:
Server capacity limits: 1, 3
Task capacity needs: 4
For this example, program should return false.

Solution:
First impression would be using greedy algorith. Each time, put the max task in the max capacity server. But it won’t find the best answer for a lot of times. An counter-example is: Server capacity [4, 3], task[3, 2, 2].

So the solution should be use recursion to traverse the whole result possibilities. The sample code is following. It is a easy recursion case, no comment :)

  1. public class ServerCapacityBalancer {
  2.     public static void main(String[] args) {
  3.         int[] server = {8, 16, 8, 32};
  4.         int[] task = {18,8,8,8,6,6,4,4};
  5.         int[] result = balanceServer(server, task);
  6.         System.out.println(Arrays.toString(result));
  7.     }
  8.     public static int[] balanceServer(int[] server, int[] task){
  9.         if(server==null||task==null){
  10.             return null;
  11.         }
  12.         int[] result = new int[task.length];
  13.         for(int i=0;i
  14.             result[i] = -1;
  15.         }
  16.         balanceServerUtil(server, task, 0, result);
  17.         return result;
  18.     }
  19.     //put task[n] in the server, and save the result
  20.     public static boolean balanceServerUtil(int[] server, int[] task, int n, int[] result){
  21.         if(n>=task.length){
  22.             return true;
  23.         }
  24.         for(int i=0;i
  25.             if(server[i]>=task[n]){
  26.                 server[i] -= task[n];
  27.                 result[n] = i;
  28.                 if(balanceServerUtil(server, task, n+1, result)){
  29.                     return true;
  30.                 }
  31.                 server[i] += task[n];
  32.                 result[n] = -1;
  33.             }
  34.         }
  35.         return false;
  36.     }
  37. }