r/dailyprogrammer • u/fvandepitte 0 0 • Sep 26 '17
[2017-09-26] Challenge #333 [Easy] Packet Assembler
Description
When a message is transmitted over the internet, it is split into multiple packets, each packet is transferred individually, and the packets are reassembled into the original message by the receiver. Because the internet exists in the real world, and because the real world can be messy, packets do not always arrive in the order in which they are sent. For today's challenge, your program must collect packets from stdin, assemble them in the correct order, and print the completed messages to stdout.
The point of reading from stdin is to simulate incoming packets. For the purposes of this challenge, assume there is a potentially unlimited number of packets. Your program should not depend on knowing how many packets there are in total. Simply sorting the input in its entirety would technically work, but defeats the purpose of this exercise.
Input description
Each line of input represents a single packet. Each line will be formatted as X Y Z some_text, where X Y and Z are positive integer and some_text is an arbitrary string. X represents the message ID (ie which message this packet is a part of). Y represents the packet ID (ie the index of this packet in the message) (packets are zero-indexed, so the first packet in a message will have Y=0, the last packet in a message will have Y=Z-1). Z represents the total number of packets in the message.
It is guaranteed that there will be no duplicate packets or message IDs.
Example input
6220 1 10 Because he's the hero Gotham deserves,
6220 9 10
5181 5 7 in time, like tears in rain. Time to die.
6220 3 10 So we'll hunt him.
6220 5 10 Because he's not a hero.
5181 6 7
5181 2 7 shoulder of Orion. I watched C-beams
5181 4 7 Gate. All those moments will be lost
6220 6 10 He's a silent guardian.
5181 3 7 glitter in the dark near the Tannhäuser
6220 7 10 A watchful protector.
5181 1 7 believe. Attack ships on fire off the
6220 0 10 We have to chase him.
5181 0 7 I've seen things you people wouldn't
6220 4 10 Because he can take it.
6220 2 10 but not the one it needs right now.
6220 8 10 A Dark Knight. Output description
Output each completed message, one line per packet. Messages should be outputted in the order in which they are completed.
Example output
5181 0 7 I've seen things you people wouldn't
5181 1 7 believe. Attack ships on fire off the
5181 2 7 shoulder of Orion. I watched C-beams
5181 3 7 glitter in the dark near the Tannhäuser
5181 4 7 Gate. All those moments will be lost
5181 5 7 in time, like tears in rain. Time to die.
5181 6 7
6220 0 10 We have to chase him.
6220 1 10 Because he's the hero Gotham deserves,
6220 2 10 but not the one it needs right now.
6220 3 10 So we'll hunt him.
6220 4 10 Because he can take it.
6220 5 10 Because he's not a hero.
6220 6 10 He's a silent guardian.
6220 7 10 A watchful protector.
6220 8 10 A Dark Knight.
6220 9 10 Challenge input
7469 1 7 believe. Attack ships on fire off the
9949 6 10 He's a silent guardian.
2997 9 19 Force is a pathway to many abilities some
6450 2 11 is a vestige of the vox populi, now vacant, vanished. However, this valorous
6450 10 11
6450 8 11 veers most verbose, so let me simply add that it's my very good honour to meet
6450 5 11 and voracious violation of volition! The only verdict is vengeance; a vendetta
9949 1 10 Because he's the hero Gotham deserves,
6450 1 11 and villain by the vicissitudes of fate. This visage, no mere veneer of vanity,
2997 13 19 he did. Unfortunately, he taught his
9949 8 10 A Dark Knight.
1938 4 17 by the iniquities of the selfish and the
1938 0 17 You read the Bible, Brett? Well there's
2997 0 19 Did you ever hear the tragedy of Darth
2997 1 19 Plagueis the Wise? I thought not. It's not a
1938 8 17 of darkness, for he is truly is brother's
2997 14 19 apprentice everything he knew, then his
6450 3 11 visitation of a bygone vexation stands vivified, and has vowed to vanquish these
1938 12 17 who attempt to poison and destroy my
6450 9 11 you and you may call me V.
7469 2 7 shoulder of Orion. I watched C-beams
2997 10 19 consider to be unnatural. He became so
1938 1 17 this passage I got memorized, sorta fits
2997 5 19 Force to influence the midichlorians to
1938 6 17 in the name of charity and good will,
7469 0 7 I've seen things you people wouldn't
9949 4 10 Because he can take it.
6450 7 11 vindicate the vigilant and the virtuous. Verily, this vichyssoise of verbiage
9949 0 10 We have to chase him.
9949 7 10 A watchful protector.
2997 3 19 legend. Darth Plagueis was a Dark Lord of the
6450 6 11 held as a votive, not in vain, for the value and veracity of such shall one day
2997 8 19 cared about from dying. The dark side of the
1938 10 17 And I will strike down upon thee with
1938 11 17 great vengeance and furious anger those
1938 7 17 shepherds the weak through the valley
1938 2 17 this occasion. Ezekiel 25:17? "The path
2997 18 19
9949 9 10
1938 14 17 the Lord when I lay my vengeance upon
1938 15 17 thee."
1938 9 17 keeper and the finder of lost children.
1938 13 17 brothers. And you will know my name is
9949 2 10 but not the one it needs right now.
2997 16 19 he could have others from death, but not
2997 7 19 dark side that he could even keep the once he
1938 5 17 tyranny of evil men. Blessed is he who,
2997 17 19 himself.
2997 6 19 create life...He had such a knowledge of the
2997 12 19 losing his power. Which eventually, of course,
7469 4 7 Gate. All those moments will be lost
2997 2 19 story the Jedi would tell you. It's a Sith
1938 16 17
2997 4 19 Sith so powerful and so wise, he could use the
1938 3 17 of the righteous man is beset on all sides
2997 11 19 powerful...The only thing he was afraid of was
7469 6 7
2997 15 19 apprentice killed him in his sleep. Ironic,
7469 5 7 in time, like tears in rain. Time to die.
9949 3 10 So we'll hunt him.
7469 3 7 glitter in the dark near the Tannhäuser
6450 4 11 venal and virulent vermin vanguarding vice and vouchsafing the violently vicious
6450 0 11 Voilà! In view, a humble vaudevillian veteran, cast vicariously as both victim
9949 5 10 Because he's not a hero. Finally
Have a good challenge idea?
Consider submitting it to /r/dailyprogrammer_ideas
7
u/Scroph 0 0 Sep 26 '17
C++ solution. I had to compile with -fpermissive because it complained about the const-correctness (or lack thereof) of set insertion, specifically in the parameter of the bool operator< overload of the Packet struct. Can any C++ gurus tell me what's wrong ?
Output :
6
u/TinyBreadBigMouth Sep 26 '17
Python 3
Output:
4
u/[deleted] Sep 26 '17
Here is my solution in Java:
4
u/Pokropow Sep 26 '17
C#
I scan forever for new inputs and print when given message is complete. Maybe does't look great when inputs are given in stdin.
4
u/mochancrimthann Sep 26 '17 edited Sep 26 '17
Javascript / Node
Went for readability over conciseness. Packets will be emitted as an event upon completion.
Ouput
3
u/kidco Sep 26 '17 edited Sep 26 '17
Python 3
Challenge output:
3
u/[deleted] Sep 26 '17
Python 3.6: I'm new to Python. Any tips would be highly appreciated.
Output
3
u/[deleted] Sep 26 '17 edited Sep 27 '17
Ruby
I map packets to a hash according to message ID, and print each message as soon as it's finished. Feedback always welcome.
Edit: made some small improvements
Edit2: simplified code thanks to feedback from /u/mn-haskell-guy. Now I assign packets to an array hashed to the message ID, indexed according to their packet ID.
code:
output:
3
u/ASpueW Sep 27 '17 edited Sep 27 '17
Rust
Output:
3
u/x1729 Sep 30 '17
Perl 6
Reactive object-oriented approach. It's over-engineered and tries to be a bit too cute, but I had fun writing it.
2
u/[deleted] Sep 26 '17
Haskell
Challenge output
2
u/TheBlackCat13 Sep 26 '17
Question about the challenge: What tells us that the input is finished? A blank line, all messages printed, some other "end" signal?
2
u/goonertom Sep 27 '17 edited Sep 27 '17
Perl
First time doing one of these as well as being new to Perl!
Output:
2
u/CEBAnder Sep 29 '17
My C# solution:
2
u/ironboy_ Sep 30 '17 edited Oct 02 '17
JS, Node.js
Focus on keeping the solution short, but sorting messages in the right order (as well as parts of messages).
Output
2
u/lilsimp Oct 08 '17
Here is my c++11 version
any feed back
before i try to use some C++17 features
2
u/schwarzfahrer Nov 10 '17 edited Nov 16 '17
Racket
Forgive me, I'm just learning. My functional/recursive interpretation of u/mochancrimthann 's JavaScript version. Reads from stdin until EOF is reached. Also, prints the messages in order of completion unlike many of the answers in the comments.
Edit: provided a little more concise version
2
u/[deleted] Nov 18 '17
JavaScript
I fucking did it! I'm even somewhat proud of myself. I don't know if my solution is "efficient", but it works and it produces the correct output. Here it is:
the printMsg function could, definitely, be better, but I don't know how and tbh I'm just happy I fixed at all.
Output:
1
u/cheers- Sep 26 '17 edited Sep 26 '17
Javascript (Node)
challenge output: https://pastebin.com/dGmD240S
1
u/JakDrako Sep 26 '17
VB.Net in LinqPad
I had the idea of using a dictionary of message IDs to build the messages as the packets come along... I thought using the new ValueTuples would be a cool way to store the message as it's being built. Of course, them being VALUEtuples, they have value semantics... had to make my counter an array[1] to force reference semantics and actually have my counter work.
Output:
1
u/[deleted] Sep 26 '17 edited Sep 28 '17
Python 3 solution in O(n2log(n)) time
Edit: The above solution is wrong. It outputs the messages in the wrong order.
Attempt #2 (same computational complexity)
1
u/TheBlackCat13 Sep 26 '17 edited Sep 26 '17
Python3 solution. I avoided sorting as suggested. Since the OP doesn't say what constitutes the end of the input stream, I stop reading inputs when all messages are complete. It would be trivially easy to change so that it ends on a blank line or some other condition. I went for clarity rather than compactness, so there are some areas where I could reduce the number of lines:
And a version that is easier to test that uses a single long string called
lines:And the solution:
1
u/octolanceae Sep 26 '17 edited Sep 26 '17
Python3
Output:
EDIT: cleaned up parse_packet as it contained a few lines of unnecessary code. Other Edit: Didn't rstrip msg_id, so msg_log key had all of that padding.
Note: I shouldn't do this while I am at work. It is making me write sloppy code as I am trying to do too many things at once...
1
u/jacobmcnamee Sep 26 '17
C
Uses a linked list to keep track of pending messages and another nested linked list for each message to keep track of received packets.
https://gist.github.com/jacobmcnamee/94a34f812f343dc85f6b74b26669f946
1
u/popillol Sep 26 '17
Go / Golang Playground Link. Prints out finished messages once the last item is received. Can be modified to use stdin by changing the source of the
bufio.NewScanner, but that doesn't work on the playground. Can also print out any unfinished packets1
u/[deleted] Sep 27 '17 edited Sep 27 '17
This is my first time using C#. I made some variants in the code, this can be done a lot faster.
If someone has any comments, please post them.
I have changed my Program class. Using my own Dictionary extension loosely based on AddOrUpdate from ConcurrentDictionary.
1
u/[deleted] Sep 27 '17
Go solution. Prints packets as they are completed
1
u/LOOKITSADAM 0 0 Sep 27 '17
Java 'one liner':
1
u/quantum_paradoxx Sep 27 '17
Here is my solution in Java:
Output:
1
u/[deleted] Sep 27 '17
Node.js
I stored the input into a file called 'input.txt' because copy pasting into git bash was messy.
1
u/darkshady1 Sep 27 '17
Python 3 New to Python/dailyprogrammer. Any tips appreciated.
Output
1
u/Herpuzderpuz Sep 27 '17
Python 3.6,
Not very pretty but it works
1
u/[deleted] Sep 27 '17 edited Sep 27 '17
Feel like my code might be "over-optimised" Java
Output:
1
u/Lawson470189 Sep 27 '17
Python3 with Regex
1
u/PoetOfShadows Sep 27 '17
Kotlin
1
u/TKraus Sep 27 '17
Java
also detects for missing packets for each message
import java.util.; import java.io.;
public class packetAssembly { public static void main(String[] args) { try { Scanner in = new Scanner(System.in); String str = in.nextLine(); String[] line; Double mID, pID; Integer pSize; String message; Map<Double, String> out = new TreeMap<>(); Map<Double, Integer> mStatus = new TreeMap<>(); while (!str.equals("")) { line = str.split("\s+"); mID = Double.parseDouble(line[0]); pID = Double.parseDouble(line[1]); pSize = Integer.parseInt(line[2]); message = String.join(" ", (Arrays.copyOfRange(line, 3, line.length))); Integer status = mStatus.get(mID); if (status != null) { mStatus.put(mID, status-1); }else { mStatus.put(mID, pSize-1); } if (pID != 0) { out.put(mID + (pID/100), message); }else { out.put(mID, message); } str = in.nextLine(); } in.close(); PrintWriter outFile = new PrintWriter(new FileWriter(new File("output.txt"))); for (Map.Entry<Double, String> entry : out.entrySet()) { double mplusp = Math.floor(entry.getKey()); String strout = entry.getValue(); Integer mstat = mStatus.get(mplusp); if (mstat != null) { if (mstat == 0) { strout = String.format("Message %d:\n", (long)mplusp) + strout; }else if (mstat == 1) { strout = String.format("Message %d (missing a packet):\n", (long)mplusp) + strout; }else { strout = String.format("Message %d (missing %d packets):\n", (long)mplusp, mstat) + strout; } mStatus.remove(mplusp); } outFile.println(strout); } outFile.close(); }catch (IOException e) { System.out.println(e.getMessage()); }catch (InputMismatchException e) { System.out.println(e.getMessage()); }catch (NumberFormatException e) { System.out.println("Packets must be entered in the following line format:\nmessage ID | packet index | # of packets/message | message string"); } } }
1
u/sober_coder Sep 27 '17 edited Sep 28 '17
Java
A new message instance is created and stored in a hash table if it doesn't already exist. For each incoming packet, a method is called on the message instance corresponding to the packet's message ID. When we have received all the messages, we format the string, and print out the entire message.
1
u/chunes 1 2 Sep 28 '17
Factor
Challenge output:
This problem was a good excuse to finally learn Factor's object model. Thanks, OP!
This program processes packets as they come and outputs messages in the order they are completed, rather than sorted by message id. I'm not sure why the special characters turned out like that. I copied the output from windows cmd. If anyone has any ideas let me know.
1
u/Herpuzderpuz Sep 28 '17
OOP solution Java
1
u/A-Grey-World Sep 28 '17
https://repl.it/LlK0/3
Javascript. MessageReader class takes a callback to fire when a message is completed, then is passed each new packet segment with "processPacket". It only holds messages in memory until they are completed.
1
u/Jean-Alphonse 1 0 Sep 28 '17
Javascript ES6
1
u/uzzgae Sep 28 '17
Clojure
Interesting solutions with the lower level languages!
1
u/AtoneBC Sep 29 '17 edited Sep 29 '17
Lua
First time trying one from this sub. I still have lot to learn. I skimmed the string sections of PIL for a little and came up with this, but I'm sure there's a cleaner way to do it with pattern matching or some string functions I'm unaware of.
1
u/nicomatic Sep 29 '17
Javascript (ES6)
you can run this script directly in your console - works with Chrome and Firefox
1
u/Working-M4n Sep 29 '17
JavaScript
Live answer on CodePen
All feedback welcome, thank you!
1
u/Darkmakers Sep 29 '17
C# I load the lines from a text file, There is an issue with some of the characters being shown correctly.
Output:
1
u/--RickyDiculous-- Oct 01 '17 edited Oct 01 '17
C++ First submission (open to feedback), new to C++ as a language, and to be fair I took a lot of reference from /u/SourVenom 's solution on github
Output:
1
u/insolent_bystander Oct 02 '17
C Here is my solution. Feedback is welcome.
1
u/hyper_coder Oct 02 '17
1
u/SusuKacangSoya Oct 03 '17 edited Oct 03 '17
Java Terribly written, and terribly inefficient... but technically works.
Output:
Does not format output like challenge's example output; does not retain whitespaces.
I admit, I do not really understand what the challenge meant by 'message completion order'... Based on others' solutions, though, I think this abides by that rule.
1
u/victiln2137 Oct 03 '17 edited Oct 03 '17
My first programming challenge here! Easy one I think. Did so that it displays the whole message after it is delivered, then deletes it from the dictionary, so it won't overflow if there are a lot of packages. Though it is not necessary of course. Python3.
1
u/[deleted] Oct 04 '17
My Java solution
1
u/glacialOwl Oct 05 '17 edited Oct 05 '17
C++
Just started getting into solving problems using C++, so please, any advice / suggestion / anything is really welcome! I want to learn ways to improve :) I've mostly done Java before, especially for this kind of "toy" problems.
Message.h
Message.cpp
main.cpp
1
u/kubunto Oct 06 '17 edited Oct 06 '17
Python 2 (Edit to make code shorter and more concise)
1
u/[deleted] Oct 06 '17 edited Oct 06 '17
Python3
Yes I complicate things a lot. :x
1
u/lgastako Oct 07 '17
Haskell (with Pipes)
1
u/German105 Oct 07 '17
Python 3
https://github.com/German105/dailyprogrammer/tree/master/easy/333
Challenge output
1
u/Zambito1 Oct 07 '17
Scala
Challenge output:
1
u/line_over Oct 08 '17
Pyhton3
1
u/joey_dubs Oct 09 '17 edited Oct 09 '17
Java solution! I tried to keep it object oriented instead of just trying to solve it using as few lines as possible for reusability. Thoughts? Also my first time doing one of these projects and posting here. I want to start doing more of these to get some good practice outside of school. Thanks!
1
u/unknown_guest17 Oct 13 '17 edited Oct 13 '17
Here is my Python 3.6 solution
The solution printed out is
1
u/BlasphemousJoshua Oct 13 '17 edited Oct 13 '17
Swift
1
u/pehnquihn Oct 14 '17
My golf-like python3 solution, got it down to 2 lines not including the shebang: https://github.com/pehnquihn/dailyprogrammer/blob/master/solutions/333E/main.py
1
u/ribenaboy15 Oct 14 '17
Java 8 using Comparable interface and TreeSet — not sure if it implicitly counts as sorting, but I thought it was a neat way.
1
u/[deleted] Oct 15 '17
Python3
1
u/dr4kun Nov 10 '17
POWERSHELL (USING REGEX)
1
u/osopolardefuego Nov 21 '17
JavaScript: I didn't finish it, but this is a good start. Thinking about putting this into a for loop and pushing the values into an array and then sorting it.
1
u/chemistrybird Dec 05 '17
Python 3
1
u/Tydra_Ardit Dec 06 '17
I'm fairly new to programming, so any feedback is welcome. C++:
1
u/keto166 Feb 17 '18
First Python 3 challenge
Output
1
u/J354 Sep 26 '17
1 horrendous line of Python:
1
u/Godspiral 3 3 Sep 26 '17
in J, with input on clipboard
1
u/Specter_Terrasbane Sep 26 '17
Python 2
Can be run interactively or given a string where each line is a packet.
0
u/thorwing Sep 26 '17
Java 8
Java has a really nice lambda based comparator ever since java 8. Even though an intermediate package class is not necessarily needed, I use it for readability.
0
u/[deleted] Sep 26 '17
[deleted] — view deleted comment
0
u/[deleted] Sep 26 '17
[deleted] — view deleted comment
0
u/[deleted] Sep 27 '17
[deleted] — view deleted comment
0
u/[deleted] Sep 26 '17
[deleted] — view deleted comment
0
u/[deleted] Sep 26 '17
[deleted] — view deleted comment
0
u/[deleted] Sep 27 '17
[deleted] — view deleted comment
0
u/[deleted] Sep 30 '17
[deleted] — view deleted comment
0
u/[deleted] Oct 05 '17
[deleted] — view deleted comment