优化算法[编译就绪代码]

时间:2014-12-27 10:29:24

标签: java performance algorithm optimization

游戏角度问题(扑克)

该玩家有2个绿色筹码(5分)和1个蓝色(10分)。这总计20分。现在玩家想要购买一个费用为16分的游戏图标。玩家有足够的钱购买物品。因此,玩家支付16分,但他会给予商店正确支付的积分。

现在我写了一个完成所有工作的工作示例。

代码

Program.java

import java.util.Arrays;

public class Program {

    public static void main(String[] args) {
        // Setting up test environment
        Player player = new Player("Borrie", new int[]{0,0,0,0, 230});
        int itemCost = 16626;
        // Pay for item
        System.out.printf("First we check if the player can pay with it's current ChipSet");
        if (!player.canPayWithChipSet(player.getChips(), 5)) {
            if (player.exchangeChips(5)) {
                System.out.printf("\n\nThe players ChipSet:" + Arrays.toString(player.getChips().chips));
                System.out.printf("\nThe players ChipSet has been succesfully exchanged.");
            } else {
                System.out.printf("\n\nThe players ChipSet:" + Arrays.toString(player.getChips().chips));
                System.out.printf("\nThe players ChipSet was not able to be exchanged.\n");
            }
        } else {
            System.out.printf("\n\nThe player can pay exact with it's original ChipSet. No need to exchange.");
        }

    }
}

Player.java

import java.util.ArrayList;
import java.util.Arrays;

public class Player {

    private String name;
    private ChipSet chips;
    private int points = 0;

    public Player(String name, int[] chips) {
        this.name = name;
        this.chips = new ChipSet(chips);
        this.points = this.chips.getSum();
    }

    public boolean exchangeChips(int cost) {
        ChipSet newChipSet = exchangePlayerChipSet(this.chips.getChips(), cost);
        if (newChipSet == null) {
            return false;
        }

        this.chips = newChipSet;
        return true;
    }

    public ChipSet exchangePlayerChipSet(int[] originalChipValues, int cost) {
        ChipSet newChipSet = null;

        // Create possible combinations to compare
        ArrayList<ChipSet> chipSetCombos = createCombinations(this.chips.getChips());

        // Filter the chipset based on if it's able to pay without changing chips
        System.out.printf("\n\n---- Filter which of these combinations are able to be payed with without changing chips ----");
        ArrayList<ChipSet> filteredCombos = filterCombinations(chipSetCombos, cost);

        // Compare the filtered chipsets to determine which one has changed the least
        if (!filteredCombos.isEmpty()) {
            newChipSet = compareChipSets(originalChipValues, filteredCombos);
        }
        return newChipSet;
    }

    private ArrayList<ChipSet> createCombinations(int[] array) {
        ArrayList<ChipSet> combos = new ArrayList<>();
        int[] startCombo = array;
        System.out.printf("Player has " + getTotalPoints(startCombo) + " points in chips.");
        System.out.printf("\nPlayer has these chips (WHITE,RED,GREEN,BLUE,BLACK): " + Arrays.toString(startCombo));

        while (startCombo[4] != 0) {
            startCombo = lowerBlack(startCombo);
            if (getTotalPoints(startCombo) == points) {
                combos.add(new ChipSet(startCombo));
            }
        }
        while (startCombo[3] != 0) {
            startCombo = lowerBlue(startCombo);
            if (getTotalPoints(startCombo) == points) {
                combos.add(new ChipSet(startCombo));
            }
        }
        while (startCombo[2] != 0) {
            startCombo = lowerGreen(startCombo);
            if (getTotalPoints(startCombo) == points) {
                combos.add(new ChipSet(startCombo));
            }
        }
        while (startCombo[1] != 0) {
            startCombo = lowerRed(startCombo);
            if (getTotalPoints(startCombo) == points) {
                combos.add(new ChipSet(startCombo));
            }
        }
        System.out.printf("\n\n---- Creating variations on the players chips ----");
        System.out.printf("\nVariation (all worth " + getTotalPoints(startCombo) + " points):\n");

        int counter = 1;
        for (ChipSet a : combos) {
            System.out.printf("\nCombo " + counter + ": " + Arrays.toString(a.getChips()));
            counter++;
        }
        return combos;
    }

