Java tutorial
//package com.java2s; /* * Copyright 2012 Jeff Hain * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Main { /** * @param sequencesRanges Sequences ranges, as {min1,max1,min2,max2,etc.}. * @return String representation of the specified sequences ranges. */ public static String toStringSequencesRanges(final long... sequencesRanges) { StringBuilder sb = new StringBuilder(); appendStringSequencesRanges(sb, Integer.MAX_VALUE, sequencesRanges); return sb.toString(); } /** * This treatment does not check that the specified ranges are increasing, * to allow for toString of not (yet) sorted ranges. * * @param sb Buffer where to add representation of the specified ranges. * @param maxNbrOfRanges Max number of ranges to consider. Must be >= 0. * @param sequencesRanges Sequences ranges, as {min1,max1,min2,max2,etc.}. */ public static void appendStringSequencesRanges(StringBuilder sb, int maxNbrOfRanges, final long... sequencesRanges) { if (maxNbrOfRanges < 0) { throw new IllegalArgumentException("max number of ranges [" + maxNbrOfRanges + "] must be >= 0"); } // Does the ranges check. final int nbrOfRanges = computeNbrOfRanges(sequencesRanges); final int nbrOfRangesToConsider = Math.min(nbrOfRanges, maxNbrOfRanges); sb.append("{"); if (nbrOfRanges != 0) { boolean firstDone = false; for (int i = 0; i < nbrOfRangesToConsider; i++) { if (firstDone) { sb.append(","); } final long min = sequencesRanges[2 * i]; final long max = sequencesRanges[2 * i + 1]; sb.append(min); if (max != min) { sb.append(".."); sb.append(max); } firstDone = true; } } if (nbrOfRangesToConsider != nbrOfRanges) { if (nbrOfRangesToConsider != 0) { sb.append(","); } sb.append("..."); } sb.append("}"); } /** * @param sequencesRanges Sequences ranges, as {min1,max1,min2,max2,etc.}. * @return The number of ranges. * @throws IllegalArgumentException if there is not an even number of min/max values specified. */ public static int computeNbrOfRanges(final long... sequencesRanges) { final int nbrOfRanges = sequencesRanges.length / 2; if (2 * nbrOfRanges != sequencesRanges.length) { throw new IllegalArgumentException( "sequencesRanges length [" + sequencesRanges.length + "] must be even"); } return nbrOfRanges; } }