Question

In: Computer Science

Linked List Outlab Political RiffRaff Manager General Overview In case you missed it we just had an...

Linked List Outlab

Political RiffRaff Manager

General Overview

In case you missed it we just had an election and America is very divided I have decided you will write a program to select our politicians that take office in a fair and just way. We just went through a year of all the slimy politicians, and all the political supporters on both sides of the aisle coming out of the woodwork spouting their verbal abuse on each other. And even though the election is over the attacks and bitterness hasn't ended. Both sides are claiming "election foul".

You are going to fix it.  

 Every year ACM sponsors programming competitions at the local, regional and world levels. This assignment is adapted from a problem that appeared at one of these competitions...........very loosely adapted. 

Purpose

The purpose of the assignment is to give you experience implementing a circular, doubly linked list and all the methods and management that is needed for such a list. 

Problem Statement

In a serious attempt to downsize (reduce) the riffRaff in politics, The New Rhinoceros Party with the motto "we promise to keep none of our promises." has decided on the following strategy. Every day all Rhino applicants will be placed in a large circle, facing inwards. Someone is arbitrarily chosen as number 1, and the rest are numbered up to N (so N is the amount of candidates in the circle and N will be standing next to 1  as the end of the potential candidates).

Now you will have two officials that will be the selectors, selector one holds a number we will call k, official two has a number we will call m. Selector k will start at candidate 1 (first candidate) and will move around the circle of candidates clockwise counting off candidates until it counts k candidates and then stop pointing at the kth candidate.

Selector m will start at candidate N (last candidate) and will move around the circle of candidates counter-clockwise counting off candidates until it gets to the mthcandidate. 

Now one of two things will have taken place, the selectors will be pointing at two different candidates, or they will be pointing at the same candidate. If the selectors are pointing to two different candidates we will remove the candidates from the circle of candidates (these candidates will be ELIMINATED), starting with k candidate first and then the m candidate. The k selector will need to move clockwise up to the next available candidate and prepare to start counting again. The m selector will do the same but it will always move counter-clockwise. After removal the two selectors will need to be ready to start counting again at the next available candidate.  

If both selectors stop and they are pointing to the same candidate we have found ourselves a worthy candidate that will be put into political office.......keep this candidate off to the side, but remove the candidate from the circle of candidates.......which means k selector will need to be moved clockwise to next available and m selector will need to be moved counterclockwise to the next available candidate. 

Each selector then starts counting again at the next available person and the process continues until no-one is left. Note that the two victims (sorry, trainees) leave the ring simultaneously, so it is possible for one official to count a person already selected by the other official.

Input File Format

Write a program that asks the user for the name of a valid input file. If the file exists, the program should read in (in that order) the three numbers (N, k and m; k, m > 0, 0 < N < 100) and determine the order in which the applicants are sent off for political retraining. Each set of three numbers will be on a separate line and the end of data will be signaled by three zeroes (0 0 0).

Here is a sample input file:

10 4 3
17 6 4
0 0 0

Output Requirements

The output should be sent to a file named LinkedListProgram.txt. For each input, the output should show the order in which the people are chosen. For each round in which two different people are chosen, list the person chosen by the counter-clockwise official first.

Here is the required output for the an input file:

Program 4
---------

N = 10, k = 4, m = 3

Output
------
4 8
9 5
3 1
2 6
10
7

End of Program 4

(Note: There seems to be an error in either the output or the instructions, because I cannot get get this exact output from the instructions given. Editing the code to make it match the output is fine.)

Requirements and Grading

12 points. You are required to design and implement your own linked list (in the style of what we have done in lecture this week) as opposed to using a built-in class provided by Java. The class you use should be doubly-linked (6 points), circular (3 point) and if it works of course(3 point).12 points. The program finds the correct answer. Your TA will test your program on some sample files after the assignment is due. Thus, please test your program thoroughly before submitting it.6 points. The program finds the solution in a reasonably efficient manner. For example, if N = 10, k = 1 and m = 450, the m judge should not circle around the candidates needlessly.5 points. The program sends it output to a file named LinkedListProgram.txt5 points. The program's output matches the required output format described above.10 points. The program uses good style. This includes factors such as appropriate commenting, good object oriented design, readable code that is high quality, etc.

Solutions

Expert Solution

Driver.java

import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;

public class Driver {

   public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException {
       // TODO Auto-generated method stub
       RiffRaff riff = new RiffRaff();
       riff.readIn();
   }

}


RiffRaff.java

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;

public class RiffRaff {
   PrintWriter writer;
   Scanner scanner = new Scanner(System.in);
   String inFile;
   int line; // what line we are currently reading in

