Пример #1
1
  @Test
  public final void testTotalBoxedLongBoxedLongBoxedLongBoxedLongBoxedLongMoreBoxedLongs() {
    final Long[] numbers1 = convertToBoxed(NUMBERS1);
    final Long[] numbers2 = convertToBoxed(NUMBERS2);

    for (final Long n1 : numbers1) {
      for (final Long n2 : numbers2) {
        for (final Long n3 : numbers1) {
          for (final Long n4 : numbers2) {
            for (final Long n5 : numbers1) {
              @SuppressWarnings("boxing")
              final Long expected1 = (n1 + n2 + n3 + n4 + n5 + n1 + n2 + n3 + n4 + n5);
              @SuppressWarnings("boxing")
              final Long actual1 = total(n1, n2, n3, n4, n5, n1, n2, n3, n4, n5);
              // System.out.println("expected: " + expected1 + "\nactual:   " + actual1);
              assertThat(actual1, is(equalTo(expected1)));

              @SuppressWarnings("boxing")
              final Long expected2 = (n1 + n2 + n3 + n4 + n5 + n1 + n2 + n3 + n4 + n5);
              @SuppressWarnings("boxing")
              final Long actual2 = total(n1, n2, n3, n4, n5, n1, n2, n3, n4, n5);
              // System.out.println("expected: " + expected2 + "\nactual:   " + actual2);
              assertThat(actual2, is(equalTo(expected2)));
            }
          }
        }
      }
    }

    final Long[] numbers3 = new Long[NUMBERS3.length];
    System.arraycopy(convertToBoxed(NUMBERS3), 0, numbers3, 0, NUMBERS3.length);
    final Long[] numbers4 = new Long[NUMBERS4.length];
    System.arraycopy(convertToBoxed(NUMBERS4), 0, numbers4, 0, NUMBERS4.length);

    for (final Long n1 : numbers3) {
      for (final Long n2 : numbers4) {
        for (final Long n3 : numbers3) {
          for (final Long n4 : numbers4) {
            for (final Long n5 : numbers3) {
              @SuppressWarnings("boxing")
              final Long expected3 = (n1 + n2 + n3 + n4 + n5 + n1 + n2 + n3 + n4 + n5);
              @SuppressWarnings("boxing")
              final Long actual3 = total(n1, n2, n3, n4, n5, n1, n2, n3, n4, n5);
              // System.out.println("expected: " + expected3 + "\nactual:   " + actual3);
              assertThat(actual3, is(equalTo(expected3)));

              @SuppressWarnings("boxing")
              final Long expected4 = (n1 + n2 + n3 + n4 + n5 + n1 + n2 + n3 + n4 + n5);
              @SuppressWarnings("boxing")
              final Long actual4 = total(n1, n2, n3, n4, n5, n1, n2, n3, n4, n5);
              // System.out.println("expected: " + expected4 + "\nactual:   " + actual4);
              assertThat(actual4, is(equalTo(expected4)));
            }
          }
        }
      }
    }
  }
