无论如何要简化 foreach 循环的老鼠巢吗?

发布于 2024-12-02 07:39:39 字数 6758 浏览 0 评论 0原文

这可行,但比地狱更难看,基本上它是迭代子数组的两个单独部分,看看两个子数组的值中是否有除 1 之外的最大公约数,如果有,则将基值乘以

1.5提前草率的代码。

error_reporting(E_ALL);
ini_set('display_errors', '1');

class CSVParser
{

    public $output = NULL;
    public $digits = NULL;

    public function __construct($file)
    {


        if (!file_exists($file)) {
            throw new Exception("$file does not exist");
        }

        $this->contents = file_get_contents($file);
        $this->output = array();
        $this->digits = array();
        $this->factor = array();
    }

    public function parse($separatorChar1 = ',', $separatorChar2 = ';', $enclosureChar = '"', $newlineChar = "\n")
    {

        $lines = explode($newlineChar, $this->contents);
        foreach ($lines as $line) {
            if (strlen($line) == 0) continue;
            $group = array();
            list($part1, $part2) = explode($separatorChar2, $line);
            $group[] = array_map(array($this, "trim_value"), explode($separatorChar1, $part1), array("$enclosureChar \t"));
            $group[] = array_map(array($this, "trim_value"), explode($separatorChar1, $part2), array("$enclosureChar \t"));
            $this->output[] = $group;
        }
    }

    private function trim_value($value, $chars)
    {
        return preg_replace("#^( |" . $chars . ")+#", '', $value);
    }


    private function gcd($x,$y) 
    {
        do {
            $rest=$x%$y;
        $x=$y;
        $y=$rest;
        } while($rest!==0);
        return $x;
    }

    public function algorithm()
    {
        $alpha = array(
            'c' => str_split('bcdfghjklmnpqrstvwxz'),
            'v' => str_split('aeiouy')
        );
        $i=$k=0;
        foreach ($this->output as $item) {
            $cnt = 0;
            $this->digits[$i] = array();
            foreach ($item as $part) {
                $this->digits[$i][$cnt] = array();
                $new = array();
                foreach ($part as $str) { 
                    $v = count(array_intersect(str_split($str), $alpha['v']));
                    $c = count(array_intersect(str_split($str), $alpha['c']));
                    $t = strlen(str_replace(' ', '', $str));

                    $new = ($cnt == 0) 
                        ? array('v' => $v, 'c' => $c, 't' => $t, 'm' => ($t%2) ? $v * 1.5 : $c) 
                        : array('v' => $v, 'c' => $c, 't' => $t);

                    $this->digits[$i][$cnt][] = $new;
                }
                $cnt++;
            }
            $i++;
        }
        $h=$cuml=0; 
            foreach($this->digits as &$slice) { 
            foreach($slice[0] as &$sliceName){ 

                foreach($slice[1] as $sliceProduct) { 
                foreach($sliceProduct as $pKey=>$pVal) { 

                    foreach($sliceName as $nKey=>$nVal) { 
                        $tmp[$h] = ($this->gcd($pVal,$nVal) != 1) ? ++$cuml:'';
                    } 
                } 
                    $tmp[$h] = $sliceName['m']*$cuml*1.5; 
                    $h++; 
                    $cuml=0; 
                }$h=0; 

            $sliceName['f'] = $tmp; 
            $tmp=''; 
            } 

            } 
        foreach($this->digits as &$u){unset($u[1]);} 
    } 

}

$parser = new CSVParser("file.csv");
$parser->parse();   //print_r($parser->output);
$parser->algorithm();   print_r($parser->digits);

每个请求的 CSV 示例

Jeff Goes, Mika Enrar;Triple Threat, Dogs on  Bikes
Sonny Ray, Lars McGarvitch, Jason McKinley;Kasabian, Lords of Acid, Hard-Fi

输出

Array
(
    [0] => Array
    (
        [0] => Array
            (
                [0] => Array
                    (
                        [v] => 3
                        [c] => 3
                        [t] => 8
                        [m] => 3
                        [f] => Array
                            (
                                [0] => 40.5
                                [1] => 4.5 // Remainder.. So 'Jeff Goes' => 'Dogs on Bikes'
                            )

                    )

                [1] => Array
                    (
                        [v] => 3
                        [c] => 4
                        [t] => 9
                        [m] => 4.5
                        [f] => Array
                            (
                                [0] => 67.5 // High Score! So 'Mika Enrar' => 'Triple Threat'
                                [1] => 13.5
                            )

                    )

            )

    )

    [1] => Array
    (
        [0] => Array
            (
                [0] => Array
                    (
                        [v] => 4
                        [c] => 2
                        [t] => 8
                        [m] => 2
                        [f] => Array
                            (
                                [0] => 24
                                [1] => 12
                                [2] => 24 // Next Highest 'Sonny Ray' => 'Hard-Fi'
                            )

                    )

                [1] => Array
                    (
                        [v] => 3
                        [c] => 8
                        [t] => 14
                        [m] => 8
                        [f] => Array
                            (
                                [0] => 84 // High Score! (This is really a tie, but 'm' has the highest secondary value so...) 
                                [1] => 60 // 'Lars McGarvitch => 'Kasabian'
                                [2] => 84
                            )

                    )

                [2] => Array
                    (
                        [v] => 5
                        [c] => 5
                        [t] => 13
                        [m] => 7.5
                        [f] => Array
                            (
                                [0] => 0
                                [1] => 0 // The only one left 'Jason McKinley' => 'Lords of Acid'
                                [2] => 11.25
                            )

                    )

            )

    )

)

它的作用

到目前为止,该类所做的是将 csv 拆分为一个数组,在 之前拆分内容;然后分成两个子数组。计算两者的辅音和元音,查找每个 CV 或混合字母对的两个小节之间是否存在最大公分母,并创建一个值以将带分配给产品。

真正需要做什么

