Simulador de coro de animales -- php campo con object-oriented campo con interview-questions camp codereview Relacionados El problema

Animal choir simulator


10
vote

problema

Español

Tengo una prueba de entrevista de desarrolladores de PHP para resolver para una empresa. No conseguí el trabajo, pero me gustaría saber dónde estaba equivocado. ¿Entendí la prueba completamente?

  /**  * Create an Animal Choir simulator  *  * The task constraints are:  *  * There must be 3 different choir member animals  * (i.e. dogs, cats, mice)  *  * Every animal must have a sing method that returns a string representation of a voice  * (i.e. 'bark', 'meow', 'squeak')  *  * Every animal must have a loudness property which can have 3 settings,  * depending on which the sing method result will be rendered as  * lowercase, first letter uppercase and uppercase.  *  * Singer groups are groups of animals with the same loudness property value.  * Singer group song is represented with a CSV of the group singer sing result in random order.  *  * The choir simulator must have implement the following methods:  *    crescendo - the choir start singing from the least loud singer group, and then are being joined   *                by more and more loud singer groups until they are singing all together.              *                The joining is represented with a new line.  *                Example:  *                  meow, squeak, bark  *                  Meow, bark, squeak, Bark, meow  *                  bark, Meow, MEOW, squeak, BARK, meow, Bark  *  *    arpeggio  - the choir singer groups of the same loudness start singing one by one from  *                the least loud to the loudest  *                Example:  *                  meow, squeak, bark  *                  Meow, Bark  *                  MEOW, BARK  *  */  //TODO: Describe the class hierarchy   //Choir class class Choir{          public $line_ending = '';     public $line_separator = '';     public $voices = '';      public function crescendo(){         $crescendo_song = '';          $animals = new Animal();                 //We define which animal voices will be included in song         $animals->voices = $this->voices;          //First we start with the silent         $animals->loudness = 'silent';         //Call the function              $silent = $animals->sing();         //echo the result         $crescendo_song .= $this->stringForm($silent);          //Then we continue with the normal, but also merge with silent         $animals->loudness = 'normal';               $normal = array_merge($animals->sing(),$silent);         $crescendo_song .= $this->stringForm($normal);          //And in the end we merge loud with silent and normal         $animals->loudness = 'loud';             $loud = array_merge($animals->sing(),$silent,$normal);         $crescendo_song .= $this->stringForm($loud);          return $crescendo_song;     }       public function arpeggio(){         $arpeggio_song = '';          $animals = new Animal();                 //We define which animal voices will be included in song         $animals->voices = $this->voices;          //First we start with the silent         $animals->loudness = 'silent';           $arpeggio_song .= $this->stringForm($animals->sing());          //Then normal         $animals->loudness = 'normal';               $arpeggio_song .= $this->stringForm($animals->sing());          //And then the loud         $animals->loudness = 'loud';         $arpeggio_song .= $this->stringForm($animals->sing());          return $arpeggio_song;      }       private function stringForm($array){         //Randomize the array         shuffle($array);         //Predefine a song and a separator         $song = '';         $comma = '';         //Form song string         foreach ($array as $slog) {             $song .= $comma.$slog;               $comma = $this->line_separator.' ';                          };         return $song.$this->line_ending;     }   }  //Animal class class Animal{     public $loudness = '';      public function sing(){         $song = array();         foreach ($this->voices as $voices) {             switch ($this->loudness) {                 case 'silent':                     array_push($song,strtolower($voices));                 break;                           case 'normal':                     array_push($song,ucfirst($voices));                 break;                 case 'loud':                     array_push($song,strtoupper($voices));                 break;                 default:                     array_push($song,$voices);                 break;             }         }            return $song;     }  }   $choir = new Choir(); $choir->line_ending = PHP_EOL; //$choir->line_ending = '<br>'; //For cleared viewing in browser use <br> tag //Define the line separator for CSV $choir->line_separator = ','; //Define the voices of animals $choir->voices = array('bark','meow','squeak'); //Call and echo the functions echo $choir->crescendo(); echo $choir->arpeggio();   
Original en ingles

I got a PHP developer interview test to solve for a company. I didn't get the job but I would like to know where I was wrong. Did I understand the test completely?

/**  * Create an Animal Choir simulator  *  * The task constraints are:  *  * There must be 3 different choir member animals  * (i.e. dogs, cats, mice)  *  * Every animal must have a sing method that returns a string representation of a voice  * (i.e. 'bark', 'meow', 'squeak')  *  * Every animal must have a loudness property which can have 3 settings,  * depending on which the sing method result will be rendered as  * lowercase, first letter uppercase and uppercase.  *  * Singer groups are groups of animals with the same loudness property value.  * Singer group song is represented with a CSV of the group singer sing result in random order.  *  * The choir simulator must have implement the following methods:  *    crescendo - the choir start singing from the least loud singer group, and then are being joined   *                by more and more loud singer groups until they are singing all together.              *                The joining is represented with a new line.  *                Example:  *                  meow, squeak, bark  *                  Meow, bark, squeak, Bark, meow  *                  bark, Meow, MEOW, squeak, BARK, meow, Bark  *  *    arpeggio  - the choir singer groups of the same loudness start singing one by one from  *                the least loud to the loudest  *                Example:  *                  meow, squeak, bark  *                  Meow, Bark  *                  MEOW, BARK  *  */  //TODO: Describe the class hierarchy   //Choir class class Choir{          public $line_ending = '';     public $line_separator = '';     public $voices = '';      public function crescendo(){         $crescendo_song = '';          $animals = new Animal();                 //We define which animal voices will be included in song         $animals->voices = $this->voices;          //First we start with the silent         $animals->loudness = 'silent';         //Call the function              $silent = $animals->sing();         //echo the result         $crescendo_song .= $this->stringForm($silent);          //Then we continue with the normal, but also merge with silent         $animals->loudness = 'normal';               $normal = array_merge($animals->sing(),$silent);         $crescendo_song .= $this->stringForm($normal);          //And in the end we merge loud with silent and normal         $animals->loudness = 'loud';             $loud = array_merge($animals->sing(),$silent,$normal);         $crescendo_song .= $this->stringForm($loud);          return $crescendo_song;     }       public function arpeggio(){         $arpeggio_song = '';          $animals = new Animal();                 //We define which animal voices will be included in song         $animals->voices = $this->voices;          //First we start with the silent         $animals->loudness = 'silent';           $arpeggio_song .= $this->stringForm($animals->sing());          //Then normal         $animals->loudness = 'normal';               $arpeggio_song .= $this->stringForm($animals->sing());          //And then the loud         $animals->loudness = 'loud';         $arpeggio_song .= $this->stringForm($animals->sing());          return $arpeggio_song;      }       private function stringForm($array){         //Randomize the array         shuffle($array);         //Predefine a song and a separator         $song = '';         $comma = '';         //Form song string         foreach ($array as $slog) {             $song .= $comma.$slog;               $comma = $this->line_separator.' ';                          };         return $song.$this->line_ending;     }   }  //Animal class class Animal{     public $loudness = '';      public function sing(){         $song = array();         foreach ($this->voices as $voices) {             switch ($this->loudness) {                 case 'silent':                     array_push($song,strtolower($voices));                 break;                           case 'normal':                     array_push($song,ucfirst($voices));                 break;                 case 'loud':                     array_push($song,strtoupper($voices));                 break;                 default:                     array_push($song,$voices);                 break;             }         }            return $song;     }  }   $choir = new Choir(); $choir->line_ending = PHP_EOL; //$choir->line_ending = '<br>'; //For cleared viewing in browser use <br> tag //Define the line separator for CSV $choir->line_separator = ','; //Define the voices of animals $choir->voices = array('bark','meow','squeak'); //Call and echo the functions echo $choir->crescendo(); echo $choir->arpeggio(); 
        
     
     

Lista de respuestas

13
 
vote
vote
La mejor respuesta
 

Comencemos con la jerarquía de clase. El coro está formado por los animales.

El msg() { echo $* } warn() { msg WARNING: $* } fatal() { msg FATAL: $* exit 1 } 3 Clase debe tener una lista de su msg() { echo $* } warn() { msg WARNING: $* } fatal() { msg FATAL: $* exit 1 } 4 MIEMBROS:

  msg() {     echo $* }  warn() {     msg WARNING: $* }  fatal() {     msg FATAL: $*     exit 1 } 5  