Пример #2
1
  @Test
  public final void testSumLongLongLongLongLongLongArray() {
    final long[] numbers1 = NUMBERS1;
    final long[] numbers2 = NUMBERS2;

    for (final long n1 : numbers1) {
      for (final long n2 : numbers2) {
        for (final long n3 : numbers1) {
          for (final long n4 : numbers2) {
            for (final long n5 : numbers1) {

              long total1 = n1 + n2 + n3 + n4 + n5;
              for (final long n : numbers1) total1 += n;

              @SuppressWarnings("boxing")
              final Long expected1 = total1;
              @SuppressWarnings("boxing")
              final Long actual1 = sum(n1, n2, n3, n4, n5, numbers1);
              // System.out.println("expected: " + expected1 + "\nactual:   " + actual1);
              assertThat(actual1, is(equalTo(expected1)));

              long total2 = n1 + n2 + n3 + n4 + n5;
              for (final long n : numbers2) total2 += n;

              @SuppressWarnings("boxing")
              final Long expected2 = total2;
              @SuppressWarnings("boxing")
              final Long actual2 = sum(n1, n2, n3, n4, n5, numbers2);
              // System.out.println("expected: " + expected2 + "\nactual:   " + actual2);
              assertThat(actual2, is(equalTo(expected2)));
            }
          }
        }
      }
    }

    final long[] numbers3 = new long[NUMBERS3.length];
    System.arraycopy(NUMBERS3, 0, numbers3, 0, NUMBERS3.length);
    final long[] numbers4 = new long[NUMBERS4.length];
    System.arraycopy(NUMBERS4, 0, numbers4, 0, NUMBERS4.length);

    for (final long n1 : numbers3) {
      for (final long n2 : numbers4) {
        for (final long n3 : numbers3) {
          for (final long n4 : numbers4) {
            for (final long n5 : numbers3) {
              long total3 = n1 + n2 + n3 + n4 + n5;
              for (final long n : numbers3) total3 += n;

              @SuppressWarnings("boxing")
              final Long expected3 = total3;
              @SuppressWarnings("boxing")
              final Long actual3 = sum(n1, n2, n3, n4, n5, numbers3);
              // System.out.println("expected: " + expected3 + "\nactual:   " + actual3);
              assertThat(actual3, is(equalTo(expected3)));

              long total4 = n1 + n2 + n3 + n4 + n5;
              for (final long n : numbers4) total4 += n;

              @SuppressWarnings("boxing")
              final Long expected4 = total4;
              @SuppressWarnings("boxing")
              final Long actual4 = sum(n1, n2, n3, n4, n5, numbers4);
              // System.out.println("expected: " + expected4 + "\nactual:   " + actual4);
              assertThat(actual4, is(equalTo(expected4)));
            }
          }
        }
      }
    }
  }
Пример #3
0
  /** testowanie przykładowego zadania */
  static void anagramTest() {
    Matcher<Integer> odd =
        new Predicate<Integer>() {
          public boolean apply(Integer item) {
            return item % 2 == 1;
          }
        };

    long l1 = System.nanoTime();
    isAnagramOfPalindrome("ZAble was I ere I saw ElbaZ".toLowerCase().replace(" ", ""));
    long l2 = System.nanoTime();
    System.out.println(
        "result : "
            + isAnagramOfPalindrome("ZAble was I ere I saw ElbaZ".toLowerCase().replace(" ", "")));
    System.out.println(
        "result : "
            + isAnagramOfPalindrome("Rats live on no evil star".toLowerCase().replace(" ", "")));
    System.out.println("result : " + isAnagramOfPalindrome("kayak"));
    System.out.println("result : " + isAnagramOfPalindrome("rraattsslliivveeoonn"));

    System.out.println("=======================================");
    long l3 = System.nanoTime();
    isAnagram_lambda("ZAble was I ere I saw ElbaZ".toLowerCase().replace(" ", ""), odd);
    long l4 = System.nanoTime();
    System.out.println(
        "result : "
            + isAnagram_lambda("ZAble was I ere I saw ElbaZ".toLowerCase().replace(" ", ""), odd));
    System.out.println(
        "result : "
            + isAnagram_lambda("Rats live on no evil star".toLowerCase().replace(" ", ""), odd));
    System.out.println("result : " + isAnagram_lambda("kayak", odd));
    System.out.println("result : " + isAnagram_lambda("rraattsslliivveeoonn", odd));

    System.out.println("lambda/classic : " + (l4 - l3) / (l2 - l1));
  }
Пример #4
0
 public static void main(String args[]) {
   try {
     System.setIn(new FileInputStream("vans.in"));
     System.setOut(new PrintStream("vans.out"));
   } catch (Throwable T_T) {
   }
   new vans().run();
 }