   public void readIn() throws UnsupportedEncodingException, FileNotFoundException { // Reads in the
                                                               // N,K, and M
                                                               // values
       writer = new PrintWriter("LinkedListProgram.txt", "UTF-8");
       System.out.println("What file would you like to use as the input file (Example: input.txt)");
       inFile = scanner.nextLine();
       try {
           // open the file that the user inputs
           FileReader fileName = new FileReader(inFile);
           Scanner fileRead = new Scanner(fileName);
           int sum = 1;
           int n, k, m;
           n = 1;
           k = 1;
           m = 1;
           while (sum != 0) {
               sum = 0;
               n = fileRead.nextInt();
               k = fileRead.nextInt();
               m = fileRead.nextInt();
               sum = n + k + m;
               CircleLinkedList LL = new CircleLinkedList(n,writer);
               if (sum != 0) { // Calls the linked list method if the sum is
                               // not 0 (its not the end of the file)
                   System.out.println(n + " " + k + " " + m);
                   LL.candidateSelection(n, k, m);
               }else{
                   LL.closeWriter();
               }
           }
           fileRead.close();
       } catch (FileNotFoundException exception) {
           // error is thrown if file cannot be found. See directions or email
           // me...
           System.out.println("File Not Found!");
       }
       System.out.println("Done");
   }

}

CircleLinkedList.java

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

public class CircleLinkedList {
   Node first = new Node(1);
   Node current = first;
   Node last = first;
   int candidates;
   PrintWriter writer;

   public CircleLinkedList(int n, PrintWriter inWriter) throws FileNotFoundException, UnsupportedEncodingException { // Constructs
                                                                                               // the
                                                                                               // circular
                                                                                               // doubly
                                                                                               // linked
       // list with N nodes
       writer = inWriter;
       for (int x = 2; x <= n; x++) {
           addItem(x);
       }
       candidates = n;
   }

   public void addItem(int inPol) { // adds an item to the end of the doubly
                                       // linked list
       Node temp = new Node(inPol);
       last.setNext(temp);
       temp.setPrev(last);
       temp.setNext(first); // Creates a circularly linked list
       last = temp;
       first.setPrev(last);
   }

   public void deleteItem(int pol) { // Deletes an item with the politician
                                       // value of the parameter
       current = first;
       if (first.getNext() != null) {
           while (pol != current.getPol()) {
               current = current.getNext();
           }
           if (current.getPol() == last.getPol()) {
               last = current.getPrev();
               current.getPrev().setNext(first);
           }
           if (current.getPol() == first.getPol()) {
               first = current.getNext();
               current.getNext().setPrev(last);
               ;
           }
           current.getPrev().setNext(current.getNext());
           current.getNext().setPrev(current.getPrev());

       } else {
           first = null;
           last = null;
       }
       candidates -= 1;
   }

   public int getCandidates() {
       return candidates;
   }
   public void closeWriter(){ //Closes the file writer
       writer.close();
   }
   // Carries out the candidate selection process
   public void candidateSelection(int n, int k, int m) {
       Node selectorK, selectorM;
       selectorK = first;
       selectorM = last;
       System.out.println("Selcector k: " + selectorK.getPol());
       System.out.println("Selcector m: " + selectorM.getPol());
       if (m == 0) {
           m = 1;
       }
       if (m > n) {
           m = m % n;
       }
       int counter = 0;
       while (candidates >= 0) {
           counter += 1;
           for (int x = 1; x < k; x++) { // Selector k : Selector k will start
                                           // at
                                           // candidate 1 (first candidate) and
                                           // will move around the circle of
                                           // candidates clockwise counting off
                                           // candidates until it counts k
                                           // candidates and then stop pointing
                                           // at
                                           // the kth candidate.
               selectorK = selectorK.getNext();
           }
           for (int x = n; x > (n-m); x--) {
               selectorM = selectorM.getPrev();
           }
           if (selectorK.getPol() == selectorM.getPol()) {
               System.out.println("Test: " + selectorK.getPol());
               writer.println(selectorK.getPol());
               deleteItem(selectorK.getPol());
           } else {
               System.out.println(counter);
               System.out.println("Test: " + selectorM.getPol() + " " + selectorK.getPol());
               writer.println(selectorM.getPol() + " " + selectorK.getPol());
               deleteItem(selectorK.getPol());
               deleteItem(selectorM.getPol());
           }

       }
   }

}

Node.java