Entonces cada animal tiene una forma diferente de cantar, pero todos cantan. Eso es polimorfismo clásico. (De hecho, cantan de una manera tan similar que el método 99887766555443326655443326 se encuentra en la clase msg() { echo $* } warn() { msg WARNING: $* } fatal() { msg FATAL: $* exit 1 } 7 ).

  msg() {     echo $* }  warn() {     msg WARNING: $* }  fatal() {     msg FATAL: $*     exit 1 } 8  

para una discusión sobre el valor de Getter / Setters en PHP (proveniente de un C ++ / Python fondo que me complace nunca tener que hacer php oop).

ahora para algunos (por ejemplo, no verifiqué los errores) críticas de bajo nivel:

  • Usa Getters and Setters
  • En su función msg() { echo $* } warn() { msg WARNING: $* } fatal() { msg FATAL: $* exit 1 } 9 Existe la funda predeterminada: simplemente emite la cadena en este caso, pero en realidad es un caso indefinido y debe lanzar una excepción.
 

Let's start with class hierarchy. The choir is made up of the animals.

The Choir class should have a list of its Animal members:

$felix = new Cat(); $rex = new Dog(); $choir = new Choir(array($felix, $rex, $bernand)); 

Then each animal has a different way of singing but they all sing . That is classic polymorphism. (In fact they sing in such a similar way that the sing() method goes into the Animal class).