    private ArrayList<ChipSet> filterCombinations(ArrayList<ChipSet> combinations, int cost) {
        ArrayList<ChipSet> filteredChipSet = new ArrayList<>();
        combinations.stream().filter((cs) -> (canPayWithChipSet(cs, cost))).forEach((cs) -> {
            filteredChipSet.add(cs);
        });
        return filteredChipSet;
    }

    // This method has be worked out
    public boolean canPayWithChipSet(ChipSet cs, int cost) {
        ChipSet csOrig = new ChipSet(cs.chips);
        ChipSet csCopy = new ChipSet(cs.chips);
        int counterWhite = 0, counterRed = 0, counterGreen = 0, counterBlue = 0, counterBlack = 0;

        while (20 <= cost && cost > 0 && csOrig.getChips()[4] != 0) {
            csOrig.getChips()[4] -= 1;
            cost -= 20;
            counterBlack++;
        }
        while (10 <= cost && cost > 0 && csOrig.getChips()[3] != 0) {
            csOrig.getChips()[3] -= 1;
            cost -= 10;
            counterBlue++;
        }
        while (5 <= cost && cost > 0 && csOrig.getChips()[2] != 0) {
            csOrig.getChips()[2] -= 1;
            cost -= 5;
            counterGreen++;
        }
        while (2 <= cost && cost > 0 && csOrig.getChips()[1] != 0) {
            csOrig.getChips()[1] -= 1;
            cost -= 2;
            counterRed++;
        }
        while (1 <= cost && cost > 0 && csOrig.getChips()[0] != 0) {
            csOrig.getChips()[0] -= 1;
            cost -= 1;
            counterWhite++;
        }

        if (cost == 0){
            System.out.printf("\nCombo: %s can pay exact. With %d white, %d red, %d green, %d blue an %d black chips", Arrays.toString(csCopy.chips),counterWhite,counterRed,counterGreen,counterBlue,counterBlack);
            return true;
        } else {
            System.out.printf("\nCombo: %s cannot pay exact.\n\n\n", Arrays.toString(csCopy.chips));
            return false;
        }    
    }

    private ChipSet compareChipSets(int[] originalChipValues, ArrayList<ChipSet> chipSetCombos) {
        ChipSet newChipSet;
        int[] chipSetWaardes = originalChipValues; // originele chipset aantal van kleur
        int[] chipSetCombosDifferenceValues = new int[chipSetCombos.size()];
        int counter = 1;

        System.out.printf("\n\n---- Calculate differences between players stack and it's variations ----");
        for (ChipSet cs : chipSetCombos) {
            int amountWhite = cs.getChips()[0];
            int amountRed = cs.getChips()[1];
            int amountGreen = cs.getChips()[2];
            int amountBlue = cs.getChips()[3];
            int amountBlack = cs.getChips()[4];
            int differenceWhite = Math.abs(chipSetWaardes[0] - amountWhite);
            int differenceRed = Math.abs(chipSetWaardes[1] - amountRed);
            int differenceGreen = Math.abs(chipSetWaardes[2] - amountGreen);
            int differenceBlue = Math.abs(chipSetWaardes[3] - amountBlue);
            int differenceBlack = Math.abs(chipSetWaardes[4] - amountBlack);
            int totalDifference = differenceWhite + differenceRed + differenceGreen + differenceBlue + differenceBlack;
            chipSetCombosDifferenceValues[counter - 1] = totalDifference;
            System.out.printf("\nCombo " + counter + ": " + Arrays.toString(cs.getChips()) + " = " + totalDifference);
            counter++;
        }
        newChipSet = chipSetCombos.get(smallestValueOfArrayIndex(chipSetCombosDifferenceValues));
        System.out.printf("\n\nThe least different ChipSet is: " + Arrays.toString(newChipSet.getChips()) + " ");

        return newChipSet;
    }

