public void writeTasks(OutputStream output) { try { output.write("[\n".getBytes()); boolean needComma = false; File[] files = tasksDirectory.listFiles((FileFilter) FileFilterUtils.directoryFileFilter()); List<Integer> numbers = new ArrayList<>(); for (File directory : files) { try { numbers.add(Integer.valueOf(directory.getName())); } catch (Throwable ignored) { } } numbers.sort(Comparator.<Integer>reverseOrder()); numbers = numbers.subList(0, Math.min(100, numbers.size())); for (int taskId : numbers) { File infoFile = new File(new File(tasksDirectory, String.valueOf(taskId)), "info.json"); if (!infoFile.exists()) { continue; } if (needComma) { output.write(",\n".getBytes()); } else { needComma = true; } try (FileInputStream fis = new FileInputStream(infoFile)) { IOUtils.copy(fis, output); } } output.write("]\n".getBytes()); } catch (IOException e) { throw Throwables.propagate(e); } }
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] temp = in.readLine().split(" "); int n = Integer.parseInt(temp[0]); int s = Integer.parseInt(temp[1]); HashMap<Integer, Integer> buy = new HashMap<>(); HashMap<Integer, Integer> sell = new HashMap<>(); for (int i = 1; i <= n; i++) { temp = in.readLine().split(" "); int p = Integer.parseInt(temp[1]); int q = Integer.parseInt(temp[2]); if (temp[0].charAt(0) == 'B') { if (buy.containsKey(p)) buy.put(p, buy.get(p) + q); else buy.put(p, q); } else { if (sell.containsKey(p)) sell.put(p, sell.get(p) + q); else sell.put(p, q); } } ArrayList<Integer> buyArr = new ArrayList<>(); ArrayList<Integer> sellArr = new ArrayList<>(); for (Integer i : buy.keySet()) buyArr.add(i); for (Integer i : sell.keySet()) sellArr.add(i); Collections.sort(buyArr, Comparator.reverseOrder()); Collections.sort(sellArr); for (int i = Math.min(s, sellArr.size()) - 1; i >= 0; i--) System.out.println("S " + sellArr.get(i) + " " + sell.get(sellArr.get(i))); for (int i = 0; i < s && i < buyArr.size(); i++) System.out.println("B " + buyArr.get(i) + " " + buy.get(buyArr.get(i))); }
public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] numbers = sc.nextLine().split(" "); String sort = sc.nextLine(); if (sort.equals("Ascending")) { List<Integer> output = Arrays.stream(numbers).map(Integer::parseInt).sorted().collect(Collectors.toList()); for (Object items : output) { System.out.print(items + " "); } } else if (sort.equals("Descending")) { List<Integer> output = Arrays.stream(numbers) .map(Integer::parseInt) .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); for (Object items : output) { System.out.print(items + " "); } } }
@Override public void sort(Comparable[] items, int lo, int hi) { Integer[] gaps = IntStream.generate( new IntSupplier() { private int current = lo; @Override public int getAsInt() { return current++ * 3 + 1; } }) .limit(GAPS_SIZE_LIMIT) .boxed() .sorted(Comparator.reverseOrder()) .toArray(Integer[]::new); for (Integer gap : gaps) { for (int j = lo; j < hi; j += gap) { for (int k = j; k > 0; k -= gap) { if (items[k - gap].compareTo(items[k]) > 0) { swap(items, k, k - gap); } else { break; } } } } }
@Override @Test public void toSortedBag() { ImmutableBag<String> immutableBag = this.newBag(); MutableSortedBag<String> sortedBag = immutableBag.toSortedBag(); Verify.assertSortedBagsEqual(TreeBag.newBag(), sortedBag); MutableSortedBag<String> reverse = immutableBag.toSortedBag(Comparator.<String>reverseOrder()); Verify.assertSortedBagsEqual(TreeBag.newBag(Comparator.<String>reverseOrder()), reverse); ImmutableBag<String> immutableBag1 = this.newBag(); MutableSortedBag<String> sortedBag1 = immutableBag1.toSortedBag(Comparator.reverseOrder()); Verify.assertSortedBagsEqual(TreeBag.newBag(), sortedBag1.toSortedBag()); ImmutableBag<String> immutableBag2 = this.newBag(); MutableSortedBag<String> sortedBag2 = immutableBag2.toSortedBag(Comparator.reverseOrder()); Verify.assertSortedBagsEqual(TreeBag.newBag(Comparator.<String>reverseOrder()), sortedBag2); }
public Map<String, Integer> top(int q) { Collector<Entry<String, Integer>, ?, LinkedHashMap<String, Integer>> collector = toMap( Entry::getKey, Entry::getValue, (x, y) -> { throw new AssertionError(); }, LinkedHashMap::new); LinkedHashMap<String, Integer> collected = wordMap .entrySet() .stream() .sorted(comparingByValue(Comparator.reverseOrder())) .collect(collector); return collected.entrySet().stream().limit(q).collect(collector); }
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); for (int i = 999; i >= 100; i--) { for (int j = i; j >= 100; j--) { if (i * j >= 101101 && isPalindrome(i * j)) palindromes.add(i * j); } } Collections.sort(palindromes, Comparator.reverseOrder()); for (int aa = 1; aa <= t; aa++) { int n = Integer.parseInt(in.readLine()); for (int i : palindromes) { if (i < n) { System.out.println(i); break; } } } }
/** * ShellSort runs multiple InsertionSorts with a custom gap between elements With a a final pass * with a gap size of 1 This takes advantage of InsertionSorts adaptive nature on partial sorted * data * * @param gaps must be descendingly sorted and contain the element 1 */ public static <T> void sort(T[] data, Integer[] gaps, Comparator<? super T> cmp) { assert data != null && cmp != null && gaps != null && gaps.length > 0; if (!java.util.Arrays.asList(gaps).contains(1)) { throw new IllegalArgumentException( "The gap-sequence needs to contain, 1 as the last element"); } // Make sure that the gaps are decreasingly sorted java.util.Arrays.sort(gaps, Comparator.<Integer>reverseOrder()); for (int gap : gaps) { // Insertion Sort, with a specified gap between elements // TODO: consider refactoring this into InsertionSort for (int i = gap; i < data.length; i++) { // Swap if left side is bigger, exits the loop if it's not for (int j = i; j >= gap && (cmp.compare(data[j - gap], data[j]) > 0); j -= gap) { Arrays.swap(data, j - gap, j); } } } }
public static Map<String, Integer> freq(String safeLyrics) { Map<String, Integer> freq = new HashMap<>(); Matcher matcher = tokenizer.matcher(safeLyrics); // Create a map of the frequency while (matcher.find()) { String word = matcher.group().toLowerCase(); freq.put(word, freq.getOrDefault(word, 0) + 1); } // Sort the map by descending value Map<String, Integer> sortedMap = freq.entrySet() .stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) .collect( Collectors.toMap( Entry::getKey, Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); return sortedMap; }
@Test public void testMaxAll() { List<String> input = Arrays.asList("a", "bb", "c", "", "cc", "eee", "bb", "ddd"); checkCollector( "maxAll", Arrays.asList("eee", "ddd"), input::stream, MoreCollectors.maxAll(Comparator.comparingInt(String::length))); Collector<String, ?, String> maxAllJoin = MoreCollectors.maxAll(Comparator.comparingInt(String::length), Collectors.joining(",")); checkCollector("maxAllJoin", "eee,ddd", input::stream, maxAllJoin); checkCollector( "minAll", 1L, input::stream, MoreCollectors.minAll(Comparator.comparingInt(String::length), Collectors.counting())); checkCollector( "minAllEmpty", Arrays.asList(""), input::stream, MoreCollectors.minAll(Comparator.comparingInt(String::length))); checkCollectorEmpty( "maxAll", Collections.emptyList(), MoreCollectors.maxAll(Comparator.comparingInt(String::length))); checkCollectorEmpty("maxAllJoin", "", maxAllJoin); List<Integer> ints = IntStreamEx.of(new Random(1), 10000, 1, 1000).boxed().toList(); List<Integer> expectedMax = getMaxAll(ints, Comparator.naturalOrder()); List<Integer> expectedMin = getMaxAll(ints, Comparator.reverseOrder()); Collector<Integer, ?, SimpleEntry<Integer, Long>> downstream = MoreCollectors.pairing( MoreCollectors.first(), Collectors.counting(), (opt, cnt) -> new AbstractMap.SimpleEntry<>(opt.get(), cnt)); checkCollector("maxAll", expectedMax, ints::stream, MoreCollectors.maxAll(Integer::compare)); checkCollector("minAll", expectedMin, ints::stream, MoreCollectors.minAll()); checkCollector( "entry", new SimpleEntry<>(expectedMax.get(0), (long) expectedMax.size()), ints::stream, MoreCollectors.maxAll(downstream)); checkCollector( "entry", new SimpleEntry<>(expectedMin.get(0), (long) expectedMin.size()), ints::stream, MoreCollectors.minAll(downstream)); Integer a = new Integer(1), b = new Integer(1), c = new Integer(1000), d = new Integer(1000); ints = IntStreamEx.range(10, 100).boxed().append(a, c).prepend(b, d).toList(); for (StreamExSupplier<Integer> supplier : streamEx(ints::stream)) { List<Integer> list = supplier.get().collect(MoreCollectors.maxAll()); assertEquals(2, list.size()); assertSame(d, list.get(0)); assertSame(c, list.get(1)); list = supplier.get().collect(MoreCollectors.minAll()); assertEquals(2, list.size()); assertSame(b, list.get(0)); assertSame(a, list.get(1)); } }
/* Result: 12,690 ±(99.9%) 0,148 s/op [Average] Statistics: (min, avg, max) = (12,281, 12,690, 12,784), stdev = 0,138 Confidence interval (99.9%): [12,543, 12,838] Samples, N = 15 mean = 12,690 ±(99.9%) 0,148 s/op min = 12,281 s/op p( 0,0000) = 12,281 s/op p(50,0000) = 12,717 s/op p(90,0000) = 12,784 s/op p(95,0000) = 12,784 s/op p(99,0000) = 12,784 s/op p(99,9000) = 12,784 s/op p(99,9900) = 12,784 s/op p(99,9990) = 12,784 s/op p(99,9999) = 12,784 s/op max = 12,784 s/op # Run complete. Total time: 00:06:26 Benchmark Mode Cnt Score Error Units ShakespearePlaysScrabbleWithRxJava.measureThroughput sample 15 12,690 ± 0,148 s/op Benchmark Mode Cnt Score Error Units ShakespearePlaysScrabbleWithRxJava.measureThroughput avgt 15 250074,776 ± 7736,734 us/op ShakespearePlaysScrabbleWithStreams.measureThroughput avgt 15 29389,903 ± 1115,836 us/op */ @Benchmark @BenchmarkMode(Mode.SampleTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @Warmup(iterations = 50) @Measurement(iterations = 50) @Fork(1) public List<Entry<Integer, List<String>>> measureThroughput() throws InterruptedException { // to compute the score of a given word Function<Integer, PublisherBase<Integer>> scoreOfALetter = letter -> PublisherBase.just(letterScores[letter - 'a']); // score of the same letters in a word Function<Entry<Integer, LongWrapper>, PublisherBase<Integer>> letterScore = entry -> PublisherBase.just( letterScores[entry.getKey() - 'a'] * Integer.min( (int) entry.getValue().get(), (int) scrabbleAvailableLetters[entry.getKey() - 'a'])); Function<String, PublisherBase<Integer>> toIntegerPublisherBase = string -> PublisherBase.fromIterable( IterableSpliterator.of(string.chars().boxed().spliterator())); // Histogram of the letters in a given word Function<String, PublisherBase<HashMap<Integer, LongWrapper>>> histoOfLetters = word -> toIntegerPublisherBase .apply(word) .collect( () -> new HashMap<Integer, LongWrapper>(), (HashMap<Integer, LongWrapper> map, Integer value) -> { LongWrapper newValue = map.get(value); if (newValue == null) { newValue = () -> 0L; } map.put(value, newValue.incAndSet()); }); // number of blanks for a given letter Function<Entry<Integer, LongWrapper>, PublisherBase<Long>> blank = entry -> PublisherBase.just( Long.max( 0L, entry.getValue().get() - scrabbleAvailableLetters[entry.getKey() - 'a'])); // number of blanks for a given word Function<String, PublisherBase<Long>> nBlanks = word -> histoOfLetters .apply(word) .flatMap(map -> PublisherBase.fromIterable(() -> map.entrySet().iterator())) .flatMap(blank) .reduce(Long::sum); // can a word be written with 2 blanks? Function<String, PublisherBase<Boolean>> checkBlanks = word -> nBlanks.apply(word).flatMap(l -> PublisherBase.just(l <= 2L)); // score taking blanks into account letterScore1 Function<String, PublisherBase<Integer>> score2 = word -> histoOfLetters .apply(word) .flatMap(map -> PublisherBase.fromIterable(() -> map.entrySet().iterator())) .flatMap(letterScore) .reduce(Integer::sum); // Placing the word on the board // Building the streams of first and last letters Function<String, PublisherBase<Integer>> first3 = word -> PublisherBase.fromIterable( IterableSpliterator.of(word.chars().boxed().limit(3).spliterator())); Function<String, PublisherBase<Integer>> last3 = word -> PublisherBase.fromIterable( IterableSpliterator.of(word.chars().boxed().skip(3).spliterator())); // Stream to be maxed Function<String, PublisherBase<Integer>> toBeMaxed = word -> PublisherBase.fromArray(first3.apply(word), last3.apply(word)) .flatMap(PublisherBase -> PublisherBase); // Bonus for double letter Function<String, PublisherBase<Integer>> bonusForDoubleLetter = word -> toBeMaxed.apply(word).flatMap(scoreOfALetter).reduce(Integer::max); // score of the word put on the board Function<String, PublisherBase<Integer>> score3 = word -> PublisherBase.fromArray( score2.apply(word), score2.apply(word), bonusForDoubleLetter.apply(word), bonusForDoubleLetter.apply(word), PublisherBase.just(word.length() == 7 ? 50 : 0)) .flatMap(PublisherBase -> PublisherBase) .reduce(Integer::sum); Function< Function<String, PublisherBase<Integer>>, PublisherBase<TreeMap<Integer, List<String>>>> buildHistoOnScore = score -> PublisherBase.fromIterable(() -> shakespeareWords.iterator()) .filter(scrabbleWords::contains) .filter(word -> checkBlanks.apply(word).blockingFirst()) .collect( () -> new TreeMap<Integer, List<String>>(Comparator.reverseOrder()), (TreeMap<Integer, List<String>> map, String word) -> { Integer key = score.apply(word).blockingFirst(); List<String> list = map.get(key); if (list == null) { list = new ArrayList<String>(); map.put(key, list); } list.add(word); }); // best key / value pairs List<Entry<Integer, List<String>>> finalList2 = buildHistoOnScore .apply(score3) .flatMap(map -> PublisherBase.fromIterable(() -> map.entrySet().iterator())) .take(3) .collect( () -> new ArrayList<Entry<Integer, List<String>>>(), (list, entry) -> { list.add(entry); }) .blockingFirst(); // System.out.println(finalList2); return finalList2; }
public Solution295() { smallerElements = new PriorityQueue<>(Comparator.reverseOrder()); largerElements = new PriorityQueue<>(); }