L
L
littleguga2015-07-20 11:30:15
PHP
littleguga, 2015-07-20 11:30:15

Which algorithm is the best?

Task: we get a string consisting of several words as input. space separated.
For example: "I love the toaster, every day I answer and ask questions here"
You need to write a function that will cut the input line into 2 lines, depending on the given number of words.

//Обрезает заголовок на основной и под, разделяя по пробелам
function cut_title($thistitle,$count){ //заголовок и количество слов на которые стоит обрезать
  $post_title = explode(" ", $thistitle);
  $post_title_title = "";
  $i = 0;
  while($i < $count){
    $post_title_title .= $post_title[$i]." ";
    $i++;
  }
  $ctitle['title'] = $post_title_title;
  $ctitle['sub'] = str_replace($post_title_title, "", $thistitle);
  return $ctitle; //возвращает массив $ctitle['title'] и $ctitle['sub']
}

The question is, what is the best way to build a loop? As is or:
while($i++ < $count){
    $post_title_title .= $post_title[$i]." ";
  }

Or through for?
Interested in terms of optimality, readability and non-coding.
Thanks in advance for the detailed and detailed answer!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
IceJOKER, 2015-07-20
@littleguga

Without checks (for number of characters, etc.):

$str = "я люблю тостер, каждый день отвечаю и задаю вопросы здесь";
$words = explode(' ', $str);
$num = 2; //кол. слов
$first_line = implode(' ', array_slice($words, 0, $num));
$second_line = implode(' ', array_slice($words, $num));

var_dump($first_line, $second_line);

R
Rishat Kadyrov, 2015-07-20
@laska

1. For these purposes, as you rightly noted, they came up with for. It fits here perfectly, like an example in a textbook.
2. Among while, for and foreach there are no best and worst loops in terms of shitty coding. They are needed for a few different things. And correct coding is the use of each cycle for its intended purpose. Readability from this tode will improve slightly.
3. In terms of performance, foreach is slower, the rest are approximately equal, but this is of purely theoretical interest.

⚡ Kotobotov ⚡, 2015-07-20
@angrySCV

honestly did not understand what you want to evaluate, what optimality.
Algorithms have different metrics (evaluative characteristics)
such as running time, or memory consumption, or code size.
first determine which of these evaluation parameters you want to optimize -> then you can already tell which of the possible options is better.
based on performance, in execution time (which is usually estimated by the number of operations) . then both of these algorithms are absolutely equivalent.
more details here https://ru.wikipedia.org/wiki/Computational_complexity

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question