public class Node {
   private int politician;
   protected Node next;
   protected Node previous;
   public Node(int polNum){
       politician = polNum;
      
   }
   public void setNext(Node n){
       next = n;
   }
   public Node getNext(){
       return next;
   }
   public void setPrev(Node n){
       previous = n;
   }
   public Node getPrev(){
       return previous;
   }
   public int getPol(){
       return politician;
   }
}

LinkedListProgram.txt

7 4
3 8
10 1
5 6
2 9
2
13 6
9 11
4 17
16 7
10 15
2 8
5
12
3 1
14
14


input.txt

10 4 3
17 6 4
0 0 0


Related Solutions

Q1) In the implementation of Singly linked list we had an integer variable called size that...
Q1) In the implementation of Singly linked list we had an integer variable called size that keeps track of how many elements in the list. Also, we have a reference “tail” that points to the last node in the list. You are asked to re-implement the concept of singly linked list without using variable size, and without using reference “tail”. a) What are the methods of the main operation of singly linked list that need to be changed? Rewrite them...
Can you make this singular linked list to doubly linked list Create a Doubly Linked List....
Can you make this singular linked list to doubly linked list Create a Doubly Linked List. Use this to create a Sorted Linked List, Use this to create a prioritized list by use. Bring to front those links recently queried. -----link.h------ #ifndef LINK_H #define LINK_H struct Link{ int data; Link *lnkNxt; }; #endif /* LINK_H */ ----main.cpp---- //System Level Libraries #include <iostream> //I/O Library using namespace std; //Libraries compiled under std #include"Link.h" //Global Constants - Science/Math Related //Conversions, Higher Dimensions...
TITLE Updating Accounts Using Doubly Linked List TOPICS Doubly Linked List DESCRIPTION General Write a program...
TITLE Updating Accounts Using Doubly Linked List TOPICS Doubly Linked List DESCRIPTION General Write a program that will update bank accounts stored in a master file using updates from a transaction file. The program will maintain accounts using a doubly linked list. The input data will consist of two text files: a master file and a transaction file. See data in Test section below.  The master file will contain only the current account data. For each account, it will contain account...
How do you implement stack by using linked list? No code just explain it.
How do you implement stack by using linked list? No code just explain it.
You are given a singly linked list. Write a function to find if the linked list...
You are given a singly linked list. Write a function to find if the linked list contains a cycle or not. A linked list may contain a cycle anywhere. A cycle means that some nodes are connected in the linked list. It doesn't necessarily mean that all nodes in the linked list have to be connected in a cycle starting and ending at the head. You may want to examine Floyd's Cycle Detection algorithm. /*This function returns true if given...
(a) Write a stack class that is based on a linked list. It can be just...
(a) Write a stack class that is based on a linked list. It can be just pop(), push(), and anything you need for those methods or testing. (b) Write a queue class that is based on a linked list. As above, it can be just enqueue() and dequeue(), as well as anything you need for those methods or testing. (c) Write some test cases, trying to include edge cases. Why did you choose those tests? Did you get the results...
You just been hired as the general manager of Green Company which is a distributor that...
You just been hired as the general manager of Green Company which is a distributor that has an exclusive franchise to sell a particular product SD. You gathered the following information about the last two years:             2017 2018 Units sold        200,000 160,000 Sales revenue $1,000,000 $800,000 Less cost of goods sold   $700,000 $560,000 Gross margin   $300,000 $240,000 Less G& Adm. expenses     $210,000 $198,000 Operating income            $     90,000 $ 42,000             Required:       Use the provided information to find out how...
Developa case study summary on the company Microsoft, including a general overview of the company, its...
Developa case study summary on the company Microsoft, including a general overview of the company, its external environment, and a list of its current strategies and objectives. Cite references
Case Analysis 3: You are the General Manager at the Bicker, Slaughter, and Lynch Law Firm....
Case Analysis 3: You are the General Manager at the Bicker, Slaughter, and Lynch Law Firm. There is an opportunity to buy out a small law firm that was just started by a young MBA/JD, and you believe the firm can be grown and become a lucrative part of your Firm. With help from your finance leader, you have estimated the following benefit streams for this new division: Before Tax Cash Flow From Operations Year 1 $(149,000) Year 2 $0...
A firm oays an annual dividend and you just missed the annual dividend of 2.50/share you...
A firm oays an annual dividend and you just missed the annual dividend of 2.50/share you expect dividend will grow at 10%/yr for 5yrs abd slow to 3% after. Required rate us 8% what is the following? A. value of D1 in super normal growth B. value of D6 in super normal growth C. value od D6 in perpetuity phase D. what should you be willing to pay today
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT