如何将数组值添加到等于数字,或者如果数组中的值不起作用则失败

时间:2017-11-16 10:27:25

标签: c# arrays

我正在尝试构建一个计算器,它会告诉我堆叠到给定值需要什么“步骤”。仅使用数组中可用的“步骤”。

示例:

decimal[] blocks {.05, .100, .150, .200, .250}
goal = .550m

result = .100, .200, .250

我尝试过使用嵌套的if语句和数组find / last而运气不佳。 如果目标是精确匹配,我可以得到匹配,或者匹配其中两个堆叠。我无法让它工作到最大值(.750)。

这是我到目前为止所做的:

代码:

        string result = "nope";
        decimal goal = 3.264m;
        decimal[] DAStep = new decimal[10];
        decimal temp = Array.Find(GaugeBlockArray, element => element.Equals(goal));
        if (temp != 0m)
        {
            DAStep[0] = Array.Find(GaugeBlockArray, element => element.Equals(temp));
            result = DAStep[0].ToString();
        }
        else
        {
            DAStep[0] = GaugeBlockArray.Last(element => element <= goal); ;

            decimal remaining;
            remaining = goal - DAStep[0];
            while (remaining != 0m)
            {
                DAStep[1] = GaugeBlockArray.Last(element => element <= remaining);
                if (DAStep[1] != remaining)
                {
                    DAStep[2] = GaugeBlockArray.Last(element => element <= (DAStep[1] - .0001m));
                    if (DAStep[2] == 0) { DAStep[1] = DAStep[2]; }
                }
            }
        }

GaugeBlockArray包含从.05到4.0的72个不同元素的数组。而且,我只能使用每个块一次。

编辑: 我想有关阵列内容的更多细节可能有助于找到解决方案。

GaugeBlockArray: 0.05 .100 0.1001 0.1002 0.1003 0.1004 0.1005 0.1006 0.1007 0.1008 0.1009 0.110 0.111 0.112 .113 0.114 0.115 0.116 0.117 0.118 0.119 0.120 0.121 0.122 0.123 0.124 .125 0.126 0.127 0.128 0.129 0.130 0.131 0.132 0.133 0.134 0.135 0.136 .137 0.138 0.139 0.140 .141 0.142 0.143 0.144 0.145 0.146 0.147 0.148 0.149 0.150 0.200 .250 .300 0.350 0.400 .450 0.500 0.550 0.600 .650 0.700 .750 0.800 0.850 .900 0.950 1.000 2.000 3.000 4.000

1 个答案:

答案 0 :(得分:0)

非常感谢@GeorgPatscheider让我指出了正确的方向!

这是我的最终工作结果:

public static void CountSum(decimal[] DNumbers, decimal Dsum)
    {

        foreach (Window window in Application.Current.Windows)
        {
            if (window.GetType() == typeof(MetTracker.GaugeCalc))
            {
                (window as MetTracker.GaugeCalc).CalculateBtn.Content = "working...";
            }
        }

        DNumbers = Array.ConvertAll(DNumbers, element => 10000m * element);
        string TempString = GetSettingsStrings("GBCMaxStep"); // only used to initialize max step value
        Dsum = Dsum * 10000m;
        Int32 Isum = Convert.ToInt32(Dsum);
        Int32[] INumbers = Array.ConvertAll(DNumbers, element => (Int32)element);
        // int result = 0;
            GetmNumberOfSubsets(INumbers, Isum);
        success = false;
        return;
    }

    private static void GetmNumberOfSubsets(Int32[] numbers, Int32 Isum)
    {
        set = numbers;
        sum = Isum;
        FindSubsetSum();
    }
    //-------------------------------------------------------------

    static Int32[] set;
    static Int32[] subSetIndexes;
    static Int32 sum;
    static Int32 numberOfSubsetSums;
    static bool success = false;
    static List<Int32> ResultSet = new List<Int32>();

    static List<string> results = new List<string>();//------------------------------------------------------------

    /*
        Method: FindSubsetSum()
    */
    private static void FindSubsetSum()
    {
        numberOfSubsetSums = 0;
        Int32 numberOfElements = set.Length;
        FindPowerSet(numberOfElements);
    }
    //-------------------------------------------------------------

    /*
        Method: FindPowerSet(int n, int k)
    */
    private static void FindPowerSet(Int32 n)
    {
        // Super set - all sets with size: 0, 1, ..., n - 1
        for (Int32 k = 0; k <= n - 1; k++)
        {
            subSetIndexes = new Int32[k];
            CombinationsNoRepetition(k, 0, n - 1);
            if(subSetIndexes.Length >= GBC_MaxStepSetting) {
                break; }
        }

        if (numberOfSubsetSums == 0)
        {
            MessageBox.Show("No subsets with wanted sum exist.");
        }
    }
    //-------------------------------------------------------------

    /*
        Method: CombinationsNoRepetition(int k, int iBegin, int iEnd);
    */
    private static void CombinationsNoRepetition(Int32 k, Int32 iBegin, Int32 iEnd)
    {
        if (k == 0)
        {
            PrintSubSet();
            return;
        }

        if (success == false)
        {
            for (Int32 i = iBegin; i <= iEnd; i++)
            {
                subSetIndexes[k - 1] = i;
                ++iBegin;
                CombinationsNoRepetition(k - 1, iBegin, iEnd);
                if (success == true)
                    break;
            }

        }
            return;
    }

    private static void PrintSubSet()
    {
        Int32 currentSubsetSum = 0;

        // accumulate sum of current subset
        for (Int32 i = 0; i < subSetIndexes.Length; i++)
        {
            currentSubsetSum += set[subSetIndexes[i]];
            if(currentSubsetSum > sum) { break; }
        }

        if(currentSubsetSum > sum) { return; }

        // if wanted sum: print current subset elements
        if (currentSubsetSum == sum)
        {
            ++numberOfSubsetSums;

            // results.Add("(");
            for (Int32 i = 0; i < subSetIndexes.Length; i++)
            {
               results.Add((set[subSetIndexes[i]]).ToString());
                ResultSet.Add(set[subSetIndexes[i]]);
                if (i < subSetIndexes.Length - 1)
                {
                    // results.Add(" ,");
                }
            }
            // results.Add(")");
            Int32[] ResultSetArr = ResultSet.ToArray();
            decimal[] ResultSetArrD = Array.ConvertAll(ResultSetArr, element => (decimal)element);
            ResultSetArrD = Array.ConvertAll(ResultSetArrD, element => element / 10000m);
            // var message = string.Join(Environment.NewLine, ResultSetArrD);
            // message = string.Format("{0:0.0000}", message);
            int l = ResultSetArrD.Length;
            string[] ResultString = new string[l];
            foreach(int i in ResultSetArrD)
            {ResultString = Array.ConvertAll(ResultSetArrD, element => element.ToString("0.0000"));}
            var message = string.Join(Environment.NewLine, ResultString);
            decimal ResultSum = ResultSetArrD.Sum();
            MessageBox.Show(message + "\n= " + ResultSum.ToString("0.0000"), "Result");
            Array.Clear(ResultSetArrD, 0, ResultSetArrD.Length);
            Array.Clear(ResultSetArr, 0, ResultSetArr.Length);
            ResultSet.Clear();
            message = null;
            success = true;
            foreach (Window window in Application.Current.Windows)
            {
                if (window.GetType() == typeof(MetTracker.GaugeCalc))
                {
                    (window as MetTracker.GaugeCalc).CalculateBtn.Content = "Calculate";
                }
            }
            return;
        }

        if (success == true)
            return;
    }

我添加了一些限制,以减少报告无法找到组合之前的时间。我还将数组转换为double来解决小数点引起我的头痛问题。效果很棒!