Develop a function that concatenates elements of the same position in different arrays according to a given condition

Asked

Viewed 1,280 times

-1

This is my first question here on the site, so sorry if my way of questioning does not follow the expected pattern rs. I’m taking a programming course Javascript for beginners to apply for a scholarship. In one of the proposed exercises (prerequisite to enter the contest) was drawn up the following challenge:

Program a movie function that receives three arrays with the names of characters, movies and year of debut in the cinema. The role should also receive an id value chosen by the user with a range of 1 up to the maximum size of the arrays provided and return a phrase with the following template: "character is a character from the film that debuted in the cinema at release." If the id value is invalid, the function should return the phrase "This is not a valid option."

Example:

characters = ["Hermione", "Trinity", "Read"]

movies = ["Harry Potter", "Matrix", "Star Wars"]

lancings = [2001, 1999, 1977]

id = 3

You must return the string:

Leia is a character from the movie Star Wars which premiered in the cinema in 1977

The function, as well as the arrays, are already given by the developer himself and are inserted in the code of the machine itself, it is up to me to just complete it from the line that says "Write down your code".

In order to answer it I wrote the following code:

    function filme(personagens, filmes, lancamentos, id)
{
  // Escreva abaixo o seu código:
  if (id < 1 || id > personagens.length) {
    return ("Essa não é uma opção válida.")
     
  } else { 
    return (personagens[id--] + ' é um personagem do filme ' + filmes[id--] + ' que estreou no cinema em ' + lancamento[id--])

  }
  
}

However when putting it to run, the system returns error of my answer. More precisely, this is what presents me:

An invalid id must return an error message

According to him, my code is not returning the error message when an invalid ID is entered, as required by the statement. But I don’t see how that’s possible once I’ve defined through parole if the conditions under which he must do what the question asks of me.

Someone there can argue where is the error of my logic.

At once I thank you for your cooperation !

Obs: remembering that this is a question for beginners and therefore does not contain more elaborate solutions, basically I must solve the issue using the conditional if/Else, variables, arrays and nothing more.

  • You decrement twice id on the Return line, this in itself invalidates the post as a typo. Another thing, specific requirements of third-party websites (many are very doubtful) end up disrupting the posting. Here it is always important a [mcve] of the problem, focusing on a point doubt, and not exercise statements. Stack Overflow Survival Guide in English explains this much better and can help in formulations of upcoming posts.

3 answers

1


Your solution is partially correct, but there are several errors that must be corrected.

Starting from the most basic, in any programming language, the numbers start from 0, so when I ask you for the first element of something, that element is not at position 1, but at position 0 and whereas you start from position 0, means that its last element is actually in position length - 1.

With that we can adjust your if for: if (id < 0 || id >= personagens.length)

As you said such arrays will already be filled in, and I assume they are filled in correctly so we will not check any case where the array you put is empty.

Second problem, you need to know the operators logics in any language you are programs, are usually equal in almost all, at least the basic ones, in your case you are applying the Operator -- the value of your id each time you read some value with it, which means that if the id initial was 3, because you are decreasing it at each reading, at the end it is worth 1 and if I understood correctly this is not what you need, but you need to read the element that is in the same position in 3 different arrays, that would be:

(personagens[id] + ' é um personagem do filme ' + filmes[id] + ' que estreou no cinema em ' + lancamento[id])

The message you made referring:

An invalid id must return an error message

You’re probably saying that if the id is invalid you must return an error message, as an error. Returning a text/string saying that the value is wrong is not the same as generating an error, errors can be handled inside a block try/catch, and as the name suggests, the code tries to do something and if an error is generated inside this something, it will stop in the catch to maybe show an error message or something. So in your case instead of returning a string, you do what we call throw or lançar an exception, in JS you can do in the following way:

if (id < 0 || id >= personagens.length)
  throw new Error("Essa não é uma opção válida.");

When you launch an exception the execution code is blocked and it returns an error to the caller, and it is up to the caller to deal or not with the error, if untreated the same can crash your program.

Your final code with a touch of beauty could be something like:

function filme(personagens, filmes, lancamentos, id){
  if (id < 0 || id >= personagens.length)
    throw new Error("Essa não é uma opção válida.");
  
  // Não é necessário um bloco else aqui, pois uma vez que o seu programa chega a este ponto você pode ter certeza que nenhum erro ocorreu durante a verifica do if
  return `${personagens[id]} é um personagem do filme ${filmes[id]} que estreou no cinema em ${lancamento[id]}`
  
}

Tip: Use interpolation, is more beautiful and easier to read and you don’t have to worry about adding several + var + in your code. And if your user passes an id to the function that does not start with 0, the best thing to do is to decrease 1 of the received variable as input at the beginning of the function, or better still create another variable that is equal to received - 1, this way we do not touch the original and use the variable with the right value.

  • I was able to solve it. The solution turned out to be a hybrid in his tip and that of Diogenes Martins. His explanation was particularly helpful in clarifying that he was decreasing the value of the variable every time he declared the logical operator --. When using the number 1 instead of 0 as a comparison value, it was necessary by virtue of the question itself So, to solve the implication that this would have on arrays later, I was obliged to decrease the ID (id-) only once before declaring itlo in the concatenation of the strings as soon as I terminate the conditional.

-1

I tried to make the code more basic, see if this would solve

function filme(personagens, filmes, lancamentos, id){
      
      if (id >= personagens.length){
        return ("Essa não é uma opção válida.");
        }else{
          id
        return (personagens[id] + " é um personagem do filme " + filmes[id] + " que estreou no cinema em " + lancamentos[id]) 
        }
    }
    
    console.log(filme(["Hermione", "Trinity", "Leia"], ["Harry Potter", "Matrix", "Star wars"], [2001, 1999, 1977], 2))

-2

I think the Digital House system requires an exact program. Thus, despite several solutions, it will continue to generate this error in their system. Another detail: the code has to be basic, using content that has been passed so far in the course, so it will get error even if the program is correct as posted by Leo Letto.

I did so and it worked exactly on the tests, but still the course system does not accept.

https://jsfiddle.net/hLwtr2ef/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.