    private int smallestValueOfArrayIndex(int[] array) {
        int currentValue = array[0];
        int smallestIndex = 0;
        for (int j = 1; j < array.length; j++) {
            if (array[j] < currentValue) {
                currentValue = array[j];
                smallestIndex = j;
            }
        }
        return smallestIndex;
    }

    private int[] lowerBlack(int[] array) {
        return new int[]{array[0], array[1], array[2], array[3] + 2, array[4] - 1};
    }

    private int[] lowerBlue(int[] array) {
        return new int[]{array[0], array[1], array[2] + 2, array[3] - 1, array[4]};
    }

    private int[] lowerGreen(int[] array) {
        return new int[]{array[0] + 1, array[1] + 2, array[2] - 1, array[3], array[4]};
    }

    private int[] lowerRed(int[] array) {
        return new int[]{array[0] + 2, array[1] - 1, array[2], array[3], array[4]};
    }

    private int getTotalPoints(int[] array) {
        return ((array[0] * 1) + (array[1] * 2) + (array[2] * 5) + (array[3] * 10) + (array[4] * 20));
    }

    public String getName() {
        return this.name;
    }

    public int getPoints() {
        return this.points;
    }

    public ChipSet getChips() {
        return chips;
    }

}

ChipSet.java

public class ChipSet {

    public static final int WHITE_VALUE = 1;
    public static final int RED_VALUE = 2;
    public static final int GREEN_VALUE = 5;
    public static final int BLUE_VALUE = 10;
    public static final int BLACK_VALUE = 20;

    public static final int[] VALUES = new int[]{WHITE_VALUE, RED_VALUE, GREEN_VALUE, BLUE_VALUE, BLACK_VALUE};

    protected int[] chips;

    public ChipSet(int[] chips) {
        if (chips == null || chips.length != 5) {
            throw new IllegalArgumentException("ChipSets should contain exactly 5 integers!");
        }

        // store a copy of passed array
        this.chips = new int[5];
        for (int i = 0; i < this.chips.length; i++) {
            this.chips[i] = chips[i];
        }
    }

    public int getSum() {
        return chips[0] * WHITE_VALUE
                + chips[1] * RED_VALUE
                + chips[2] * GREEN_VALUE
                + chips[3] * BLUE_VALUE
                + chips[4] * BLACK_VALUE;
    }

    public int[] getChips() {
        return this.chips;
    }
}

一些解释:

  • 创建组合
  

我们创造了一些交易芯片的子方法,因为它的芯片更低。所以   例如black = 2 blues。然后我们按顺序创建5个循环。该   第一个检查是否还有黑色芯片,如果是,则减少1个黑色   添加2个蓝调。如果总和,请将此新组合保存在列表中   新ChipSet中的芯片等于原始ChipSets值。环   继续,直到没有黑人为止。然后检查是否存在   是蓝色并重复相同的过程,直到没有红色   了。现在我们列出了X值的所有可能变化   芯片。

  • 过滤器组合
  

您可以根据此过滤ChipSets   如果你可以与他们支付X点而不需要交换。我们遍布所有   前一部分中创建的ChipSets的可能组合。如果你   可以使用ChipSet进行支付而无需将其添加到filteredList中   ChipSets。结果是只有有效ChipSets的文件列表。

  • 计算差异
  

对于每个ChipSet,我们计算a中所有颜色的芯片数量   ChipSet并用它减去原始芯片组的芯片数量。   你取这个的绝对值,并将所有这些的总和   原始和组合颜色的差异。现在我们有一个   代表与原始差异的数字。现在我们所有人   要做的就是比较所有ChipSets的差异号码。唯一的那个   我们用来分配给玩家的差异最小。

所以它基本上做的是:它首先检查当前的ChipSet是否可用于支付并返回一个布尔值,就像你问的那样。如果它不能做任何事情,否则它会通过3个子算法并定义最好的ChipSet(一个能用于支付和最少的一个)并改变玩家ChipSet吧

那么现在我的问题是什么,我将如何开始优化呢?我问这个是因为当有更大的输入时,算法很容易使用几秒钟。

2 个答案:

答案 0 :(得分:1)