Пример #5
0
 private static void setStream(String in, String out) {
   try {
     System.setIn(new BufferedInputStream(new FileInputStream(in)));
     System.setOut(new PrintStream(out));
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Пример #6
0
 public static void main(String[] args) {
   InputReader in = new InputReader(System.in);
   OutputWriter out = new OutputWriter(System.out);
   A1Task solver = new A1Task();
   solver.solve(in, out);
   out.close();
   System.exit(0);
 }
Пример #7
0
  /**
   * Łączenie list w jeden łańcuch znakowy
   *
   * @param p lista osób do połączenia
   */
  public static void joinStrings(List<Person> p) {
    long l1 = System.nanoTime();
    String s1 = "";
    for (Person p1 : p) {
      s1 += p1.toString() + "\n";
    }
    long l2 = System.nanoTime();

    // System.out.println(s1);
    // System.out.println("================================================");

    long l3 = System.nanoTime();
    String s2 = joinFrom(p, "\n").toString();
    long l4 = System.nanoTime();
    // System.out.println(s2);

    System.out.println("lambda/classic : " + (l4 - l3) / (l2 - l1));
  }
Пример #8
0
  /**
   * Ekstraktownie zadanej własności do listy
   *
   * @param p
   */
  public static void extraktowanie(List<Person> p) {
    long l1 = System.nanoTime();
    List<String> names1 = new ArrayList<String>();
    for (Person pers : p) {
      names1.add(pers.getName());
    }
    long l2 = System.nanoTime();

    long l3 = System.nanoTime();
    List<String> names2 = extract(p, on(Person.class).getName());
    long l4 = System.nanoTime();

    //		StartLambda.print.each(names1);
    //		System.out.println("===============================================");
    //		StartLambda.print.each(names2);
    //		System.out.println("===============================================");

    System.out.println("lambda/classic : " + (((double) (l4 - l3)) / ((double) (l2 - l1))));
  }
Пример #9
0
  void run() {
    Scanner sc = new Scanner(System.in);
    int oo = sc.nextInt();
    for (int o = 1; o <= oo; o++) {
      que = new PriorityQueue<E>();
      int n = sc.nextInt();
      tank = new Tank();
      count = 0;
      int[] h = new int[n + 3], b = new int[n + 3];
      h[0] = 100;
      b[0] = 0;
      h[n + 1] = 50;
      b[n + 1] = 100;
      h[n + 2] = 50;
      b[n + 2] = INF;
      for (int i = 1; i <= n; i++) {
        b[i] = sc.nextInt();
        h[i] = sc.nextInt();
      }
      n += 3;
      for (int i = 1; i < n; i++) {
        tank.bs.add(new Box(b[i - 1], b[i], h[i - 1], h[i], 0, 0));
      }
      int m = sc.nextInt();
      for (int i = 0; i < m; i++) {
        int f = sc.nextInt();
        double a = sc.nextDouble() / 30;
        for (Box box : tank.bs) {
          if (box.b1 < f && f < box.b2) box.f += a;
        }
      }
      debug(tank.bs);

      int l = sc.nextInt();
      res = new double[l];
      for (int i = 0; i < l; i++) {
        que.offer(new W(sc.nextInt(), sc.nextDouble(), i));
      }
      que.offer(tank.nextEvent());
      debug(que.size());
      while (!que.isEmpty()) {
        if (res[0] < 0) System.exit(1);
        que.poll().go();
        debug(que.peek().time());
        debug(tank.bs);
        debug(res);
        debug();
        if (count == l) break;
      }
      for (double r : res) {
        System.out.println(r);
      }
    }
  }
Пример #10
0
  /**
   * sortowanie, klasyczny sposób - sortowanie przez wstawianie - najbardziej przewidywalny algorytm
   *
   * @param p
   */
  public static void sortowanie(List<Person> p) {
    // ArrayList<Object> p1 = new ArrayList<Object>((index(p, on(Person.class).getName() )).values()
    // );
    // ArrayList<Object> p2 = new ArrayList<Object>((index(p, on(Person.class).getName() )).values()
    // );
    ArrayList<Person> p1 = new ArrayList<Person>(p);
    ArrayList<Person> p2 = new ArrayList<Person>(p);

    List<Person> ps2 = null;

    // klasyczne sortowanie przez wstawianie

    StartLambda.print.each(p1);
    System.out.println("===============================================");

    long l1 = System.nanoTime();
    for (int i = 0; i < p1.size(); i++) {
      // System.out.println(((Person)p1.get(i)).getName());
      // System.out.println("==");
      for (int j = i; j > 0; j--) {
        if (((Person) p1.get(j - 1)).getName().compareTo(((Person) p1.get(j)).getName()) > 0) {
          Person tmp = (Person) p1.get(j - 1);
          p1.set(j - 1, p1.get(j));
          p1.set(j, tmp);
        }
      }
    }
    long l2 = System.nanoTime();

    System.out.println("===============================================");
    StartLambda.print.each(p1);
    System.out.println("===============================================");

    long l3 = System.nanoTime();
    ps2 = sort(p2, on(Person.class).getName());
    long l4 = System.nanoTime();

    StartLambda.print.each(ps2);

    System.out.println("lambda/classic : " + (((double) (l4 - l3)) / ((double) (l2 - l1))));
  }
Пример #11
0
 public static void main(String[] args) throws IOException {
   // InputStream inputStream = new FileInputStream("replaceme.in");
   // OutputStream outputStream = new FileOutputStream("replaceme.out");
   /////////////////////////////////////////////////////////////////////
   InputStream inputStream = System.in;
   OutputStream outputStream = System.out;
   InputReader in = new InputReader(inputStream);
   OutputWriter out = new OutputWriter(outputStream);
   Task solver = new Task();
   solver.solve(1, in, out);
   out.close();
   System.exit(0);
 }
  public void addGestureTrace(String id, ArrayList<float[]> trace, boolean addToDB) {
    /*
     *  reads a gesture id and a trace and then adds it to
     *  gesture hashmap and optionally saves it to the DB
     */
    Gesture g = new Gesture();
    g.databaseID = -1; /* not known to database yet */
    g.gestureTrace = trace;
    g.gestureID = id;
    g.gestureAdded = System.currentTimeMillis();

    this.addGesture(id, g, addToDB);
  }
 void run() throws Exception {
   long s = System.currentTimeMillis();
   solve();
   out.flush();
   pr(System.currentTimeMillis() - s + "ms");
 }
public class _336_D_Bear_Vasily_and_Beautiful_Strings {
  // ->solution screencast http://youtu.be/oHg5SJYRHA0
  public void solve() {
    int n = ni();
    long res = 0;

    out.println(res);
  }

  // IO methods

  void run() throws Exception {
    long s = System.currentTimeMillis();
    solve();
    out.flush();
    pr(System.currentTimeMillis() - s + "ms");
  }

  public static void main(String[] args) throws Exception {
    new _336_D_Bear_Vasily_and_Beautiful_Strings().run();
  }

  InputStream in = System.in;
  PrintWriter out = new PrintWriter(System.out);

  private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
  private byte[] inbuf = new byte[1024];
  private int lenbuf = 0, ptrbuf = 0;

  private int readByte() {
    if (lenbuf == -1) throw new InputMismatchException();
    if (ptrbuf >= lenbuf) {
      ptrbuf = 0;
      try {
        lenbuf = in.read(inbuf);
      } catch (IOException e) {
        throw new InputMismatchException();
      }
      if (lenbuf <= 0) return -1;
    }
    return inbuf[ptrbuf++];
  }

  private boolean isSpaceChar(int c) {
    return !(c >= 33 && c <= 126);
  }

  private int skip() {
    int b;
    while ((b = readByte()) != -1 && isSpaceChar(b)) ;
    return b;
  }

  public String ns() {
    int b = skip();
    StringBuilder sb = new StringBuilder();
    while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != // ' ')
      sb.appendCodePoint(b);
      b = readByte();
    }
    return sb.toString();
  }

  public char[] ns(int n) {
    char[] buf = new char[n];
    int b = skip(), p = 0;
    while (p < n && !(isSpaceChar(b))) {
      buf[p++] = (char) b;
      b = readByte();
    }
    return n == p ? buf : Arrays.copyOf(buf, p);
  }

  public char[][] nm(int n, int m) {
    char[][] map = new char[n][];
    for (int i = 0; i < n; i++) map[i] = ns(m);
    return map;
  }

  public int[] na(int n) {
    int[] a = new int[n];
    for (int i = 0; i < n; i++) a[i] = ni();
    return a;
  }

  public int ni() {
    int num = 0, b;
    boolean minus = false;
    while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
    if (b == '-') {
      minus = true;
      b = readByte();
    }

    while (true) {
      if (b >= '0' && b <= '9') {
        num = num * 10 + (b - '0');
      } else {
        return minus ? -num : num;
      }
      b = readByte();
    }
  }

  public long nl() {
    long num = 0;
    int b;
    boolean minus = false;
    while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
    if (b == '-') {
      minus = true;
      b = readByte();
    }
    while (true) {
      if (b >= '0' && b <= '9') {
        num = num * 10 + (b - '0');
      } else {
        return minus ? -num : num;
      }
      b = readByte();
    }
  }

  void pr(Object... ob) {
    if (!oj) System.out.println(Arrays.deepToString(ob).replace("],", "],\n"));
  }
}
Пример #15
0
  void run() throws Exception {
    System.setOut(new PrintStream(new FileOutputStream("tmp.out")));
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 1 << 13);
    int N = Integer.parseInt(br.readLine());
    int[] len =
        new int[] {
          64, 32, 16, 8, 4, 2, 1, 96, 48, 24, 12, 6, 3, 112, 56, 28, 14, 7, 120, 60, 30, 15, 124,
          62, 31, 126, 63, 127
        };
    String[] onpu =
        new String[] {
          "R1",
          "R2",
          "R4",
          "R8",
          "R16",
          "R32",
          "R64",
          "R1.",
          "R2.",
          "R4.",
          "R8.",
          "R16.",
          "R32.",
          "R1..",
          "R2..",
          "R4..",
          "R8..",
          "R16..",
          "R1...",
          "R2...",
          "R4...",
          "R8...",
          "R1....",
          "R2....",
          "R4....",
          "R1.....",
          "R2.....",
          "R1......"
        };
    String[] dp = new String[max];
    dp[0] = "R1.A";
    //        debug(dp[0]);
    for (int i = 1; i < max; i++) {
      String ns = null;
      for (int j = 0; j < onpu.length; j++) {
        int ni = i - len[j];
        if (ni >= 0) {
          String s1 = dp[ni] + onpu[j];
          if (ns == null || isleast(s1, ns)) {
            ns = s1;
          }
        }
      }
      for (int j = 0; j < onpu.length; j++) {
        int ni = i - len[j];
        if (ni >= 0) {
          String s1 = onpu[j] + dp[ni];
          if (isleast(s1, ns)) {
            ns = s1;
          }
        }
      }
      dp[i] = ns;
    }

    //        debug(dp);

    for (int n = 0; n < N; n++) {
      String[] rests = br.readLine().split("R");
      int[] dots = new int[rests.length - 1];
      for (int i = 1; i < rests.length; i++)
        for (int j = rests[i].length() - 1; j >= 0 && rests[i].charAt(j) == '.'; j--) dots[i - 1]++;
      //            debug(rests, dots);
      int[] nums = new int[rests.length - 1];
      for (int i = 1; i < rests.length; i++)
        nums[i - 1] = Integer.parseInt((rests[i].split("\\."))[0]);
      int sum = 0;
      for (int i = 0; i < nums.length; i++) {
        sum += 64 / nums[i];
        sum += (64 / nums[i]) - ((64 / nums[i]) >> dots[i]);
      }
      //            debug(sum);
      int mod = sum;

      StringBuffer f = new StringBuffer("");
      for (; mod >= max; mod -= 192) {
        f.append("R1.R1.");
      }
      //            debug(rests, sum, mod, max);
      String res = dp[mod].replace("R1.A", f.toString());
      System.out.println(res);
    }
  }
public class World {
  public World evolve() {
    return new World(locationsOfSurvivingCells(), locationsOfNewbornCells());
  }

  // Creation Methods
  // ///////////////////////////////////////////////////////////////////////////////////////////

  public static World empty() {
    return new World();
  }

  public static World withCellsAt(Location... locations) {
    return new World(Arrays.asList(locations));
  }

  public static World withCellsAt(List<Location>... groupsOfLocations) {
    return new World(groupsOfLocations);
  }

  // Predicates
  // /////////////////////////////////////////////////////////////////////////////////////////////////

  public boolean hasLiveCellAt(Location location) {
    return liveCellLocations.contains(location);
  }

  public boolean isEmpty() {
    return liveCellLocations.isEmpty();
  }

  // Overridden Object methods
  // //////////////////////////////////////////////////////////////////////////////////

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    World world = (World) o;

    return liveCellLocations.equals(world.liveCellLocations);
  }

  @Override
  public int hashCode() {
    return liveCellLocations.hashCode();
  }

  @Override
  public String toString() {
    return toString(buildGridOfLocations());
  }

  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
  // Private
  // ////////////////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

  // Member fields
  // //////////////////////////////////////////////////////////////////////////////////////////////
  private final HashSet<Location> liveCellLocations;

  // Constructors
  // ///////////////////////////////////////////////////////////////////////////////////////////////
  private World(List<Location>... groupsOfLocations) {

    liveCellLocations = new HashSet<>();

    stream(groupsOfLocations).flatMap(List::stream).forEach(liveCellLocations::add);
  }

  // Location of Surviving Cells
  // ////////////////////////////////////////////////////////////////////////////////

  private List<Location> locationsOfSurvivingCells() {
    return liveCellLocations.stream().filter(aCellWillSurviveAt).collect(toList());
  }

  private Predicate<Location> aCellWillSurviveAt =
      location -> NEIGHBOUR_COUNTS_ALLOWING_SURVIVAL.contains(countOfNeighbouringCellsAt(location));

  private long countOfNeighbouringCellsAt(Location location) {
    return neighboursOf(location).stream().filter(isPopulated).count();
  }

  // Locations of Newborn Cells
  // /////////////////////////////////////////////////////////////////////////////////

  private List<Location> locationsOfNewbornCells() {
    return liveCellLocations
        .stream()
        .flatMap(
            l1 ->
                liveCellLocations
                    .stream()
                    .flatMap(
                        l2 ->
                            liveCellLocations
                                .stream()
                                .flatMap(
                                    l3 ->
                                        areInNeighbourhoodOfSomeCell(l1, l2, l3)
                                            ? emptyLocationsWithLiveNeighboursInAllAndOnlyLocations(
                                                l1, l2, l3)
                                            : Stream.empty())))
        .collect(toList());
  }

  private boolean areInNeighbourhoodOfSomeCell(Location... locations) {
    return distinct(locations) && distantAtMostOneCell(locations);
  }

  private boolean distinct(Location... locations) {
    long numberOfLocations = locations.length;
    long numberOfDistinctLocations = stream(locations).distinct().count();
    return numberOfDistinctLocations == numberOfLocations;
  }

  private boolean distantAtMostOneCell(Location... locations) {
    return stream(locations)
        .allMatch(l1 -> stream(locations).allMatch(l2 -> l1.distanceFrom(l2) <= 2));
  }

  private Stream<Location> emptyLocationsWithLiveNeighboursInAllAndOnlyLocations(
      Location... locations) {
    return emptyLocationsThatAreSharedNeighboursOf(locations)
        .stream()
        .filter(hasNeighbouringLiveCellsInAllAndOnlyThese(locations));
  }

  private List<Location> emptyLocationsThatAreSharedNeighboursOf(Location[] locations) {
    return stream(locations)
        .map(emptyLocationsThatAreNeighboursOf)
        .reduce(intersection)
        .orElseGet(Collections::emptyList);
  }

  private Predicate<Location> isPopulated = this::hasLiveCellAt;
  private Predicate<Location> isNotPopulated = isPopulated.negate();

  private Function<Location, List<Location>> emptyLocationsThatAreNeighboursOf =
      location -> neighboursOf(location).stream().filter(isNotPopulated).collect(toList());

  private BinaryOperator<List<Location>> intersection =
      (xs, ys) -> xs.stream().filter(ys::contains).collect(toList());

  private Predicate<Location> hasNeighbouringLiveCellsInAllAndOnlyThese(Location... locations) {
    return location -> areTheSameLocations(liveNeighboursOf(location), locations);
  }

  private boolean areTheSameLocations(List<Location> locations, Location[] otherLocations) {
    Set<Location> setOne = new HashSet<>(locations);
    Set<Location> setTwo = stream(otherLocations).collect(toSet());
    return setOne.equals(setTwo);
  }

  private List<Location> liveNeighboursOf(Location location) {
    return neighboursOf(location).stream().filter(isPopulated).collect(toList());
  }

  private List<Location> neighboursOf(Location location) {
    return asList(
        location.northWest(),
        location.north(),
        location.northEast(),
        location.west(), /*  location  */
        location.east(),
        location.southWest(),
        location.south(),
        location.southEast());
  }

  // Displaying Worlds
  // ///////////////////////////////////////////////////////////////////////////////////////////////

  private String toString(List<List<Location>> grid) {
    return grid.stream().map(convertRowOfLocationsToString).collect(joining());
  }

  private Function<List<Location>, String> convertRowOfLocationsToString =
      row ->
          row.stream()
              .map(location -> liveCellPresentAt(location) ? "O" : "_")
              .collect(joining(NO_DELIMITER, NO_PREFIX, NEWLINE_SUFFIX));

  private boolean liveCellPresentAt(Location location) {
    return hasLiveCellAt(location);
  }

  private List<List<Location>> buildGridOfLocations() {
    List<Location> northMostFirst = liveCellLocations.stream().sorted().collect(toList());
    Location northMost = northMostFirst.get(0);
    Location southMost = northMostFirst.get(northMostFirst.size() - 1);

    List<Location> westMostFirst =
        liveCellLocations.stream().sorted(byWestMostFirst).collect(toList());
    Location westMost = westMostFirst.get(0);
    Location eastMost = westMostFirst.get(westMostFirst.size() - 1);

    Location topLeft = getTopLeft(northMost, westMost);
    Location topRight = getTopRight(northMost, eastMost);
    Location bottomLeft = getBottomLeft(northMost, southMost);

    List<Location> topRow = topRowWith(topLeft, topRight);

    return gridWith(topRow, topLeft, bottomLeft);
  }

  private static final Comparator<? super Location> byWestMostFirst =
      (aLocation, anotherLocation) ->
          aLocation.isWestOf(anotherLocation) ? -1 : (aLocation.isEastOf(anotherLocation) ? 1 : 0);

  private static final Location getBottomLeft(Location northMost, Location southMost) {
    return Stream.iterate(northMost, Location::south)
        .filter(location -> !southMost.isSouthOf(location))
        .findFirst()
        .get();
  }

  private static final Location getTopRight(Location northMost, Location eastMost) {
    return Stream.iterate(northMost, Location::east)
        .filter(location -> !eastMost.isEastOf(location))
        .findFirst()
        .get();
  }

  private static final Location getTopLeft(Location northMost, Location westMost) {
    return Stream.iterate(northMost, Location::west)
        .filter(location -> !westMost.isWestOf(location))
        .findFirst()
        .get();
  }

  private static final List<List<Location>> gridWith(
      List<Location> topRow, Location topLeft, Location bottomLeft) {
    int rowCount = topLeft.equals(bottomLeft) ? 1 : topLeft.distanceFrom(bottomLeft) + 1;
    return Stream.iterate(topRow, row -> row.stream().map(Location::south).collect(toList()))
        .limit(rowCount)
        .collect(toList());
  }

  private static final List<Location> topRowWith(Location topLeft, Location topRight) {
    int columnCount = topLeft.equals(topRight) ? 1 : topLeft.distanceFrom(topRight) + 1;
    return Stream.iterate(topLeft, Location::east).limit(columnCount).collect(toList());
  }

  // Constants
  // //////////////////////////////////////////////////////////////////////////////////////////////////

  private static final List<Long> NEIGHBOUR_COUNTS_ALLOWING_SURVIVAL = asList(2L, 3L);
  private static final String NEWLINE_SUFFIX = System.getProperty("line.separator");
  private static final String NO_PREFIX = "";
  private static final String NO_DELIMITER = "";
}
Пример #17
0
 public static void main(String[] args) throws Exception {
   System.setIn(new BufferedInputStream(new FileInputStream("E.txt")));
   new E().run();
 }