简体   繁体   English

Java 检查增量/减量模式

[英]Java check for increment/decrement pattern

my question/issue (Both really) is I want to check for a increment pattern in Java via a list.我的问题/问题(两者都是真的)是我想通过列表检查 Java 中的增量模式。

What I mean basically is lets say I have a list of 10 samples worth of floats (Or doubles, or whantnot) with the following values:我的意思基本上是说我有一个包含 10 个浮点数(或双打,或 whintnot)样本的列表,其中包含以下值:

3.2675781, 3.2800293, 3.232666, 3.1662598, 3.0898438, 3.0302734, 3.0253906, 2.9074707, 2.9343262, 2.9179688 3.2675781、3.2800293、3.232666、3.1662598、3.0898438、3.0302734、3.0253906、2.9074707、2.934368127

Notice how it goes from small > bigger > small > smaller> smaller, etc.?请注意它是如何从小>大>小>小>小等开始的?

How can I detect this pattern if possible and what would be the most efficient way to do it.如果可能,我如何检测这种模式以及最有效的方法是什么。

Thanks!谢谢!

You simply need a generic method to do that.你只需要一个通用的方法来做到这一点。

The idea is to take a custom Comparator that lets you compare the type, or your types should be comparable (should implement Comparable ).这个想法是采用自定义Comparator来比较类型,或者您的类型应该是可比较的(应该实现Comparable )。

The following code shows this:以下代码显示了这一点:

public <T extends Comparable<T>> boolean checkPattern(List<T> list) {
    return checkPattern(list, T::compareTo);
}

public <T> boolean checkPattern(List<T> list, Comparator<T> comparator) {
    // assuming null/empty/list with 1 element satisfy the pattern
    if (list == null || list.size() == 0 || list.size() == 1)
        return true;
    if (comparator.compare(list.get(0), list.get(1)) >= 0)
        return false;
    for (int i = 1; i < list.size() - 1; i++) {
        T current = list.get(i);
        T next = list.get(i + 1);
        if (comparator.compare(current, next) <= 0) {
            System.out.println(current + " " + next);
            return false;
        }
    }
    return true;
}

You can call it like:你可以这样称呼它:

System.out.println(new Test().checkPattern(Arrays.asList(3.2675781, 3.2800293, 3.232666, 3.1662598, 3.0898438, 3.0302734, 3.0253906, 2.9074707, 2.9343262, 2.9179688)));

And the output for this will be:这个输出将是:

false

because 2.9074707 < 2.9343262 .因为2.9074707 < 2.9343262

Talking about the efficiency, the asymptotic complexity of the above solution is O(n) where n is the number of elements in the input list.谈到效率,上述解决方案的渐近复杂度是O(n) ,其中n是输入列表中的元素数。 We can't do better than this as we need to visit every element of the list (except the last one) to check if satisfy the condition or not.我们不能做得比这更好,因为我们需要访问列表的每个元素(除了最后一个)以检查是否满足条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM