2017-12-13 10 views
0

私は全体から各エンティティ(合計3つ)の%を計算するアルゴリズムを持っています。 しかし、私はまた、超過してはならない各部分の最大%を持っています。 この部分をアルゴリズムに追加するにはどうすればよいですか?それぞれの最大限を知る全体の部分を計算する方法は? (好ましくはphp)

13%の合計のための例(他のもののために予約他の87%がある):

x | calculated % | max % | should get 
x1  2   20   6* 
x2  5   4   4 
x3  6   3   3 

シンプルなこの種のが、何だけ1つがダウンした場合や他の二つの残りの部分を共有する必要がありますその部分に応じ

x | calculated % | max % | should get 
x1  2   10   2.5* 
x2  5   10   6.5* 
x3  6   4   4 

は、ここに1つの可能なアプローチだ助けてくれてありがとうと

+0

あなたは質問を明確にすることはできますか?次のようにテストされた

<?php function adjustEntities($total, array $entities) { $entities_locked = array(); while (true) { $found_any_at_max = false; $total_to_adjust = 0; foreach ($entities as $entity => $values) { if ($values['calculated'] >= $values['max']) { $found_any_at_max = true; $entities_locked[$entity] = $values['max']; $total -= $values['max']; unset($entities[$entity]); } else { $total_to_adjust += $values['calculated']; } } if (!$found_any_at_max || empty($entities)) { foreach ($entities as $entity => $values) { $entities_locked[$entity] = $values['calculated']; } ksort($entities_locked); return $entities_locked; } $ratio = $total/$total_to_adjust; foreach ($entities as $entity => $values) { $values['calculated'] = roundToNearestHalf($values['calculated'] * $ratio); $entities[$entity] = $values; } } } function roundToNearestHalf($value) { return 0.5 * round(2 * $value); } 

2、5、6はあなたが現在取得している値で、必要なものは6,4,3です。最初のグループを計算するコードを投稿できますか? – solarc

+0

はい。 $ concentr_index = $ max_percentage * $ x0 * $ x1 * $ x2 /($ x0 * $ x1 + $ x1 * $ x2 + $ x2 * $ x0); \t $ o0 = $ concentr_index/$ x0; \t $ o1 = $ concentr_index/$ x1; \t $ o2 = $ concentr_index/$ x2; –

答えて

0

を助言する(PHP 5.6でテスト) - すでに最大値以上のエンティティを見つけ、別の配列に移動し、残りのエンティティを比率で再平衡化し、さらに最大値以上であるかどうかを確認することによって動作します。私はまた、最も近い0.5に丸める関数を追加しました。これは、例で行ったように思われますが、返されたエンティティが特定の状況下で合計に正確に加算されない可能性があります。

<?php 

$total = 13; 

$entities1 = array(
    'x1' => array (
     'calculated' => 2, 
     'max' => 20, 
    ), 
    'x2' => array (
     'calculated' => 5, 
     'max' => 4, 
    ), 
    'x3' => array (
     'calculated' => 6, 
     'max' => 3, 
    ), 
); 

$entities2 = array(
    'x1' => array (
     'calculated' => 2, 
     'max' => 10, 
    ), 
    'x2' => array (
     'calculated' => 5, 
     'max' => 10, 
    ), 
    'x3' => array (
     'calculated' => 6, 
     'max' => 4, 
    ), 
); 

var_dump(adjustEntities($total, $entities1)); 
var_dump(adjustEntities($total, $entities2)); 

は、出力を提供します:

array(3) { 
    ["x1"]=> 
    float(6) 
    ["x2"]=> 
    int(4) 
    ["x3"]=> 
    int(3) 
} 
array(3) { 
    ["x1"]=> 
    float(2.5) 
    ["x2"]=> 
    float(6.5) 
    ["x3"]=> 
    int(4) 
} 
+0

ありがとう、今それを挿入し、全体の画像を参照してください! –

+0

もう一度ありがとう、それは素晴らしいと非常に高速な答えでした!私は本当にあなたの助けに感謝します!私は+1をするだけの十分な評判は持っていませんが、+10000にするでしょう! –

関連する問題