Josh Figgles
Josh Figgles

Reputation: 11

ArrayList combination to one String

Updated:

package packet;

import java.util.ArrayList;   //java library implementation of List interface
import java.util.Arrays;
import java.util.List;            //java library the List interface
import java.util.Random;    //for random number generator
import java.io.FileNotFoundException;         //for opening a file
import java.io.PrintWriter;                              //for writing to a file

public class Message
{
private String message;
private int packetLength;
private List<Packet> dividedMessage;    //use java library java.util.List 
private boolean messageSent;
private Random generator;                      //use java library java.util.Random


public Message(String theMessage, int thePacketLength)
       {
        message = theMessage;
        packetLength = thePacketLength;
        receiveInFile(message);


       }

public void send()
{          // divide the message into Packet and store the packets in the list   
                  // dividedMessage
    dividedMessage = new ArrayList<Packet>();

    List<String> items = Arrays.asList(message.split("\\s*,\\s*"));
    int sequenceNumber = packetLength;
    String nextPiece = message;
                //This is the line of code to create a Packet object using a sequence   
                   //number and a string (represent part of the message)
    Packet nextPacket = new Packet(sequenceNumber, nextPiece);
    dividedMessage.add(nextPacket);

        }
/** Simulates the receipt of the packets of a message. The packets
         are not in any particular order and are written to a text file.
            @param fileName  a string that names the file to be created and the    
                                           packets are written to the file.
            @return true if the packets are received, or
                          false if the message was never sent or the file
                          cannot be created */


public boolean receiveInFile(String fileName)
{

    String[] items = message.split(" ");
    int numberOfPackets = items.length;
   dividedMessage = Arrays.asList(message.split(","));

    shuffle(dividedMessage, numberOfPackets);
   // container.send();

    return messageSent;

       }
public String toString()
       {
        return message;

       }
private void shuffle (List<Packet>  packetList, int  numberOfPackets)
{
        if (numberOfPackets > 1)
        {
               // swap packet at index numberOfPackets - 1 and a random index
               Packet temp = packetList.get(numberOfPackets - 1);
               int randomIndex = Math.abs(generator.nextInt()) 
               %numberOfPackets;
               packetList.set(numberOfPackets - 1, packetList.get(randomIndex));
               packetList.set(randomIndex, temp);
               shuffle(packetList, numberOfPackets - 1);
        }  // end if
      }  // end Shuffle
}// end class Message

Original:

I am making a sample program with the intent of sending packets out of order and reorders then outputs the packets in a full string. i have the ordering part working fine so i did not include them, i do not seem to know where to go next from here, these classes should be taking the reordered packets and make them into one string. any help is awesome!

public class Packet implements Comparable<Packet>
{
    private int    sequence;      //sequence number of the packet
    private String message;    //a part of the message represented by the packet
    public Packet(int sequenceNumber, String nextPiece) {
        setSequence(sequenceNumber);
        setMessage(nextPiece);
        Message test = new Message(message, sequence);

    }
    @Override
    public int compareTo(Packet o) {
        int comparedSize = o.sequence;
        if (this.sequence > comparedSize) {
            return 1;
        } else if (this.sequence == comparedSize) {
            return 0;
        } else {
            return -1;
        }

    }
    public String toString() {
        return message;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public int getSequence() {
        return sequence;
    }
    public void setSequence(int sequence) {
        this.sequence = sequence;
    }

    //Implement constructor and other methods as necessary
}

import java.util.ArrayList;   //java library implementation of List interface
import java.util.List;            //java library the List interface
import java.util.Random;    //for random number generator
import java.io.FileNotFoundException;         //for opening a file
import java.io.PrintWriter;                              //for writing to a file

public class Message
{
    private String message;
    private int packetLength;
    private List<Packet> dividedMessage;    //use java library java.util.List
    private boolean messageSent;
    private Random generator;                      //use java library java.util.Random

