Problem with DRY

Asked

Viewed 89 times

6

The problem: compare two arrays and give a dot whenever a number of one array is larger than the other. Ex)

A = [1, 2, 2]

B = [2, 1, 1]

result = [2, 1]

The answer I found:

function a($a, $b){

    $a1 = 0;
    $b1 = 0;

    if ($a[0] > $b[0]) {
        $a1++;
    }
    if ($a[1] > $b[1]) {
        $a1++;
    }
    if ($a[2] > $b[2]) {
        $a1++;
    }

    if ($a[0] < $b[0]) {
        $b1++;
    }
    if ($a[1] < $b[1]) {
        $b1++;
    }
    if ($a[2] < $b[2]) {
        $b1++;
    }

return [$a1, $b1];

}

$a = [5,6,7];
$b = [3,6,10];


var_dump(a($a, $b));

But I feel there is a lot of unnecessary repetition in this code. Some enhancement tip?

  • The tip is to use a same loop, that for the case the for will be the most appropriate

2 answers

8


What you’re doing is walking both arrays at the same time, it is exactly the use case of the for. Using it would not only be repeating less but would also be leaving generic to any size that the arrays have, as long as they are the same size (I did not validate this). The only drawback is that it is slightly slower, but it is derisory and in PHP it makes zero sense to worry about it (in other languages it is almost always also in this case).

function a($a, $b) {
    $a1 = 0;
    $b1 = 0;
    for ($i = 0; $i < count($a); $i++) {
        if ($a[$i] > $b[$i]) $a1++;
        if ($a[$i] < $b[$i]) $b1++;
    }
    return [$a1, $b1];
}
$a = [5, 6, 7];
$b = [3, 6, 10];
var_dump(a($a, $b));

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

You are not violating DRY, you are repeating code, they are different things. I explain this in DRY is to avoid redundancies, right?.

A more basic concern than DRY is to give meaningful names for variables and functions.

  • 1

    @gmsantos yes, I started interpreting it as one thing and then I saw that he wanted something else, so I forgot to change it.

3

I tried a different approach but I think I came to the same result as my colleague:

  $a1 = 0;
  $b1 = 0;


$a = [5,6,7];
$b = [3,6,10];

    $c = count($a);
    for($i = 0; $i < $c;$i++){

        if($a[$i] > $b[$i]){
            $a1++;
        }
        if($a[$i] < $b[$i]){
            $b1++;
        }
    }

echo "a1: " . $a1;
echo "<br>b1: " . $b1;
  • I had some indefinite offset warnings with this code, but it worked anyway. Nice this way to leave the abstract array. I had a similar idea, but I wasn’t sure how to express it in the code. Thank you.

  • 1

    sorry but I was wrong on "for", the correct is this: for($i = 0; $i < $c;$i++) because the array starts from position 0 and was $i <= to $c . that is after comparing items 0, 1 and 2 he was looking for the 3 that does not exist. I already corrected there.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.