Here you can find the source of summarizeNumbersAsString(int[] numbers)
Parameter | Description |
---|---|
numbers | a parameter |
public static String[] summarizeNumbersAsString(int[] numbers)
//package com.java2s; /*/* w ww. java 2s. c o m*/ * Copyright 2016 Roche NimbleGen Inc. * * 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. */ import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class Main { /** * Return a list of strings were adjacent values are clumped together. So 1,2,3,5,6,7,8,10 would be expressed as 1-3, 5-8, 10 * * @param numbers * @return */ public static String[] summarizeNumbersAsString(int[] numbers) { // filter out duplicates Set<Integer> set = new HashSet<Integer>(); for (int number : numbers) { set.add(number); } List<Integer> sortedNumbers = new ArrayList<Integer>(set); Collections.sort(sortedNumbers); List<String> summarizedStrings = new ArrayList<String>(); Integer currentRunMin = null; Integer lastNumber = null; for (int number : sortedNumbers) { if (currentRunMin == null) { currentRunMin = number; } else if (number > (int) (lastNumber + 1)) { if (currentRunMin.equals(lastNumber)) { summarizedStrings.add(wrapNegativeNumbers(currentRunMin)); } else { summarizedStrings .add(wrapNegativeNumbers(currentRunMin) + "-" + wrapNegativeNumbers(lastNumber)); } currentRunMin = number; } lastNumber = number; } if (currentRunMin == null || currentRunMin.equals(lastNumber)) { summarizedStrings.add(wrapNegativeNumbers(lastNumber)); } else { summarizedStrings.add(wrapNegativeNumbers(currentRunMin) + "-" + wrapNegativeNumbers(lastNumber)); } return summarizedStrings.toArray(new String[0]); } private static String wrapNegativeNumbers(int number) { String valueAsString = "" + number; if (number < 0) { valueAsString = "(" + number + ")"; } return valueAsString; } }