class Dog extends Animal {     public function  __construct() {         $noise = 'bark';         ....  class Animal {     private $loudness;     private $loudnessLevels = array('silent', 'normal', 'screaming');     private $noise;      public function __set($name, $value) {         if($name == 'loudness') {             if(!in_array($value, $loudnessLevels) {                 throw new Excpetion('Unknown loudness');             }              $loudness = $value;      ... 

For a discussion about the value of getter/setters in PHP (coming from a C++/Python background I'm pleased never having to do PHP OOP).

Now for some (e.g. I didn't check for bugs) low-level criticism:

  • Use getters and setters
  • In your sing() function there is the default case - you just output the string in this case but actually it is an undefined case and should throw an exception.
 
 
 
 
7
 
vote

Lamentablemente, parece que no ha entendido mal o se ha perdido esta parte del breve:

Debe haber 3 animales miembros de diferentes coros (es decir, perros, gatos, ratones)

Cada animal debe tener un método de canta que devuelva una representación de cadena de una voz

Entonces suena como lo deseen para que pueda agregar un ratón al coro y solo se chilló, y un gato solo el Meow. En su lugar, tiene un solo coro que escoge al azar un sonido para hacer y no hay objetos distintos para los animales. Sospecho que querían que un animal hiciera un solo ruido que se especifica por adelantado en una forma más orientada a objetos. Algo así como mínimo:

  class /* enum */ Animals {     const CAT = 'meow';     const DOG = 'bark';     const MOUSE = 'squeak'; }  class /* enum */ Loudness {     const LOUD = 'loud';     const NORMAL = 'normal';     const SILENT = 'silent'; }  class SingingAnimal {     private $noise, $loudness;      public function __construct($noise, $loudness)     {         $this->noise = $noise;         $this->loudness = $loudness;     }      public function arpeggio()     {         //Implementation here     }      public function crescendo()     {         //Implementation here     }      public function sing()     {         //Implementation here     } }  class Choir {     public /* SingingAnimal[] */ $singers = array();      public function addAnimal($animal, $loudness)     {         $this->singers[] = new SingingAnimal($animal, $loudness);     } }  $choir = new Choir(); $choir->addAnimal(AnimalNoises::CAT, Loudness::SILENT); $choir->addAnimal(AnimalNoises::MOUSE, Loudness::LOUD); $choir->addAnimal(AnimalNoises::DOG, Loudness::NORMAL);   

Aunque incluso esto es bastante descuidado, dependiendo de la cantidad de tiempo que tenga probablemente más profundo y escribirá el estándar 9988776665544331 s y 9988777665544332 es ' Re Buscando con estas pruebas: interface Animal3 , abstract class Enum4 (Para todos los métodos de validación), 9988776655544335 , class AnimalEnum extends Enum65544336 , etc.

 

Unfortunately you seem to have misunderstood or missed this part of the brief:

There must be 3 different choir member animals (i.e. dogs, cats, mice)

Every animal must have a sing method that returns a string representation of a voice

So it sounds like they want it so you can add a mouse to the choir and it will only squeak, and a cat will only meow. Instead you have a single choir which randomly picks a sound to make and no distinct objects for the animals. I suspect they were wanting an Animal to make a single noise which is specified upfront in a more object-orientated way. Something like this at a minimum:

class /* enum */ Animals {     const CAT = 'meow';     const DOG = 'bark';     const MOUSE = 'squeak'; }  class /* enum */ Loudness {     const LOUD = 'loud';     const NORMAL = 'normal';     const SILENT = 'silent'; }  class SingingAnimal {     private $noise, $loudness;      public function __construct($noise, $loudness)     {         $this->noise = $noise;         $this->loudness = $loudness;     }      public function arpeggio()     {         //Implementation here     }      public function crescendo()     {         //Implementation here     }      public function sing()     {         //Implementation here     } }  class Choir {     public /* SingingAnimal[] */ $singers = array();      public function addAnimal($animal, $loudness)     {         $this->singers[] = new SingingAnimal($animal, $loudness);     } }  $choir = new Choir(); $choir->addAnimal(AnimalNoises::CAT, Loudness::SILENT); $choir->addAnimal(AnimalNoises::MOUSE, Loudness::LOUD); $choir->addAnimal(AnimalNoises::DOG, Loudness::NORMAL); 

Though even this is pretty sloppy, depending on the amount of time you have I'd probably go deeper and write out the standard interfaces and abstract classes they're looking for with these tests: interface Animal, abstract class Enum (for all the validation methods), class LoudnessEnum extends Enum, class AnimalEnum extends Enum, etc.

 
 

Relacionados problema

1  Cuenta las precipitaciones acumuladas en una cadena de montaña 2D  ( Count the accumulated rainfall in a 2d mountain range ) 
desafío: cuenta cuánta lluvia se recogerá en los valles entre los picos de una cordillera en un mundo 2D. La gama de montaña se define por una única ...

2  Contando un ciclo  ( Counting a cycle ) 
Una pregunta de entrevista que tengo - Cada elemento de un int Matriz puntos al otro elemento, eventualmente creando un ciclo. A partir de array[0] , ...

3  Tarea de entrevista de juego de blackjack  ( Blackjack game interview task ) 
Como parte de una entrevista reciente, me asignaron escribir un pequeño programa de blackjack. Después de enviar la solución, recibí una respuesta que "la sol...

5  Compruebe si dos cadenas son permutaciones entre sí  ( Check if two strings are permutations of one another ) 
Estoy trabajando en mi camino a través de "Cracking The Coding Entrevistion" problemas y ha terminado de implementar esta pregunta: "Dadas, dos cuerdas, escri...

11  Optimizando el corrector de anagramas Java (comparar 2 cadenas)  ( Optimizing java anagram checker compare 2 strings ) 
Un anagrama es como una mezcla de las letras en una cadena: pots es un anagrama de detener wilma es un anagrama de ilwma Estoy pasando por el ...

18  Invirtiendo una cadena  ( Reversing a string ) 
Tuve esto como una pregunta de entrevista, y el entrevistador señaló esto. Esto es lo que escribí: //C# Syntax here public string Reverse(string s) { c...

3  Codificación de longitud de ejecución  ( Run length encoding ) 
Dada una cadena de entrada, escriba una función que devuelva la longitud de ejecución Cadena codificada para la cadena de entrada. Por ejemplo, si la cad...

2  Cola de bloqueo delimitada  ( Bounded blocking queue ) 
¿Puede alguien por favor revise este código para mí? No he implementado todos los métodos para la simplicidad. NSUSerDefaults1 Preguntas abiertas: l...

8  Escriba un método para reemplazar todos los espacios en una cadena con% 20  ( Write a method to replace all spaces in a string with 20 ) 
He implementado una solución a este agrietamiento la pregunta de la entrevista de codificación: Escriba un método para reemplazar todos los espacios en una ...

3  Invertir un mapa de puntuación de letras de Scrabble  ( Inverting a scrabble letter score map ) 
Pregunta: El sistema antiguo almacenó una lista de letras por puntaje: 1 punto: "A", "E", "I", "O", "U", "L", "N", "R", "S", "T", 2 puntos: "D", "G", ...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos