Skip to content

Instantly share code, notes, and snippets.

@eutkin
Created February 11, 2019 10:08
Show Gist options
  • Save eutkin/3547004d5ba30dbe8cb3734a1e531682 to your computer and use it in GitHub Desktop.
Save eutkin/3547004d5ba30dbe8cb3734a1e531682 to your computer and use it in GitHub Desktop.
package com.company;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
public class Test {
public static void main(String[] args) {
one();
System.out.println(two(5, 2)); // 10
System.out.println(two(5, 3)); // 10
System.out.println(two(5, 5)); // 1
System.out.println(three("Hello World! Hello, my friend! All Friend meet you."));
// [friend, hello, all, world, meet, my, you]
}
public static void one() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0 && i % 7 == 0) {
System.out.println("TwoSeven");
} else if
(i % 2 == 0) {
System.out.println("Two");
} else if (i % 7 == 0) {
System.out.println("Seven");
} else {
System.out.println(i);
}
}
}
public static BigInteger two(int m, int r) {
if (m < r || m < 0 || r < 0) {
throw new RuntimeException();
}
int diff = m - r;
if (diff == 0) return BigInteger.ONE;
/*
m = 5, r = 2. Берем 3 числа, m = 5, r = 2 и diff = m - r = 3. Факториал самого маленького
сокращается. Самое маленькое число + 1 тоже сокращается.
1) вычисляем разницу между m и r, diff = m - r.
2) если diff = 0, возвращаем 1
3) Вычисляем минимальное число (min). Оно сокращается, поэтому факториал для него считать не надо.
4) Вычисляем два факториала. (min - 1)! и (от min - 1 до m)!. Отнимаем 1, так как есть и там и там.
2! * 3 * 4 * 5 3 * 4 * 5 4 * 5
------------------- = ------------- = --------- = 10
2! * 3! 1 * 2 * 3 1 * 2
*/
int min = diff < r ? r : diff;
BigInteger f1 = factorial(min - 1);
BigInteger f3 = factorial(min + 1, m);
return f3.divide(f1);
}
public static List<String> three(String text) {
return Stream.of(text.split("\\s+|,|-|\\.|\\?|!"))
.map(String::toLowerCase)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed())
.map(Map.Entry::getKey)
.filter(s -> !s.isEmpty())
.collect(toList());
}
public static BigInteger factorial(final int start, final int number) {
if (number == 0) return BigInteger.ONE;
BigInteger result = BigInteger.ONE;
for (int i = start; i <= number; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
public static BigInteger factorial(final int number) {
return factorial(1, number);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment