Question

Please help with Java array list:

In this lab, you will implement two basic heuristics for updating a list of Intergers based on a sequence of requests to elem

import java.util.ArrayList;

public class ListUpdate {

/**
* Does a linear search through the ArrayList list, returning the index of the first occurrence of
* valToFind.
*
* Starting from index 0, check each element in list and return the index of the first element
* that matches valToFind.
*
* @param valToFind The int value to search for.
* @param list The ArrayList of Integers to search in.
* @return The index of the first occurrence of valToFind in list. If list is null, or valToFind
* is not found, return -1.
*/
public static int linearSearch(int valToFind, ArrayList<Integer> list) {
return -99;
}

/**
* Performs the Move to Front heuristic on the element located at index in list.
*
* Moves the element at index in list to index 0.
*
* If the list is null, or the index is out of bounds, the method should end gracefully without
* changing list.
*
* @param list The ArrayList to update.
* @param index The element in the ArrayList to move to the front.
*/
public static void moveToFront(ArrayList<Integer> list, int index) {
}

/**
* Performs the Transpose heuristic on the element located at index in list.
*
* Moves the element at index to index - 1. That is, it moves the item at index one spot closer
* to index 0.
*
* If the list is null, or the index is out of bounds, the method should end gracefully without
* changing list.
*
* @param list The ArrayList to update.
* @param index The element in the ArrayList to move to the front.
*/
public static void transpose(ArrayList<Integer> list, int index) {
}

/**
* Runs either the Move to Front or the Transpose heuristic on a given list over a sequence of
* requests, calculating the cost for accessing the items.
*
* For each element in requests:
* - Find its index in list. Let i be the index of the request in list.
* - The cost to access an item at index i (0 based) is i + 1. Add this cost to a running
* total.
* - Apply the move to front heuristic (doMTF is true) or the Transpose heuristic (doMTF is
* false) to list to the element at index i.
*
* Don't duplicate code! Use your linearSearch, moveToFront, and Transpose methods!
*
* @param requests The sequence of request to process.
* @param list The list to update with each request.
* @param doMTF A flag that is true when the heuristic to use is Move to Front and false when it
* is Transpose.
* @return The total access cost for the all the elements of requests.
*/
public static int runListUpdate(ArrayList<Integer> requests,
ArrayList<Integer> list,
boolean doMTF){
return -99;
}
  
  
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Program:

import java.util.ArrayList; import java.util.Arrays; public class List Update { * Does a linear search through the ArrayList

* @param list The ArrayList to update. * @param index The element in the ArrayList to move to the front. */ public static voi

Sample output:

// test the methods

public static void main(String[] args)
    {
        ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
        ArrayList<Integer> valuesAccessed = new ArrayList<>(Arrays.asList(2,4));
        int totalCost = ListUpdate.runListUpdate(valuesAccessed,list,true);
        System.out.println("list = " + list);
        System.out.println("totalCost = " + totalCost);
    }

Console X <terminated List Update [Java Application) C:\Program Files list = [4, 2, 1, 3, 5] totalCost = 6

public static void main(String[] args)
    {
        ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
        ArrayList<Integer> valuesAccessed = new ArrayList<>(Arrays.asList(2,4));
        int totalCost = ListUpdate.runListUpdate(valuesAccessed,list,false);
        System.out.println("list = " + list);
        System.out.println("totalCost = " + totalCost);
    }

Console X <terminated ListUpdate [Java Application) CA Program Files list = [2, 1, 4, 3, 5] totalCost = 6

Code to copy:

import java.util.ArrayList;
import java.util.Arrays;

public class ListUpdate
{
  
    /**
     * Does a linear search through the ArrayList list, returning the index of the first occurrence of
     * valToFind.
     * <p>
     * Starting from index 0, check each element in list and return the index of the first element
     * that matches valToFind.
     *
     * @param valToFind The int value to search for.
     * @param list      The ArrayList of Integers to search in.
     * @return The index of the first occurrence of valToFind in list. If list is null, or valToFind
     * is not found, return -1.
     */
    public static int linearSearch(int valToFind, ArrayList<Integer> list)
    {
       if(list==null)
           return -1;
       // do linear search
       for(int i=0;i<list.size();i++)
       {
           if(list.get(i)==valToFind)
               return i;
       }
       // if value does not found, return -1
        return -1;
    }

    /**
     * Performs the Move to Front heuristic on the element located at index in list.
     * <p>
     * Moves the element at index in list to index 0.
     * <p>
     * If the list is null, or the index is out of bounds, the method should end gracefully without
     * changing list.
     *
     * @param list The ArrayList to update.
     * @param index The element in the ArrayList to move to the front.
     */
    public static void moveToFront(ArrayList<Integer> list, int index)
    {
       // Method ends gracefully without changing list.
        if (list == null || index < 0 || index > list.size()-1) return;
        // Otherwise
        // find the value at index
        int valueToMoveToFront = list.get(index);
        // Remove element from the index position
        list.remove(index);
        // Add temporary element at index 0. This method will move other elements to right.      
        list.add(0, valueToMoveToFront);
    }
    /**
     * Performs the Transpose heuristic on the element located at index in list.
     * <p>
     * Moves the element at index to index - 1. That is, it moves the item at index one spot closer
     * to index 0.
     * <p>
     * If the list is null, or the index is out of bounds, the method should end gracefully without
     * changing list.
     *
     * @param list The ArrayList to update.
     * @param index The element in the ArrayList to move to the front.
     */
    public static void transpose(ArrayList<Integer> list, int index)
    {
       // Method ends gracefully without changing list.
        if (list == null || index < 0 || index > list.size()-1) return;
        // Otherwise
        // find the value at index
        int valueToMove = list.get(index);
        // Remove element from the index position
        list.remove(index);
        // Add temporary valueToMove at index 0. This method will move other elements to right.
        list.add(index-1, valueToMove);
    }

    /**
     * Runs either the Move to Front or the Transpose heuristic on a given list over a sequence of
     * requests, calculating the cost for accessing the items.
     * <p>
     * For each element in requests:
     * - Find its index in list. Let i be the index of the request in list.
     * - The cost to access an item at index i (0 based) is i + 1. Add this cost to a running
     * total.
     * - Apply the move to front heuristic (doMTF is true) or the Transpose heuristic (doMTF is
     * false) to list to the element at index i.
     * <p>
     * Don't duplicate code! Use your linearSearch, moveToFront, and Transpose methods!
     *
     * @param requests The sequence of request to process.
     * @param list     The list to update with each request.
     * @param doMTF    A flag that is true when the heuristic to use is Move to Front and false when it
     *                 is Transpose.
     * @return The total access cost for the all the elements of requests.
     */
    public static int runListUpdate(ArrayList<Integer> requests,ArrayList<Integer> list,boolean doMTF)
    {
       int totalCost = 0;
       // for each number in the requests
        for(int request: requests)
        {
           // Find the current number index in the list
            int i = ListUpdate.linearSearch(request,list);
            // Add the cost(i+1) of accessing an item at index i, to a running total
            totalCost = totalCost + i + 1;
            // if doMTF is true, apply the move to front heuristic
            if(doMTF)
            {
                ListUpdate.moveToFront(list,i);
            }
            // otherwise, Apply the Transpose heuristic
            else
            {
                ListUpdate.transpose(list,i);
            }          
        }
        // return the total access cost for the all the elements of requests.
        return totalCost;
    }
}

Add a comment
Know the answer?
Add Answer to:
Please help with Java array list: import java.util.ArrayList; public class ListUpdate { /** * Does a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • JAVA programming 9.9 Ch 9, Part 2: ArrayList Searching import java.util.ArrayList; public class ArrayListSet {    ...

    JAVA programming 9.9 Ch 9, Part 2: ArrayList Searching import java.util.ArrayList; public class ArrayListSet {     /**      * Searches through the ArrayList arr, from the first index to the last, returning an ArrayList      * containing all the indexes of Strings in arr that match String s. For this method, two Strings,      * p and q, match when p.equals(q) returns true or if both of the compared references are null.      *      * @param s The string...

  • How do i rewrite this code only using the list below? import java.util.ArrayList; import java.util.Collection; import...

    How do i rewrite this code only using the list below? import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.HashSet; public class RotationCheck {    /**    * Rotates the elements in the specified list by the specified distance. After calling this    * method, the element at index {@code i} will be the element previously at index    * {@code (i - distance) % list.size()}, for all values of {@code i} between {@code 0} and    * {@code...

  • JAVA - Circular Doubly Linked List Does anybody could help me with this method below(previous)? public...

    JAVA - Circular Doubly Linked List Does anybody could help me with this method below(previous)? public E previous() { // Returns the previous Element return null; } Explanation: We have this class with these two implemented inferfaces: The interfaces are: package edu.ics211.h04; /** * Interface for a List211. * * @author Cam Moore * @param the generic type of the Lists. */ public interface IList211 { /** * Gets the item at the given index. * @param index the index....

  • PLEASE COMPLETE THE CODES. package javaprogram; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; /** * Movie class...

    PLEASE COMPLETE THE CODES. package javaprogram; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; /** * Movie class definition. * * @author David Brown * @version 2019-01-22 */ public class Movie implements Comparable { // Constants public static final int FIRST_YEAR = 1888; public static final String[] GENRES = { "science fiction", "fantasy", "drama", "romance", "comedy", "zombie", "action", "historical", "horror", "war" }; public static final int MAX_RATING = 10; public static final int MIN_RATING = 0; /** * Converts a string of...

  • complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class...

    complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class WordDetective { /** * Finds the specified set of words in the specified file and returns them * as an ArrayList. This finds the specified set in the file which is on the * line number of the set. The first line and set in the file is 1. * * This returns an ArrayList with the keyword first, then : and then followed...

  • Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)...

    Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)    {        this.size = size;    }    /** Reference to list head. */    private Node<E> head = null;    /** The number of items in the list */    private int size = 0;       /** Add an item to the front of the list.    @param item The item to be added    */    public void addFirst(E...

  • /** * A collection of methods related to multi-dimensional arrays. */ public class Array2Lab { /**...

    /** * A collection of methods related to multi-dimensional arrays. */ public class Array2Lab { /** * Return whether k is in list. * Precondition: the elements of list are not null. * @param list the array to be searched. * @param k the number to search for. * @return true if k is an element of list, and false otherwise. */ public static boolean contains(Object[][] list, Object k) { return false; }    /** * Create a String that...

  • import java.util.List; import java.util.ArrayList; import java.util.LinkedList; public class ListPractice {       private static final int[]...

    import java.util.List; import java.util.ArrayList; import java.util.LinkedList; public class ListPractice {       private static final int[] arr = new int[100000];    public static void main(String[] args) {        for(int i=0; i<100000; i++)            arr[i] = i;               //TODO comment out this line        LinkedList<Integer> list = new LinkedList<Integer>();               //TODO uncomment this line        //List<Integer> list = new ArrayList<Integer>();               //TODO change the rest of the...

  • complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class...

    complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class WordDetective { /** * Picks the first unguessed word to show. * Updates the guessed array indicating the selected word is shown. * * @param wordSet The set of words. * @param guessed Whether a word has been guessed. * @return The word to show or null if all have been guessed. */ public static String pickWordToShow(ArrayList<String> wordSet, boolean []guessed) { return null; //TODO...

  • Need Help Using Java programming only import java.util.ArrayList; //Import anything you need here public class Dictionary...

    Need Help Using Java programming only import java.util.ArrayList; //Import anything you need here public class Dictionary {     // Declare any variables you feel necessary here     public Dictionary(/*DO NOT PUT ANY PARAMETERS HERE!*/) {         // Initialise those variables     }     /***      * @return number of terms currently in the dictionary hint: starts at 0 when      *         there are no terms      */     public int numberOfTerms() {         return 0;     }     /***     ...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT