Problem 1 (2.5 points)



Similar documents
Problem 1 (1.5 points)

Bucle for_in. Sintaxis: Bucles for_in con listas. def assessment(grade_list): """ Computes the average of a list of grades

Ordered Lists and Binary Trees

Taller de Emprendimiento 2 IESE Business School Version LMC

Binary Search Trees (BST)

Data Structures and Algorithms

sngraph * Optimal software to manage scale-free networks

Algorithms and Data Structures Written Exam Proposed SOLUTION

A. Before you read the text, answer the following question: What should a family do before starting to look for a new home?

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

LINIO COLOMBIA. Starting-Up & Leading E-Commerce. Luca Ranaldi, CEO. Pedro Freire, VP Marketing and Business Development

Chapter 12 Intellectual Development from One One to Three to Three

Spanish GCSE Student Guide

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Update a MS

Schema XML_PGE.xsd. element GrupoInformes. attribute XML_PGE.xsd unqualified qualified

5-Port Gigabit GREENnet Switch TEG-S5g ŸGuía de instalación rápida (1) ŸTechnical Specifications (3) ŸTroubleshooting (4)

POSIBILIDAD DE REALIZACIÓN DE PFC EN DELPHI (Luxembourg)

Propiedades del esquema del Documento XML de envío:

D755M CONTROL CARD FOR TWO SINGLE-PHASE MOTORS 220/230 VAC TARJETA DE MANDO PARA DOS MOTORES MONOFÁSICOS 220/230 VAC INSTALLATION GUIDE

Work Instruction (Instruccion de Trabajo) Wistron InfoComm (Texas) Corp.

COMPUTER SCIENCE. Paper 1 (THEORY)

Exercises Software Development I. 11 Recursion, Binary (Search) Trees. Towers of Hanoi // Tree Traversal. January 16, 2013

EJEMPLO IMPRESIÓN PDF desde llamada RFC a SAP utilizando una variable binaria SAP (XSTRING)

New words to remember

Data Structures CSC212 (1) Dr Muhammad Hussain Lecture - Binary Search Tree ADT

Curso académico 2015/2016 INFORMACIÓN GENERAL ESTRUCTURA Y CONTENIDOS HABILIDADES: INGLÉS

5-Port 10/100Mbps Fast Ethernet Switch (TE100-S5) 8-Port 10/100Mbps Fast Ethernet Switch (TE100-S8)

Práctica 1: PL 1a: Entorno de programación MathWorks: Simulink

Visual basic string search function, download source code visual basic 6.0 gratis. > Visit Now <

IBM PureSystems: Familia de Sistemas Expertos Integrados

Dictionary (catálogo)

J Intercultural communica0on, mee0ngs and nego0a0ons Seminars and case studies

Cambridge IGCSE.

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

DEMENTIA. Impact of an intervention in a rural community in Peru. Dr. Sara Gallardo Instituto de La Memoria IMEDER Puerto Rico

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

FORMULARIO DE INSCRIPCIÓN

Chapter 14 The Binary Search Tree

BDL4681XU BDL4675XU. Video Wall Installation Guide

Sample Questions Csci 1112 A. Bellaachia

FAMILY INDEPENDENCE ADMINISTRATION Seth W. Diamond, Executive Deputy Commissioner

Data Structures and Algorithms Written Examination

1. DESCRIPCIÓN DE WEB SERVICES DE INTERCAMBIO DE DATOS CON NOTARIOS

DIPLOMADO EN BASE DE DATOS

Analysis of Algorithms I: Binary Search Trees

Unit 5. Landmarks and Large Numbers. How Much Is 1,000? Common Core

Data Structure [Question Bank]

Desde la División de Advanced Solutions de Ingram Micro, queremos agradecerle su asistencia al evento Technology Day organizado por Symantec.

56h NIVEL LOWER INTERMEDIATE INGLÉS OBJETIVOS DEL CURSO. ÍNDICE 1 Objetivos didácticos_unit 1

Lista de Condiciones y Reglas

HPN Product Tools. Copyright 2012 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.

Apéndice C: Esquemas de la base de datos

Ranking de Universidades de Grupo of Eight (Go8)

COMPUTACIÓN ORIENTADA A SERVICIOS (PRÁCTICA) Dr. Mauricio Arroqui EXA-UNICEN

Previous Lectures. B-Trees. External storage. Two types of memory. B-trees. Main principles

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

DATA STRUCTURES USING C

Horizon 2020 Y emprendedores en la red

Propedéutico de Programación

Recursive Implementation of Recursive Data Structures

Binary Search Trees. Data in each node. Larger than the data in its left child Smaller than the data in its right child

Military Scholarship & Employment Program (MSEP)

REVIEWER(S): Clement Anson, Tim Dodge. Ortega Industrial Contractors

OMEGA SOFT WF RISKEVAL

Lotus Foundations Despreocupese de sus problemas de TI, enfoquese en su Negocio Network en una Caja

Técnicas Avanzadas de Inteligencia Artificial Dpt. Lenguajes y Sistemas Informáticos. FISS. UPV-EHU

Keys and records. Binary Search Trees. Data structures for storing data. Example. Motivation. Binary Search Trees

LINKED DATA STRUCTURES

UNIVERSIDADES PÚBLICAS DE LA COMUNIDAD DE MADRID PRUEBA DE ACCESO A ESTUDIOS UNIVERSITARIOS (LOGSE) Curso (Junio)

LOS ANGELES UNIFIED SCHOOL DISTRICT POLICY BULLETIN

Monitoreo de Bases de Datos

Symbol Tables. Introduction

LA HOMOLOGACIÓN DE ESTUDIOS EN LA COMUNIDAD EUROPEA: PERSPECTIVAS DESDE EL PUNTO DE VISTA DEL TRABAJO SOCIAL

Package hive. January 10, 2011

Resumen de Entrevista: Asociación de Agentes de Aduana del Puerto de Manzanillo

Binary Heaps. CSE 373 Data Structures

DESIGN OF ACTION PLANS AGAINST NOISE IN NAVARRE, SPAIN

New words to remember

RIGGING CONDITIONS AND PROCEDURES

Dave Rojas. Summary. Experience. Software Engineer - Web Developer & Web Designer davejrojas@gmail.com


How To Know If An Ipod Is Compatible With An Ipo Or Ipo (Sanyo)

TREE BASIC TERMINOLOGIES

Come to London, divorce capital of the world

Binary Heap Algorithms

Prior Knowledge Needed -Students should have a basic Spanish vocabulary (basic verbs, determiners, pronouns, adjectives, adverbs, etc)

Completa los recuadros con las conjugaciones correctas del verbo TO BE. Elige la opción más adecuada para responder a las siguientes preguntas.

Inteligencia Artificial Representación del conocimiento a través de restricciones (continuación)

VMware vsphere with Operations Management: Fast Track

Big Data and Scripting. Part 4: Memory Hierarchies

Level 2 Spanish, 2012

Sub OPT() j = 1 k = 1 m = 1 n = 1 o = 1 g = 1 h = 1

Apéndice C: Código Fuente del Programa DBConnection.java

Data Structure with C

How To Create A Tree From A Tree In Runtime (For A Tree)

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

Tema: Encriptación por Transposición

Curso SQL Server 2012 para Desarrolladores

Transcription:

Duration: 90 minutes University Carlos III of Madrid Instructions for the exam: Books and notes are not allowed. Please write your name, surname, NIA and group on all pages. Problem 1 (2.5 points) Context: We have a simple linked list, implemented by MyLinkedList and Node classes: public class MyLinkedList { private Node first; private int numelems; MyLinkedList (){ first=null; numelems=0; public int getsize(){return numelems; public Object retrieventh (int pos){ // To implement public int insertnth (Object o, int pos){ // To implement public class Node { private Object info; private Node next; Node (Object obj) {info=obj; next=null; public void setinfo(object obj){ info=obj; public void setnext(node n){ next=n; public Object getinfo() {return info; public Node getnext(){return next; Section 1 (1.25 points) Implement the method public Object retrieventh (int pos) 1

from MyLinkedList class. This method returns the element placed at the pos -th position. If the position specified does not exist in the list (i.e. the position is out of bounds), the method must return null. Positions start at index 1. The method must not delete any item from the list. Section 2 (1.25 points) Implement the method public int insertnth (Object obj, int pos) from MyLinkedList class. This method takes as parameters both the object to be inserted and the position at which the object will be inserted. Positions start at index 1. Inserting an object at a specific position means that this object must be placed at that position. It might be necessary to shift other elements. For example, if there is an object to be inserted at position 3, then the element that was at position 3 before the insertion will be shifted to position 4. If the position specified is higher than the number of elements in the list, the object must be added at the end of the list (e.g. if the list contains 4 elements, and the position at which the new element is wanted to be added is 10, then the new element will be actually inserted at position 5). If the position specified is 0 or lower than 0, then no insertion must be done. The method must return the position at which the new element is finally inserted (the case in which pos>list size must be taken into account), or -1 is no insertion is made. Problem 2 (2.5 points) Context: We have a binary search tree representing a library (Library class). Each tree node stores information about a book: title, author and ISBN code. The tree is sorted alphabetically by book title in increasing order. We can assume there will not be two books with the same title. The following code implements the library: 2

public class Library { BNode root; public boolean insertbook(book con){ if (root==null) { root=new BNode(con); return true; else { return root.insertbook(con); public int getnumbooks (){ if (root==null) return 0; else return root.getnumbooks(); public class Book{ String title; String author; String isbn; Contact (){ title=""; author=""; isbn=""; public String gettitle() {return title; public String getauthor() {return author; public String getisbn() { return isbn; public class BNode { private Book info; private BNode left; private BNode right; public void setleft(bnode n) {left=n; public void setright(bnode n) {right=n; public BNode getright() {return right; public BNode getleft() {return left; public Book getinfo() {return info; public void setinfo(book c){ info = c; BNode (Book con) { setinfo(con); setleft(null); setright(null); public int getnumbooks(){ // // TO IMPLEMENT IN SECTION 1 public boolean insertbook(book con){ // // TO IMPLEMENT IN SECTION 2 3

Section 1 (1.25 points) Implement the method getnumbooks from BNode class. This method returns the number of books in the subtree which root node is the one invoking the method. Notice this method is the one called from getnumbooks method, from Library class, in order to get the total number of books in the library. This method must be solved recursively. Section 2 (1.25 points) Implement the method insertbook from BNode class. This method inserts the book (Book) specified as parameter at its corresponding place. Notice this method is the one called from the method insertbook from Library class. The method must return true if the book is inserted in the tree, or false if the book is not inserted because there is another book with the same title in the tree. This method must be solved recursively. 4

SOLUCIONES PROBLEMA 1 public Object retrieventh (int pos){ Node aux=first; if (pos<=0) return null; if (pos>getsize()) return null; for (int i=1;i<pos;i++){ aux=aux.getnext(); return aux.getinfo(); public int insertnth (Object o, int pos){ Node aux=first; Node newnode=new Node(o); if (pos<=0){ return -1; if (pos==1) { newnode.setnext(first); first=newnode; numelems++; else { if (pos>getsize()){ pos=getsize()+1; for (int i=1;i<pos-1;i++){ aux=aux.getnext(); newnode.setnext(aux.getnext()); aux.setnext(newnode); numelems++; return pos; Criterios de calificación Problema 1 Apartado 1) 0,75 puntos - Recorrer correctamente la lista hasta la posición requerida. Si la indexación no la hace correctamente desde 1, sino desde 0, se le da 0,5 puntos. 0,25 puntos - Check correcto de índice de posición fuera de rangos. 0,25 puntos - Return correcto del objeto. Apartado 2) 0,10 puntos. Crear correctamente el nodo a insertar. 0,25 puntos. Insertar correctamente en la primera posición. 0,25 puntos, recorrer hasta la posición a insertar. 0,25 puntos. Insertar correctamente en la posición nth. 5

0,15 controlar que la posición requerida sea mayor que el tamaño de la lista. 0,25 devolver correctamente la posición final. SOLUCIONES PROBLEMA 2 public int getnumbooks (){ int n=1; if (this.getleft()!=null){ n+=this.getleft().getnumbooks(); if (this.getright()!=null){ n+=this.getright().getnumbooks(); return n; public boolean insertbook(book newcon){ boolean res=false; int comp = this.getinfo().getname().compareto(newcon.getname()); if (comp == 0) { res=false; else if (comp < 0){ if (this.getright()==null) { this.setright(new BNode(newcon)); res=true; else{ res = this.getright().insertbook(newcon); else if (comp > 0){ if (this.getleft()==null) { this.setleft(new BNode(newcon)); res=true; else { res = this.getleft().insertbook(newcon); return res; Criterios de calificación Apartado 1) 0,25 Sumar correctamente 1 por el nodo actual. 0,25 Comprobar correctamente que las ramas!= null antes de invocar. 0,25 Invocar correctamente de forma recursiva. 0,25 sumar correctamente los return de las ramas. 0,25 devolver suma completa. Apartado 2) 0,15 Comparación correcta del título. 0,25 Comprobación de si es el título del nodo actual. 0,25 Comprobar si la rama correspondiente es null o no. 6

0,25 Insertar si la rama es null. 0,25 Invocar correctamente la llamada recursiva si la rama no es null. 0,10 return correcto de true/false. 7