产生的最高价值应该与创造该高价值的乐队相关联。所以我真正想做的是将一个名字与一个乐队联系起来,具体取决于它最终产生的分数有多高。我已经完成一半了 =(

正如你们所看到的,这段代码从字面上看是一团糟。我真正想要的是根据我生成的数字为乐队分配一个名称。

This works but is uglier than hell, basically it's iterating through two separate portions of a sub array, seeing if there's a greatest common denominator besides 1 in the values of both sub arrays, and if there is, multiplying the base value by 1.5

Sorry for the sloppy code ahead of time.

error_reporting(E_ALL);
ini_set('display_errors', '1');

class CSVParser
{

    public $output = NULL;
    public $digits = NULL;

    public function __construct($file)
    {


        if (!file_exists($file)) {
            throw new Exception("$file does not exist");
        }

        $this->contents = file_get_contents($file);
        $this->output = array();
        $this->digits = array();
        $this->factor = array();
    }

    public function parse($separatorChar1 = ',', $separatorChar2 = ';', $enclosureChar = '"', $newlineChar = "\n")
    {

        $lines = explode($newlineChar, $this->contents);
        foreach ($lines as $line) {
            if (strlen($line) == 0) continue;
            $group = array();
            list($part1, $part2) = explode($separatorChar2, $line);
            $group[] = array_map(array($this, "trim_value"), explode($separatorChar1, $part1), array("$enclosureChar \t"));
            $group[] = array_map(array($this, "trim_value"), explode($separatorChar1, $part2), array("$enclosureChar \t"));
            $this->output[] = $group;
        }
    }

    private function trim_value($value, $chars)
    {
        return preg_replace("#^( |" . $chars . ")+#", '', $value);
    }


    private function gcd($x,$y) 
    {
        do {
            $rest=$x%$y;
        $x=$y;
        $y=$rest;
        } while($rest!==0);
        return $x;
    }

    public function algorithm()
    {
        $alpha = array(
            'c' => str_split('bcdfghjklmnpqrstvwxz'),
            'v' => str_split('aeiouy')
        );
        $i=$k=0;
        foreach ($this->output as $item) {
            $cnt = 0;
            $this->digits[$i] = array();
            foreach ($item as $part) {
                $this->digits[$i][$cnt] = array();
                $new = array();
                foreach ($part as $str) { 
                    $v = count(array_intersect(str_split($str), $alpha['v']));
                    $c = count(array_intersect(str_split($str), $alpha['c']));
                    $t = strlen(str_replace(' ', '', $str));

                    $new = ($cnt == 0) 
                        ? array('v' => $v, 'c' => $c, 't' => $t, 'm' => ($t%2) ? $v * 1.5 : $c) 
                        : array('v' => $v, 'c' => $c, 't' => $t);

                    $this->digits[$i][$cnt][] = $new;
                }
                $cnt++;
            }
            $i++;
        }
        $h=$cuml=0; 
            foreach($this->digits as &$slice) { 
            foreach($slice[0] as &$sliceName){ 

                foreach($slice[1] as $sliceProduct) { 
                foreach($sliceProduct as $pKey=>$pVal) { 

                    foreach($sliceName as $nKey=>$nVal) { 
                        $tmp[$h] = ($this->gcd($pVal,$nVal) != 1) ? ++$cuml:'';
                    } 
                } 
                    $tmp[$h] = $sliceName['m']*$cuml*1.5; 
                    $h++; 
                    $cuml=0; 
                }$h=0; 

            $sliceName['f'] = $tmp; 
            $tmp=''; 
            } 

            } 
        foreach($this->digits as &$u){unset($u[1]);} 
    } 

}

$parser = new CSVParser("file.csv");
$parser->parse();   //print_r($parser->output);
$parser->algorithm();   print_r($parser->digits);

Sample CSV per request

Jeff Goes, Mika Enrar;Triple Threat, Dogs on  Bikes
Sonny Ray, Lars McGarvitch, Jason McKinley;Kasabian, Lords of Acid, Hard-Fi

The Output

Array
(
    [0] => Array
    (
        [0] => Array
            (
                [0] => Array
                    (
                        [v] => 3
                        [c] => 3
                        [t] => 8
                        [m] => 3
                        [f] => Array
                            (
                                [0] => 40.5
                                [1] => 4.5 // Remainder.. So 'Jeff Goes' => 'Dogs on Bikes'
                            )

                    )

                [1] => Array
                    (
                        [v] => 3
                        [c] => 4
                        [t] => 9
                        [m] => 4.5
                        [f] => Array
                            (
                                [0] => 67.5 // High Score! So 'Mika Enrar' => 'Triple Threat'
                                [1] => 13.5
                            )

                    )

            )

    )

    [1] => Array
    (
        [0] => Array
            (
                [0] => Array
                    (
                        [v] => 4
                        [c] => 2
                        [t] => 8
                        [m] => 2
                        [f] => Array
                            (
                                [0] => 24
                                [1] => 12
                                [2] => 24 // Next Highest 'Sonny Ray' => 'Hard-Fi'
                            )

                    )

                [1] => Array
                    (
                        [v] => 3
                        [c] => 8
                        [t] => 14
                        [m] => 8
                        [f] => Array
                            (
                                [0] => 84 // High Score! (This is really a tie, but 'm' has the highest secondary value so...) 
                                [1] => 60 // 'Lars McGarvitch => 'Kasabian'
                                [2] => 84
                            )

                    )

                [2] => Array
                    (
                        [v] => 5
                        [c] => 5
                        [t] => 13
                        [m] => 7.5
                        [f] => Array
                            (
                                [0] => 0
                                [1] => 0 // The only one left 'Jason McKinley' => 'Lords of Acid'
                                [2] => 11.25
                            )

                    )

            )

    )

)

What it does

What this class does so far is split the csv one array, split content prior to ; and after into two sub arrays. Count the consonants and vowels of both, find if there is a greatest common denominator between the two subsections for each C V or mixed letter pair, and create a value to assign a band to a product.

What really needs to do though

The highest value generated should be associated with the band that created that high value. So what I am trying to really do is associate a name to a band depending on how high of a score it ultimately generates. I'm about half way through =(

As you guys can see, this code is a mess, literally. All I really want is to assign a name to a band based on the numbers I'm generating.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

故事与诗 2024-12-09 07:39:39

我必须同意这里其他人的观点...但我想补充一点:

而是搜索如何遍历 $this->digits 更简单,您应该强烈考虑重新考虑 $this->digits中数据的结构。

此外,将所有内容集中到一个数组中并不总是能让感觉。但当它发生时,可以考虑结构,使其直观且易于遍历。

如果没有有关其用途的更多信息,我们无法建议如何重组您的数据/类。首先给我们一个示例 $this->digits 数组的样子。另外,有关您的问题的更多信息会很好(例如如何使用此方法)。

I have to agree with everyone else here... but I'd like to add:

Instead searching for how to traverse $this->digits more simply, you should strongly consider rethinking the structure of the data in $this->digits.

Furthermore, lumping everything into a single array doesn't always make sense. But when it does, the structure can be thought out so that it is intuitive and can be traversed easily.

Without more information about what this is doing, there is no way for us to suggest how to restructure your data / class. A start would be giving us what a sample $this->digits array looks like. Also, some more information about your problem would be good (like how this method is used).

樱花坊 2024-12-09 07:39:39

如果它有效,你为什么要改变它?表现?重构?生意变了?要求变了?干净的代码撒玛利亚人?童子军规则?

当我遇到“意大利面条代码”时,我不会去管它,除非我绝对必须更改它。也就是说,我会编写几个单元测试来验证“意大利面条代码”的输出,这样我就知道我没有破坏任何东西或使事情变得更糟。

If it works why are you changing it? Performance? Refactor? Business changed? Requirements changed? Clean code Samaritan? Boy Scout rule?

When I come across "spaghetti code" I leave it alone unless I absolutely must change it. That said, I would write a couple of unit tests verifying the output of the "spaghetti code" so that I know that I did not break anything or make things worse.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文