I was participating in an internship test and the following problem was proposed to me:
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 I would 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 character's name and an array that would be the contacts.
Now the condition for a character to enter the contact array of another character is:
-
This character is not the same character as the
-
2 characters can be contacts between them if both are "jedi": true OR if they have any system in common. For example Jabba, the Hutt will be Han contact because both have Tatooine in their arrays in the systems field.
Here's 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 I see is this if
:
if(((personagem1.jedi == true && personagem2.jedi==true)|| d == true) && personagem1.nome !== personagem2.nome)
I just can not think of anything better.