Package com.politikodrom.parking.engine

Source Code of com.politikodrom.parking.engine.Grid

package com.politikodrom.parking.engine;

import com.politikodrom.parking.engine.exceptions.InconsistentGridException;

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.Set;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Map;

public class Grid {
  private int height;
  private int width;
  private List<Vehicle> vehicles;

  public Grid(Level l) throws InconsistentGridException {
    this.setHeight(6);
    this.setWidth(6);
    this.setVehicles(l.getVehicles());
  }

  public void setHeight(int newHeight) {
    this.height = newHeight;
  }
 
  public int getHeight() {
    return this.height;
  }

  public void setWidth(int newWidth) {
    this.width = newWidth;
  }

  public int getWidth() {
    return this.width;
  }

  public void setVehicles(List<Vehicle> newVehicles) throws InconsistentGridException {
    boolean consistent;
    Set<Block> blocks;

    this.vehicles = new ArrayList<Vehicle>();
    consistent = true;

    for (Vehicle v : newVehicles) {
      blocks = this.getUsedBlocksAsSet();

      for (Block b : v.getUsedBlocks()) {
        if (blocks.contains(b)) throw new InconsistentGridException(b.toString());
      }

      this.vehicles.add(v);
    }
  }

  public Set<Block> getUsedBlocksAsSet() {
    Set<Block> blocks;

    blocks = new HashSet<Block>();

    if (this.vehicles != null) {
      for (Vehicle v : this.vehicles) {
        blocks.addAll(v.getUsedBlocks());
      }
    }

    return blocks;
  }

  public List<Block> getUsedBlocks() {
    return Arrays.asList((Block[]) this.getUsedBlocksAsSet().toArray());
  }

  public List<Vehicle> getVehicles() {
    return this.vehicles;
  }

  public Map<Block, Vehicle> getBlockMap() {
    int i, j;
    Map<Block, Vehicle> map;
    Map<Vehicle, Set<Block>> vehicleBlockMap;
    Set<Block> blocks;
    Vehicle current;
    Block b;

    map = new HashMap<Block, Vehicle>();
    vehicleBlockMap = new HashMap<Vehicle, Set<Block>>();

    for (Vehicle v : this.vehicles) {
      vehicleBlockMap.put(v, new HashSet<Block>(v.getUsedBlocks()));
    }

    for (j = 0; j < this.height; j++) {
      for (i = 0; i < this.width; i++) {
        b = new Block(i, j);
        current = null;

        for (Map.Entry<Vehicle, Set<Block>> m : vehicleBlockMap.entrySet()) {
          blocks = m.getValue();

          if (blocks.contains(b)) {
            current = m.getKey();
            break;
          }
        }

        map.put(b, current);
      }
    }

    return map;
  }
}
TOP

Related Classes of com.politikodrom.parking.engine.Grid

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.