Comment detail

小町算 (Nested Flatten)
式をすべて生成して演算する方法。
が、メモリエラーが発生(memory_limit = 32Mの設定)したため、
とりあえず8を追加するときに、9を加減する場合のみ前計算して不要なものを排除。
101件取得(33.56秒)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
$operators = array( '+', '-', '*', '/', '' );

for ( $i = 1; $i <= 9; $i ++ ) {
    $h = 1;
    if ( $i == 1 ) {
        foreach ( $operators as $row ) {
            $temp[$h] = $i . $row;
            $h++;
        }
    } elseif ( $i == 9 ) {
        foreach ( $temp as $row ) {
            $expression = $row . $i;
            eval("\$ans = $expression;");
            if ( $ans == 100 ) {
                $expressions[] = $expression;
            }
            $h++;
        }
    } else {
        if ( $i == 8 ) {
            foreach ( $temp as $row ) {
                foreach ( $operators as $key => $val ) {
                    $expression_temp = $row . $i;
                    eval("\$ans = $expression_temp;");
                    if ( $key === 0 ) {
                        if ( $ans == 91 ) {
                            $temp[$h] = $row . $i . $val;
                            $h++;
                        }
                    } elseif ( $key == 1 ) {
                        if ( $ans == 109 ) {
                            $temp[$h] = $row . $i . $val;
                            $h++;
                        }
                    } else {
                        $temp[$h] = $row . $i . $val;
                        $h++;
                    }
                }
            }
        } else {
            foreach ( $temp as $row ) {
                foreach ( $operators as $row2 ) {
                    $temp[$h] = $row . $i . $row2;
                    $h++;
                }
            }
        }
    }
}
print_r($expressions);

Index

Feed

Other

Link

Pathtraq

loading...