2

I came across the following programming challenge recently:

Statement

Consider a 2D square matrix of size NxN containing 0s and 1s. You have to cover all the 1s in the matrix using squares of size 1, 2 or 3. The coverage cost using square of size 1 is 2, using square of size 2 is 4 and using square of size 3 is 7. The objective is to find the minimum coverage cost to cover all the 1s in matrix.

Constraints

1 <= N <= 100

General Comments

  • Overlapping covering squares are allowed.
  • It is not necessary that the covering square should cover only 1s - they may cover cells containing 0s as well.

Example

Consider the following matrix as an example:

0 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0
0 1 1 1 0 0 0 0
0 0 1 1 1 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0
0 0 0 0 0 1 1 0
0 0 0 0 0 0 1 0

In above example, minimum coverage cost is 7x1 + 4x2 + 2x1 = 17. Another covering is possible with minimum coverage cost of 7x1 + 4x1 + 2x3 = 17.

Cover 1 Cover 2

My Approach

I tried to approach the problem in the following manner:

  1. Use square of size 3 to cover 1s where number of 1s in any 3x3 area is >= 5. Remove those 1s from the matrix.
  2. Next, use square of size 2 to cover 1s where number of 1s in any 2x2 area is >= 2. Remove those 1s from the matrix.
  3. Cover remaining 1s with sqaure of size 1.

This approach is greedy and is not optimal. For the example above, my approach gives answer 7x1 + 4x2 + 2x2 = 19 which is not optimal.

Greedy Cover

Any pointers about how to approach this problem or references to known problems which can be used to solve this one are appreciated. Thanks.

Update

Taking a cue from @bvdb answer, I updated the approach to select the coverage squares based on the number of 1s they are covering. However, the approach is still non-optimal. Consider a scenario where we have the following arrangement:

1 0 1
0 0 0
1 0 1

This arrangement will be covered using 4 coverage squares of size 1 whereas they must be covered using 1 square of size 3. In general, 5 1s in 3x3 area must be covered using different strategies based on how they are spread in the area. I can hardcode it for all types of cases, but I am looking for an elegant solution, if it exists.

2 Answers 2

1

Your problem is a typical Packing problem.

Your approach of fitting the biggest box first makes perfect sense.

A simple way to make your algorithm better, is to just give preference to 3x3 squares with maximum conent.

Example:

  1. Use square of size 3 to cover 1s where number of 1s in any 3x3 area is = 9. Remove those 1s from the matrix.
  2. Idem, but where area is = 8.
  3. Idem, but where area is = 7.
  4. Idem, but where area is = 6.
  5. Next, use square of size 2 to cover 1s where number of 1s in any 2x2 area is = 4. Remove those 1s from the matrix.
  6. etc ...

Monte carlo method

But if you want to add overlap, then it gets more tricky. I am sure you could work it out mathematically. However, when logic becomes tricky, then the Monte Carlo method always comes to mind:

Monte Carlo methods (or Monte Carlo experiments) are a broad class of computational algorithms that rely on repeated random sampling to obtain numerical results. They are often used in physical and mathematical problems and are most useful when it is difficult or impossible to use other mathematical methods.

Monte Carlo trades coded logic for speed and randomness:

STEP 1: repeat 4 times:
  cor = randomCoordinate()
  if ( hasContent(cor, 3) ) then putSquare(cor, 3)

STEP 2: repeat 16 times:
  cor = randomCoordinate()
  if ( hasContent(cor, 2) ) then putSquare(cor, 2)

STEP 3: corList = getFreeSquaresWithContent()
putSquare(corlist, 1)

calculateScore()
store used squares and score.

This code should be simple but really fast. Then run this 100.000 times, and keep the top 10 scores. Which 3x3 squares did the winners use most often? Use this information as a "starting position".

Now, run it again from STEP2 using this starting position. This means that the 100.000 iterations don't have to focus on the 3x3 squares any more, they immediately start adding 2x2 squares.

PS: The number of iterations you do (e.g. 100.000) is really a matter of the required response time and the required accuracy. You should test this to find out what is acceptable.

2
  • 1
    Thank you for the approach. However, I am looking for a deterministic approach where I can prove its correctness.
    – Bhoot
    Apr 27, 2015 at 10:18
  • Agreed, that's why I posted a second answer :).
    – bvdb
    Apr 27, 2015 at 16:00
1

If you are looking for a deterministic approach.

I think the best thing to do is to sort all possible patterns in an optimal order. There are only 394 relevant patterns. There is no need to hardcode them, you can generate them on-the-fly.

First our definitions (rules of the game). Each square has a size and a cost.

  class Square
  {
    private int size;
    private int cost;

    Square(int pSize, int pCost)
    {
      size = pSize;
      cost = pCost;
    }
  }

And there are only 3 types of squares. squareOne keeps the cost of a 1x1 matrix, squareTwofor a 2x2 and squareThree for a 3x3 matrix.

  Square squareOne = new Square(1, 2);
  Square squareTwo = new Square(2, 4);
  Square squareThree = new Square(3, 7);
  List<Square> definitions = Arrays.asList(squareOne, squareTwo, squareThree);