对应用程序进行几次配置,以确定哪些方法的准确性最高。例如:

enter image description here

尝试优化那些您知道瓶颈和重新配置的方法,直到出现瓶颈为止。

答案 1 :(得分:0)

让我告诉你如何找到问题。这是做什么的:

让它运行并点击“暂停”。显示调用堆栈。单击每个级别,它将显示一行代码,其中一些方法/函数A调用某些B,并且原因从上下文中显而易见。将所有这些原因放在一起,你完全理解为什么要花时间。现在问自己“有没有办法避免这样做,至少在某些时候?”现在,不要立即采取行动。再多停顿几次并以同样的方式研究每一个。

现在,如果你看到这样的事情,你可以避免这样做,而且你看到它不仅仅是一个样本,那么你应该修复它,你将看到一个实质性的加速,保证。现在来了一个好消息:如果你再次这样做,你会发现你已经暴露了其他东西,这也可以给你一个加速。这种情况一直持续到它停止,然后你的代码几乎达到最佳状态。关于你发布的图片,我已多次解释why that does not work

如果你这样做,你可以找到任何可以找到的探索者,以及他们不能找到的东西。 原因很简单 - 归结为描述事物。

  • 什么是功能的包含时间百分比?它是包含该函数的调用堆栈样本的一部分。

  • 什么是功能的自我时间百分比?它是在末尾包含该函数的调用堆栈样本的一部分

  • 一行代码的包含时间百分比是什么(与函数相对)?它是包含该行代码的调用堆栈样本的一部分。

  • 如果查看调用图,函数A和B之间图中链接的时间百分比是多少?它是调用堆栈样本的一小部分,其中A直接调用B。

  • 什么是CPU时间?如果您忽略在I / O,睡眠或任何其他此类阻塞期间采集的任何样本,您将得到的时间?

因此,如果您自己检查堆栈样本,您可以找到探查器可以找到的任何内容,只需查看即可。 您还可以找到探查器无法找到的内容,例如:

  • 看到花费很长一段时间用于为短时间后的对象分配内存只是被删除。

  • 看到一个函数被多次使用相同的参数调用,只是因为程序员懒得声明一个变量来记住先前的结果。

  • 在一个20级的堆栈示例中看到一个看似无害的函数在10级被调用,程序员从未想过会在20级进行文件I / O,因为它的作者有些模糊不清的原因不能排除,但你知道没有必要。

  • 看到有十几种不同的功能都在做同样的事情,但它们是不同的功能,因为它们的所有者类已被模板化。

  • 看到有一个频繁模式的函数P调用某个东西,然后调用R,其中P从许多不同的地方调用,而R调用到很多不同的地方。

您可以轻松地查看这些内容中的任何内容,只需自己检查样本即可。 现在,看到它们所需的平均样本数量取决于它们的大小。 如果某些东西需要50%的时间,那么看到它两次所需的平均样本数量是2 / 0.5 = 4个样本,所以如果你需要10个样本,你肯定会看到它。

假设有另外一件事需要25%的时间。 现在在解决了第一个问题并将时间缩短了一半之后,第二个问题占了50%,而不是25%,所以它也很容易找到。

这就是修复一个加速版暴露下一个加速的方法。 但是一旦你没有找到真正存在的加速,整个过程就会停止,因为你停止暴露那些最初很小的但当更大的那些被删除时变得非常重要。

Profilers可以为您提供精确的测量结果,但它们的测量结果是什么? (实际上,这种精度是假的。所有这些测量都有标准错误,你没有显示。) 它们的测量值是多少?实际上只是非常简单的东西。 他们无法识别您能识别的东西,因为您知道代码。 我有学术剖析粉丝坚持告诉我,你可以找到任何问题,你可以找到一个探查器,但这不是一个定理。 理论上或实际上都没有理由。 有很多问题可以从剖析器中逃脱。 这是一个“看不见 - 忘记”的案例。

“哎呀,我在我的代码上运行了探查器,但我看不到任何瓶颈,所以我猜没有任何瓶颈。”

如果你对表现很认真,你必须做得更好。