    /**implement constructor  */
    public Message(String theMessage, int thePacketLength)
    {
        message = theMessage;
        packetLength = thePacketLength;

    }
    /** Sends this message as a sequence of packets. */
    public void send()
    {          // divide the message into Packet and store the packets in the list
        // dividedMessage
        dividedMessage = new ArrayList<Packet>();
        int sequenceNumber = 0;
        String nextPiece = null;
        //This is the line of code to create a Packet object using a sequence
        //number and a string (represent part of the message)
        Packet nextPacket = new Packet(sequenceNumber, nextPiece);

    }
    /** Simulates the receipt of the packets of a message. The packets
     are not in any particular order and are written to a text file.
     @param fileName  a string that names the file to be created and the
     packets are written to the file.
     @return true if the packets are received, or
     false if the message was never sent or the file
     cannot be created
     */
    public boolean receiveInFile(String fileName)
    {

        // shuffle the packets to simulate their arrival order
        int numberOfPackets = 0;
        shuffle(dividedMessage, numberOfPackets);
        return messageSent;

    }
    public String toString()
    {
        return message;

    }
    private void shuffle (List<Packet>  packetList, int  numberOfPackets)
    {
        if (numberOfPackets > 1)
        {
            // swap packet at index numberOfPackets - 1 and a random index
            Packet temp = packetList.get(numberOfPackets - 1);
            int randomIndex = Math.abs(generator.nextInt())
                              %numberOfPackets;
            packetList.set(numberOfPackets - 1, packetList.get(randomIndex));
            packetList.set(randomIndex, temp);
            shuffle(packetList, numberOfPackets - 1);
        }  // end if
    }  // end Shuffle
}// end class Message

The original message is "Meet me at 6 o'clock in the union."

The received packets of the message: 1 Mee 3 e a 6 clo 5 o' 4 t 6 2 t m 11 ion 7 ck 8 in 10 un 9 the

The received message is "Meet me at 6 o'clock in the union"

Upvotes: 0

Views: 233

Answers (3)

tonychow0929
tonychow0929

Reputation: 466

Here I can give you some hints, but try to write the code yourself.

First, use split(" ") to split the String 1 Mee 3 e a 6 clo 5 o' 4 t 6 2 t m 11 ion 7 ck 8 in 10 un 9 the into a String[].

Assume that numbers and string chunks appear alternately, put them into a Map<Integer, String>. You may use a TreeMap if you don't want further sorting.

Finally, iterate through the values in the Map. Add them to a StringBuilder and finally use toString() to obtain a String instance, which should be the result.

Edit: if Packet implements Comparable<Packet>, a TreeSet will do all the sorting for you (because there won't be any equal Packet). See the following code (much simplified and condensed into a single java file for convenience).

import java.util.*;
import java.io.FileNotFoundException;         //for opening a file
import java.io.PrintWriter;                              //for writing to a file

public class Message
{
    private String message;
    private int packetLength;
    private List<Packet> dividedMessage;    //use java library java.util.List 
    private boolean messageSent;
    private Random generator;                      //use java library java.util.Random
    public Message(String theMessage, int thePacketLength)
    {
        message = theMessage;
        packetLength = thePacketLength;
        //receiveInFile(message);
    }

    public static void main(String[] args)
    {
        ArrayList<Packet> list = new ArrayList<>();
        list.add(new Packet(1, "Mee"));
        list.add(new Packet(3, "e a"));
        list.add(new Packet(6, "clo"));
        list.add(new Packet(5, "o\'"));
        list.add(new Packet(4, "t 6 "));
        list.add(new Packet(2, "t m"));
        list.add(new Packet(11, "ion"));
        list.add(new Packet(7, "ck "));
        list.add(new Packet(8, "in "));
        list.add(new Packet(10, "un"));
        list.add(new Packet(9, "the "));
        Collections.shuffle(list);
        /*
         * now shuffled
         * read message
         */
        TreeSet<Packet> set = new TreeSet<>(list);
        StringBuilder builder = new StringBuilder();
        for (Packet p: set)
        {
            builder.append(p.getMessage());
        }
        System.out.println(builder.toString());
    }

    public String toString()
    {
        return message;
    }

    static class Packet implements Comparable<Packet>
    {
        private int    sequence;   //sequence number of the packet
        private String message;    //a part of the message represented by the packet
        public Packet(int sequenceNumber, String nextPiece) {
            setSequence(sequenceNumber);
            setMessage(nextPiece);
            Message test = new Message(message, sequence);
        }
        @Override
        public int compareTo(Packet o) {
            int comparedSize = o.sequence;
            if (this.sequence > comparedSize) {
                return 1;
            } else if (this.sequence == comparedSize) {
                return 0;
            } else {
                return -1;
            }

        }
        public String toString() {
            return message;
        }
        public String getMessage() {
            return message;
        }
        public void setMessage(String message) {
            this.message = message;
        }
        public int getSequence() {
            return sequence;
        }
        public void setSequence(int sequence) {
            this.sequence = sequence;
        }
    }
}

IMO, a Set is more convenient than a List is there are no equal elements. Use a HashSet if the order is unimportant, a LinkedHashSet if the order must be unaltered, and a TreeSet if natural ordering is required.

Upvotes: 0

akhil_mittal
akhil_mittal

Reputation: 24157

I tried the following code and it works fine:

public static void main(String[] args) {
    List<Packet> dividedMessage = new ArrayList<>();
    dividedMessage.add(new Packet(1, "Mee"));
    dividedMessage.add(new Packet(2, "t m"));
    dividedMessage.add(new Packet(3, "e a"));
    dividedMessage.add(new Packet(6, "clo"));
    dividedMessage.add(new Packet(5, "o'"));
    dividedMessage.add(new Packet(4, "t 6 "));
    dividedMessage.add(new Packet(11, "ion"));
    dividedMessage.add(new Packet(7, "ck"));
    dividedMessage.add(new Packet(8, " in"));
    dividedMessage.add(new Packet(10, " un"));
    dividedMessage.add(new Packet(9, " the"));

    Collections.sort(dividedMessage);
    String originalMessage = "";
    for (Packet packet : dividedMessage)
    {
        originalMessage += packet.getMessage();
    }
    System.out.println(originalMessage);
}

I hope this is what you want. Output is: Meet me at 6 o'clock in the union

If you have lots of packets then performance may be a concern and you can use StringBuilder:

StringBuilder sb = new StringBuilder();
for (Packet packet : dividedMessage)
{
    sb.append(packet.getMessage());
}

Upvotes: 0

Aakash
Aakash

Reputation: 2109

Why not sort the ArrayList of Packets itself, since you have implemented Comparable interface? You can

  1. Sort the List of Packets. You can use Collections.sort() for this.
  2. Iterate over the sorted list, get next item from list and append it's nextPiece to a String.

You should have the proper string after this.

Upvotes: 1

Related Questions