We are going to have to store each pattern with its cost, number of hits, and its cost per hit (efficiency). So here follows the class that I am using to store it. Note that this class contains methods that help to perform the sorting as well as conversions to a matrix of boolean's (1/0 values).

  class ValuedPattern implements Comparable<ValuedPattern>
  {
    private long pattern;
    private int size;
    private int cost;
    private double costPerHit;
    private int hits;

    ValuedPattern(long pPattern, int pSize, int pCost)
    {
      pattern = pPattern;
      cost = pCost;
      size = pSize;

      // calculate the efficiency
      int highCount = 0;
      BitSet set = BitSet.valueOf(new long[]{pattern});
      for (int i = 0; i < set.size(); i++)
      {
        if (set.get(i)) highCount++;
      }
      hits = highCount;
      costPerHit = (double) cost / (double) hits;
    }

    public boolean[][] toArray()
    {
      boolean[][] patternMatrix = new boolean[size][size];

      BitSet set = BitSet.valueOf(new long[]{pattern});
      for (int i = 0; i < size; i++)
      {
        for (int j = 0; j < size; j++)
        {
          patternMatrix[i][j] = set.get(i * size + j);
        }
      }
      return patternMatrix;
    }

    /**
     * Sort by efficiency
     * Next prefer big matrixes instead of small ones.
     */
    @Override
    public int compareTo(ValuedPattern p)
    {
      if (p == null) return 1;
      if (costPerHit < p.costPerHit) return -1;
      if (costPerHit > p.costPerHit) return 1;
      if (hits > p.hits) return -1;
      if (hits < p.hits) return 1;
      if (size > p.size) return -1;
      if (size < p.size) return 1;
      return Long.compare(pattern, p.pattern);
    }

    @Override
    public boolean equals(Object obj)
    {
      if (! (obj instanceof ValuedPattern)) return false;
      return (((ValuedPattern) obj).pattern == pattern) &&
             (((ValuedPattern) obj).size == size);
    }
  }

Next we are going to store all possible patterns in a sorted collection (i.e. a TreeSet sorts its content automatically using the compareTo method of the object).

Since your patterns are just 0 and 1 values, you can think of them as numeric values (long is a 64bit integer which is more than enough) which can be converted later to a boolean matrix. The size of the pattern is the same as the number of bits of that numeric value. Or in other words there are 2^x possible values, with x being the number of cells in your pattern.

  // create a giant list of all possible patterns :)
  Collection<ValuedPattern> valuedPatternSet = new TreeSet<ValuedPattern>();
  for (Square square : definitions)
  {
    int size = square.size;
    int bits = size * size;
    long maxValue = (long) Math.pow(2, bits);
    for (long i = 1; i < maxValue; i++)
    {
      ValuedPattern valuedPattern = new ValuedPattern(i, size, square.cost);

      // filter patterns with a rediculous high cost per hit.
      if (valuedPattern.costPerHit > squareOne.cost) continue;

      // and store the result for later
      valuedPatternSet.add(valuedPattern);
    }
  }

After composing the list, the patterns are already sorted according to efficiency. So now you can just apply the logic that you already have.

  // use the list in that order
  for (ValuedPattern valuedPattern : valuedPatternSet)
  {
    boolean[][] matrix = valuedPattern.toArray();
    System.out.println("pattern" + Arrays.deepToString(matrix) + " has cost/hit: " + valuedPattern.costPerHit);
    // todo : do your thing :)
  }

The demo code above outputs all patterns with their efficiency. Note that smaller patterns sometimes have a better efficiency than the bigger ones.

Pattern [[true, true, true], [true, true, true], [true, true, true]] has cost/hit: 0.7777777777777778
Pattern [[true, true, true], [true, true, true], [true, true, false]] has cost/hit: 0.875
Pattern [[true, true, true], [true, true, true], [true, false, true]] has cost/hit: 0.875
Pattern [[true, true, true], [true, true, true], [false, true, true]] has cost/hit: 0.875
...

The entire thing runs in just a couple of ms.

EDIT: I added some more code, which I am not going to drop here (but don't hesitate to ask, then I'll e-mail it to you). But I just wanted to show the result it came up with:

Result

EDIT2: I am sorry to tell you that you are correct to question my solution. It turns out there is a case where my solution fails:

0 0 0 0 0 0
0 1 1 1 1 0
0 1 1 1 1 0
0 1 1 1 1 0
0 1 1 1 1 0
0 0 0 0 0 0

My solution is greedy, in the sense that it immediatly tries to apply the most efficient pattern:

1 1 1
1 1 1
1 1 1

Next only the following remains:

0 0 0 0 0 0
0 _ _ _ 1 0
0 _ _ _ 1 0
0 _ _ _ 1 0
0 1 1 1 1 0
0 0 0 0 0 0

Next it will use three 2x2 squares to cover the remains. So the total cost = 7 + 3*4 = 19

The best way of course would have been to use four 2x2 squares. With a total cost of 4*4 = 16

Conclusion: So, even though the first 3x3 was very efficient, the next 2x2 patterns are less efficient. Now that you know this exception you could add it to the list of patterns. E.g. a square with size 4 has cost 16. However, that wouldn't solve it, a 3x3 would still have a lower cost/hit and would always be considered first. So, my solution is broken.

2
  • Thank you for taking the time for this post. I am still thinking about the correctness of this solution. I will get back as soon as I am convinced.
    – Bhoot
    Apr 28, 2015 at 8:00
  • @Bhoot, you are correct, it's not perfect. It will fail when presented with a 4x4 region of 1 values.
    – bvdb
    Apr 28, 2015 at 12:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.