Categories
General

Screen Fitting – php

class Solution {

    
    public function screenFitting($rows, $cols, $sentence)
    {
        # intiialization
        $numberWords = count($sentence);
        $wordIndex = 0;
        $c = 0;
        $r = 0;

        # loop foreach row
        while($r < $rows && $c < $cols) {
            
                $wordLength = strlen($sentence[$wordIndex]); # 5 {hello} ; 5 {world}
                if(($c + $wordLength) < $cols) { # 5 < 7 ;  !! 11 < 7 ; 5 < 7; !! 11 < 7
                    $c += $wordLength;   # 5 ; 7
                    $hashmap[$sentence[$wordIndex]] += 1;
                    $wordIndex++; #1 

                    var_dump($hashmap);
                } else {
                    $r++;  #1 
                    $c = 0;
                    continue;
                }
                $c++; # 6

                if($wordIndex === $numberWords) {
                    $wordIndex = 0;
                }
            }
            
        return min($hashmap);
    }
}

$rows = 2;
$cols = 7;
$sentence = ['hello', 'world'];

$sentence = ["i","had","apple","pie"];
$rows = 4;
$cols = 15;
$solution = new Solution();
$res = $solution->screenFitting($rows, $cols, $sentence);

var_dump($res);

Simplified solution

$s = ["hello", "world"];
$cols = 7;
$rows = 6;

$col = 0;
$row = 0;
$i = 0;

$count = 0;;
while($row < $rows) 
{
    while($col < $cols) 
    {        
        $col = $col + strlen($s[$i]);
        if($col < $cols)  {
            continue;
        }
        $i++;
        if($i == 2) {
            $i = 0;
            $count++;
        }
    }
     $col = 0;
     $row++;
    
}
                            
print $count;

Leave a Reply