Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 1. A line of people at an amusement park ride.
- The line is composed of members, represented as strings.
- There is a front to the line, as well as a back.
- When someone enters the line, place them at the end.
- People may leave the line whenever they see fit, and those behind them take their place.
- Given the above real-world information, use an array data structure to code the following solution.
- a) Use an array input: ["Vivian", "Ava", "Josh", "Patrick", "Mike"]
- b) Insert a new person, "Mary" at the end of the line. In other words, you should insert Mary after Mike.
- c) Find a person in line named "Josh." This function should return the position of 2 in the array, (recall that arrays are 0-based).
- d) Find a person in line named "Emily." What should your function return if it does not find the item in the array?
- e) What if Ava wants to allow a friend, "Melissa", to cut in line in front of her? How would you code this so Melissa appears before Ava?
- f) If Patrick wants to leave the line, how would you delete him from the array?
- //a
- var peopleInLine = ["Vivian", "Ava", "Josh", "Patrick", "Mike"];
- function addPerson(lineArray, name) {
- lineArray.push(name);
- console.log(lineArray);
- }
- //b
- addPerson(peopleInLine, "Mary");
- function findPerson(array, name) {
- for(var i = 0; i < array.length; i++) {
- if(peopleInLine[i] === name) {
- console.log(i);
- return;
- }
- }
- console.log(name + " was not found");
- }
- //c
- findPerson(peopleInLine, "Josh");
- //d
- findPerson(peopleInLine, "Emily");
- function cutTheLine(lineArray, personInLine, personCutting) {
- for(var i = 0; i < lineArray.length; i++){
- if(lineArray[i] === personInLine) {
- lineArray.splice(i, 0, personCutting);
- lineArray.join();
- i++;
- }
- }
- console.log(lineArray);
- }
- //e
- cutTheLine(peopleInLine, "Ava", "Melissa");
- function removePerson(lineArray, personLeaving) {
- for (var i = 0; i < lineArray.length; i++){
- if(lineArray[i] === personLeaving){
- lineArray.splice(i, 1);
- }
- }
- console.log(lineArray);
- }
- //f
- removePerson(peopleInLine, "Patrick");
- 2. Provide another real-world example that you can model using a data structure.
- An Ice cream shop can keep the flavors of their ice creams in an array data structure. They would be able to add new flavors, delete flavors.
- 3. How would your data structure allow developers to access and manipulate the data?
- There are functions for different ways to manipulte the data
Add Comment
Please, Sign In to add comment