2
I was participating in an internship test and I was proposed the following problem:
I would have to read the JSON below:
[
{ "nome":"Jabba, the Hutt", "jedi":false, "sistemas":[ "Tatooine" ] },
{ "nome":"Chewbacca", "jedi":false, "sistemas":[ "Kashyyk" ] },
{ "nome":"Han", "jedi":false, "sistemas":[ "Tatooine", "Coruscant" ] },
{ "nome":"Leia", "jedi":true, "sistemas":[ "Alderaan", "Endor" ] },
{ "nome":"Luke", "jedi":true, "sistemas":[ "Tatooine", "Dagobah" ] },
{ "nome":"Yoda", "jedi":true, "sistemas":[ "Kashyyk", "Dagobah" ] },
{ "nome":"Obi-Wan", "jedi":true, "sistemas":[ "Coruscant", "Mustaphar" ] },
{ "nome":"Darth Vader", "jedi":false, "sistemas":[ "Tatooine", "Mustaphar" ] }]
And you’d have to create a new JSON that would look something like this:
[{"nome": Darth Vader, "contato":["Luke", "Leia" ....]},{}]
It would be a JSON that would have in each field the name of the character and an array that would be the contacts.
Now the condition for a character to enter the contact array of another character is:
that this character is not the same character from the name field
2 characters can contact each other if they are both "jedi":true OR if they have any system in common. For example the Jabba, the Hutt will be Han’s contact because both have Tatooine in their arrays in the field systems.
This is my code:
var v = [
{ "nome":"Jabba, the Hutt", "jedi":false, "sistemas":[ "Tatooine" ] },
{ "nome":"Chewbacca", "jedi":false, "sistemas":[ "Kashyyk" ] },
{ "nome":"Han", "jedi":false, "sistemas":[ "Tatooine", "Coruscant" ] },
{ "nome":"Leia", "jedi":true, "sistemas":[ "Alderaan", "Endor" ] },
{ "nome":"Luke", "jedi":true, "sistemas":[ "Tatooine", "Dagobah" ] },
{ "nome":"Yoda", "jedi":true, "sistemas":[ "Kashyyk", "Dagobah" ] },
{ "nome":"Obi-Wan", "jedi":true, "sistemas":[ "Coruscant", "Mustaphar" ] },
{ "nome":"Darth Vader", "jedi":false, "sistemas":[ "Tatooine", "Mustaphar" ] }];
function verificaSist(){
var verifica = false;
for(var i in arguments[0]){
for(var b in arguments[1]){
if(arguments[0][i]===arguments[1][b]){
verifica = true;
break;
}
}
if(verifica == true){
break;
}
}
if(verifica == true){
return true;
}
else{
return false;
}
}
function criaAgenda(v){
var agenda=[];
var contato = []
for(var personagem1 of v){
for(var personagem2 of v){
var sist = [personagem1.sistemas, personagem2.sistemas];
var d = verificaSist.apply(null,sist);
if(((personagem1.jedi == true && personagem2.jedi==true)|| d == true) && personagem1.nome !== personagem2.nome){
contato.push(personagem2.nome);
}
}
agenda.push({"nome":personagem1.nome, "contato":contato=[]});
}
return JSON.stringify(agenda);
}
console.log(criaAgenda(v));
The problem as far as I’m concerned is this if
:
if(((personagem1.jedi == true && personagem2.jedi==true)|| d == true) && personagem1.nome !== personagem2.nome)
I just can’t think of anything better.
"Read" has no relation to "Darth Vader": both are not "Jedi" and have no common systems.
– Sam