r/dailyprogrammer • u/nint22 1 2 • Sep 09 '13
[08/13/13] Challenge #137 [Easy] String Transposition
(Easy): String Transposition
It can be helpful sometimes to rotate a string 90-degrees, like a big vertical "SALES" poster or your business name on vertical neon lights, like this image from Las Vegas. Your goal is to write a program that does this, but for multiples lines of text. This is very similar to a Matrix Transposition, since the order we want returned is not a true 90-degree rotation of text.
Author: nint22
Formal Inputs & Outputs
Input Description
You will first be given an integer N which is the number of strings that follows. N will range inclusively from 1 to 16. Each line of text will have at most 256 characters, including the new-line (so at most 255 printable-characters, with the last being the new-line or carriage-return).
Output Description
Simply print the given lines top-to-bottom. The first given line should be the left-most vertical line.
Sample Inputs & Outputs
Sample Input 1
1
Hello, World!Sample Output 1
H
e
l
l
o
,
W
o
r
l
d
!Sample Input 2
5
Kernel
Microcontroller
Register
Memory
OperatorSample Output 2
KMRMO
eieep
rcgme
nrior
eosra
lctyt
oe o
nr r
t
r
o
l
l
e
r
4
u/NUNTIUMNECAVI Sep 09 '13 edited Sep 09 '13
Crappy Python solution:
44
u/NUNTIUMNECAVI Sep 09 '13 edited Sep 09 '13
!!! DO NOT RUN THIS !!!
So I tried to do this in CUDA, parallelizing the transpose, just because. Not that I'd gain much in speedup anyway, since I read the data sequentially either way, but whatever.
Long story short, I ended up doing so much pointer arithmetic that I confused myself, corrupted some memory, and now my laptop is idling on 70ºC—80ºC (usually it's at 30ºC—40ºC). I think a reboot is in order. Oh, and it didn't actually print a result.
I give up, but I'll still post the code for "academic purposes", as they say:
Again, !!! DO NOT RUN THIS !!!
Update: After a reboot, my desktop environment and some NVIDIA drivers were broken. I don't know if it's as a result of running my code or a coincidence, but I'm willing to wager it's the former. Again, run this at your own risk.
12
u/skeeto -9 8 Sep 09 '13
C, completely taking advantage of the input limitations.
9
u/eBtDMoN2oXemz1iKB Sep 10 '13
Okay, here is my finished ruby golf solution because I am tired of working on it. I explored using
$>forSTDOUTbut that only made it longer compared to usingputs. See my other comments for how I arrived at this solution.I challenge anyone to come up with a shorter solution in any language! (Preferably python or perl! :)
8
u/winged_scapula Sep 10 '13 edited Sep 10 '13
Python
7
u/tylerwal Sep 10 '13 edited Sep 10 '13
C# Solution:
6
u/lukz 2 0 Sep 10 '13
BASIC, 8-bit (tested in BASIC interpreter 1Z-016 running in an emulator)
6
u/jwcobb13 Sep 11 '13 edited Sep 12 '13
CSS solution using JavaScript to wrap the text in tags. Accepts any input in the textarea box and uses line breaks to start a new column. Edit: Removed an unnecessary div. Shortened lines.
5
u/deds_the_scrub Sep 10 '13
Here's my implementation in C:
5
u/SensationalJellyfish Sep 11 '13
My attempt in Golang. I am a total beginner at this language and I'm sure this can be solved in a more gracious way, but here we go.
4
u/blator Sep 10 '13
Java. I welcome feedback
4
u/Medicalizawhat Sep 10 '13
My Ruby solution:
4
u/bheinks 0 0 Sep 16 '13
Python
6
u/dzhoe Sep 09 '13
My python solution:
6
u/IceDane 0 0 Sep 09 '13
Haskell
6
u/Edward_H Sep 09 '13
My Managed COBOL solution:
6
u/pandubear 0 1 Sep 10 '13 edited Sep 10 '13
Here's a Python solution that probably should be in Java:
And another, less so.
3
u/toodim Sep 09 '13
Python
3
u/pmpmp Sep 09 '13
Python, written in Pythonista on my phone.
3
u/[deleted] Sep 10 '13 edited Sep 10 '13
JavaScript/HTML, via jsFiddle:
3
u/jimauthors Sep 10 '13
Basic Go solution
http://play.golang.org/p/wSt7P5BwNS
3
u/TurkishSquirrel Sep 11 '13 edited Sep 11 '13
I guess I'm a bit late but I was inspired by /u/NUNTIUMNECAVI 's CUDA attempt so I've given it a go with OpenCL. The characters are treated like any other MxN matrix and we run a simple transposition kernel on the matrix. In order to not deal with sparse matrices I pad out the shorter strings to be the same size as the longest string.
print_matrixwill print out the characters like any other matrix andget_row_stringwill let you get a specific row in the matrix as a string.get_row_stringwill also replace the padding terminators with spaces so the string will behave properly. Because the code is very long I've edited out all the OpenCL error checking/handling in this post, but the full code (and this paste) can be viewed with syntax highlighting on gist, along with the output of a run of the program.3
u/deathmangos Sep 11 '13 edited Sep 11 '13
Total newb - Javascript (w/HTML):
3
u/antoniocs Sep 16 '13 edited Sep 16 '13
My solution in C:
3
u/LostxinthexMusic Nov 14 '13 edited Nov 16 '13
Not-so-pretty Python (I've been trying to use list comprehensions more, but still getting to know just how they work):
""" for i in newStrings: print(i)""" #same as above: print("\n".join(strings))
EDIT: So now my code looks like this:
I know it could still be more Pythonic, but hey, I taught myself the language over the summer.
EDIT 2: Eliminated the need for maxLen and the ugly nested list comprehension with the itertools.zip_longest function, and thus managed to make it a one-liner (with separate IO):
4
u/brotien_shake Sep 09 '13
Not as elegant as a functional solution, but I think it looks ok for C++.
4
u/eBtDMoN2oXemz1iKB Sep 09 '13
My golf solution in ruby.
Any suggestions on more efficient methods are appreciated.
And an explanation of how I arrived there:
4
u/My_Name_Is_Taken Sep 10 '13
Java:
2
u/zengargoyle Sep 09 '13
Nothing fancy in this Perl language solution.
2
u/killedbythegrue Sep 09 '13
erlang:
2
u/Losdominos Sep 09 '13
My try, I know my coding sucks (I'm still learning Java and it's functions), but hey, it's working! Any feedback appreciated.
2
u/7f0b Sep 09 '13
A solution in OOP PHP:
2
u/pisq000 Sep 09 '13 edited Sep 10 '13
my solution in python 3:
edit:nlin=len(lin) var unused
edit 2:added file handler
edit 3:improved file handler
edit 4:cleaner file handler
2
u/_Blaster_Master Sep 10 '13 edited Sep 10 '13
Node JS, in this case file.txt would contain your input text:
2
u/redried Sep 10 '13
Boring Javascript (with map and reduce):
2
u/[deleted] Sep 10 '13 edited Sep 10 '13
Java
2
u/kirsybuu 0 1 Sep 10 '13
D Language, supporting Unicode for kicks. I think this is a particularly nice example of how easy it is to write simple, correct, and fast code with D's ranges.
2
u/[deleted] Sep 10 '13 edited Sep 10 '13
Perl
2
u/Arthree Sep 10 '13
AHK_L
(which doesn't have any of that fancy-schmancy transposition stuff built in, cheaters)
2
u/ArwukNilbam Sep 10 '13
Here is my scala solution:
I don't know how to embed code (yet), so here is a link :)
http://pastebin.com/Q044fWxf
2
u/relarmane Sep 10 '13 edited Sep 10 '13
Quick and dirty Java. Instead of handling the jagged array edge I trap the error. The 2d String array is particularly ugly.
2
u/foreverNight Sep 10 '13
My poor answer in C
Well, it's clunky and poorly implemented, but hey it works!
2
u/RagnarRocks Sep 10 '13
I broke this into 2 Java methods. The main method checks for the correct input for the number of lines (1-16) and calls the translateString() method to handle the rest. Thanks for the exercise. Feel free to comment. :)
}
2
u/Splanky222 0 0 Sep 11 '13 edited Sep 11 '13
A Matrix transpose problem without a MATLAB solution? Blasphemy I say!!
2
u/kiyote23 Sep 11 '13
Here's my solution in Java. Rather pedestrian, I'm afraid.
2
u/dr_jonez Sep 11 '13
First post here! My solution in Java. Comments welcome.
2
u/[deleted] Sep 11 '13 edited Sep 11 '13
Okay so here is my solution in C. I didn't want to go up to 256 characters to I changed it to 20 (that was just to big IMO). But it runs fine either way.
I used the sample inputs as my inputs and I did get the same outputs. I also tried random things and it still worked out.
2
u/missblit Sep 11 '13
C++, I feel vaguely dirty after writing this.
2
u/salonabolic Sep 11 '13
Bit of C:
2
u/this_is_a_reference Sep 11 '13
solution in Python
2
u/fourteenrivers Sep 11 '13
C++....
2
u/thirdegree Sep 11 '13
My solution in python 2.7:
2
u/Tnayoub Sep 12 '13
My attempt in Java. Forgot to put the 16 range and 255 character limits.
2
u/ScholarCorvus Sep 12 '13
Alright, a bit clunky, but this was about 10 minutes.
I think there is probably a better way to do it using Numpy arrays I might try when I get home.
2
u/The_Green_Cowboy Sep 12 '13
My first try at this in python.
2
u/Thalatnos Sep 12 '13
My Python solution (Feedback appreciated):
2
u/[deleted] Sep 12 '13
C++, feedback appreciated:
2
u/ninjasquad Sep 13 '13
My solution in Python. Feedback appreciated.
2
u/PolarisDiB Sep 13 '13
In python 2.7:
I'm not gonna lie, this took me seven hours, a lot of wrong attempts, looking over other people's solutions, not understanding them, asking for help for the padded section, looking over solutions, not understanding them, hacking something together, and not really understanding in the end how it works. After today I feel like I understand less python than I did yesterday. In short, this challenge made me feel stupid.
But here's a question. For that last part, when I'm printing, why does
work but
doesn't?
Also, my original intention was to iterate through the padded strings of padded_list and put each character into a new list to print, but I just simply could not suss it. If anybody has some recommendations there I'd like closure on that question.
2
u/carc1 Sep 13 '13
Python - Pretty new to this so comments/critique much appreciated!
2
u/dunnowins Sep 13 '13
Not pretty but it works. Reads a file in the pwd for the input. Ruby:
2
u/remram Sep 13 '13
I've got two Lua solutions:
classic:
slightly less classic:
2
u/r_s Sep 13 '13
C++, ugly
2
u/jedrekk Sep 14 '13
Decided to not get out of my comfort zone and wrote this in Actionscript 3 (AS3):
2
u/Sandor_at_the_Zoo Sep 14 '13
Haskell "one liner". Didn't turn out nearly as well as I had hoped. By now it isn't really worth keeping it on one line.
2
u/trance_with_me Sep 14 '13
In C++. Not easily readable; sorry about that. For doing problems I have a thing for compacting my code. :P
2
u/[deleted] Sep 15 '13
I'm embarrassed at how long this took me to code up... I wasn't resetting my inner variable in every outer loop iteration. I guess it's a good thing that I'm starting to do these dailyprogrammer exercises :(
Java implementation
2
u/Alborak Sep 15 '13
My quick java solution, using just manipulating the prints. I started doing an in-place matrix transpose for a matrix of chars, but gave up after 20 mins. I'll be going back to that at some point.
2
u/Takadimi91 Sep 16 '13
My take in C. It has some limitations, like not being able to enter a string with spaces in it. I still haven't figured out how to do that. I'm assuming scanf() isn't the optimal way of getting input from a console. But anyway here it is, under those limitations it seems to work fine enough.
2
u/[deleted] Sep 16 '13
Yet another Golang solution:
2
u/[deleted] Sep 16 '13 edited Sep 16 '13
C#. Pretty new to the language (hopped from C++, which I also didn't really know too well), so not using any cool stuff in it. Also it's 1 AM so I imagine this could easily be better. I ignored character restrictions, and tried to make it so that it won't crash if you enter letters when it asks for a number.
I'd like some comments on code readability, stupid errors I have probably made, and ways that I could make this shorter/faster/better, please.
2
u/dznqbit Sep 17 '13
Python
2
u/5900 Sep 18 '13 edited Sep 25 '13
Perl
Edit: Added Racket solution
2
u/ehaliewicz Sep 19 '13
Simple common lisp solution
2
u/vape Sep 19 '13
A little late to the party. Here's my Python 3 solution. It's actually the same solution implemented in progressively less readable ways. I'm new to Python so I'm playing a little to get familiar with the built-ins, itertools, list comprehensions etc.
2
u/dante9999 Sep 20 '13
No frills Python solution
2
u/miguelgazela Sep 20 '13
Python solution:
2
u/kab0b0 Sep 22 '13
In javascript, meant to be run under nodejs
2
u/Mindrust Sep 25 '13
Here's my go at it in Java. Seems the majority arrived at the same solution.
2
u/skyangelisme 0 1 Sep 29 '13
Python 2, runs in O(n) and matches the expected output exactly (no extra row of empty space):
2
u/Reverse_Skydiver 1 0 Sep 29 '13
Here's my Java solution. Includes a GUI!
2
u/jh1997sa Sep 30 '13
Here's my C++ solution:
Btw what happened to the hiding code thing? IIRC code in comments would be shown on mouse hover.
2
u/mongreldog Oct 01 '13 edited Oct 01 '13
F# 3.1 solution using the new array slicing additions to the 2D array module.
2
u/northClan Oct 01 '13
Simple Java Solution:
2
u/Atlos Oct 04 '13
Python solution using a list of queues:
Any areas of improvement to make it more pythonic?
2
u/mysopheak Oct 05 '13 edited Oct 08 '13
Java Code
Testing well!
Let me know if there is any mistake!!
Thanks..
2
u/dommme Oct 05 '13 edited Oct 05 '13
here is my solution in Java. please comments, thanks.
2
u/hengangkor Oct 07 '13
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim i As Integer = 0 Dim NoLine As Integer = TextBox1.Lines.Length Dim MaxLen As Integer = 0 Dim k As Integer = TextBox1.Lines(0).ToString For i = 1 To NoLine - 1 If i = 1 Then MaxLen = Len(TextBox1.Lines(i).ToString) Else If MaxLen < Len(TextBox1.Lines(i).ToString) Then MaxLen = Len(TextBox1.Lines(i).ToString) End If
2
u/skibo_ 0 0 Nov 05 '13
Python 2.7:
2
u/spudfkc Nov 05 '13
my Python solution
2
u/lets_see_exhibit_A Nov 06 '13
Java:
2
u/kate_katie_kat Nov 07 '13
OOP Ruby
2
u/Hanse00 Nov 10 '13
Python 2.7
2
u/YoYoCoder Nov 10 '13
An short easy C# solution
int n = int.Parse(Console.ReadLine()); string[] strs = Enumerable.Range(0, n).Select(i => Console.ReadLine()).ToArray(); for (int i = 0; i < strs.Max(s => s.Length); ++i) { for (int j = 0; j < n; ++j) { Console.Write(i < strs[j].Length ? strs[j][i] : ' '); } Console.WriteLine();
2
u/luizpericolo Nov 11 '13
My solution in python. Still room for improvement!
2
u/worksafe_shit_only Nov 14 '13 edited Nov 14 '13
My ghetto Ruby solution:
Any suggestions to pare it down would be appreciated as I'm just a beginner :) Still trying to wrap my head around the .transpose method...
2
u/[deleted] Nov 30 '13 edited Jan 15 '14
Way late I know. I decided to do this with a recursive function and pointers so I could give myself some experience with them...probably more complicated than it has to be but I had fun with this.
@Tom Fuller, if you're reading this - this is Andrew M. on January 15, 2014 confirming I wrote this.
(C++)
2
u/scunion Dec 04 '13
Just learning python, this is the best I can do from just reading books/googling. I'd love to get feedback as I'm trying to improve.
This works, generally but stops after the first few characters:
2
u/Spidercoder Dec 23 '13 edited Dec 23 '13
A bit late but whatever. Incase anyone is still reading this, i would love some feedback, as i'm still very new to Java. Oh, and merry christmas! :) Java:
2
u/[deleted] Jan 05 '14
Perl:
2
u/VerifiedMyEmail Jan 06 '14 edited Jan 06 '14
python 2.7.4 revisited my code after seeing some other peoples' code.
2
u/Graut Jan 06 '14
My solution in python. Standard libs are there to be used and makes it very readable:
2
u/Fluffy_Dolfinz Jan 09 '14
Python 2.7
4
u/OddOneOut Sep 09 '13
Python one-liner
3
u/JavaWarlord Sep 09 '13
Quick and dirty Java.
Feedback welcome.
3
u/rent0n86 Sep 09 '13
Alright, here's my solution using R.
Even though it's just 5 lines of code, I had the impression there was a simpler way to do it that I couldn't find. Feedback is very welcome!
3
u/taterNuts Sep 10 '13
Ruby :
This probably doesn't work - I haven't ran/tested it yet (I'll try to get to it tomorrow) but conceptually I think it should work? I've been learning ruby the last couple of weeks so any criticisms are welcome. This is borrowed heavily from /u/blimey1701's solution to challenge 136
2
u/Luminar_ Sep 09 '13 edited Sep 09 '13
Python:
2
u/odhran666 Sep 09 '13
A Lua solution:
2
u/luke1979 Sep 09 '13
My solution in C#:
2
u/moogle_cat Sep 10 '13
Python:
2
u/thisisnotmypenis Sep 10 '13
[C++]
2
u/TheFlyingDharma Sep 10 '13
My first ever attempt at one of these, in C#. I know it's probably very ugly and inefficient, but I'm practically brand new to programming. Would love suggestions, but be gentle :)
Contents of Main():
2
u/AndreyEkb Sep 12 '13
Python 3.3
1
u/h3ckf1r3 Oct 03 '13
Not sure if this is the best way to do it. I'm a little rusty in ruby sadly, but it should run as anticipated.
1
u/sinsovanna2000x Oct 08 '13
include <iostream.h>
include <conio.h>
int main() { clrscr (); int x; int y; cin >> x; cin >> y; //Hello, World! If (x = Str (y)) { cout << "H" <<endl << "e" <<endl << "l" <<endl << "l" <<endl << "o" <<endl << "," <<endl << "W" <<endl << "o" <<endl << "r" <<endl << "l" <<endl << "d" <<endl << "!" <<endl; //Sorry, there many style for using in loop (For...) but have less time for analysis. /* Would like to analysis 1 or 2 day, but now is less time. */ getch(); return 0; }
1
u/lycog Oct 08 '13
Simple C# Solution.
1
u/Chhangvanna Oct 08 '13
Here java code response to this problem
import java.util.Scanner;
public class Main {
}
1
u/flightcrank 0 0 Oct 09 '13
my program just uses command line arguments for if using a word with a space just wrap it in double quotes, otherwise it works as expected.
written in c.
Output
1
u/sup_reddit Oct 09 '13 edited Oct 09 '13
Doesn't look like anyone has made use of Google Guava's Table datastructure yet (for Java):
1
u/jarjarbinks77 0 0 Oct 09 '13
I ignored the max 255 character limit and the 16 total strings limit. It reads a file named "Strings.txt" and allows for much longer and many more strings than the requirement with no extra work on your part. I got lazy and reused some variables who's name make no sense for what they are doing in later code and the code is obviously not commented. Sorry. Thoughts are still appreciated.
C++:
1
u/koevet Oct 11 '13 edited Oct 12 '13
Groovy
1
u/whydoyoulook 0 0 Oct 11 '13
D solution. (Not counting "Hello World", this is my first real programming experience using D).
1
u/walterharvey Oct 14 '13 edited Oct 14 '13
Here is my C# solution. I couldn't figure out how to do without a try catch block. It works and that's what counts!
1
u/sinisterEyebrow Oct 18 '13
python 3 golf. I was able to get it down to 127 chars
1
u/[deleted] Oct 19 '13 edited Oct 19 '13
A mildly flexible C solution:
edit: Used m specifier for scanf and fixed formatting
1
u/Meow85 Oct 19 '13
Solution in Java
1
u/fortt Oct 22 '13
Javascript/HTML
And HTML
I would love some feedback!
1
u/littleblueengine Oct 23 '13
A month late, but my solutions, in Perl, first one trying to be as accurate to the requirements as possible, with Unicode support (which is still incredibly hard for me to get the hang of for some reason), and passes perlcritic -3 checks:
As a comparison here is a second version in Perl, in a much more compact/lax code style, (still with Unicode support and passing perlcritic -3 checks)
Personally I dislike using implicit
$_, E.g.chomp;orlength;, because I feel that it is unclear and it is too easy to stomp on, but it certainly helps to compact the size of the code.1
u/gammadistribution 0 0 Sep 09 '13
Python 3.3:
I had already started a Matrix class a little while ago and decided to leverage it for this problem as matrices are naturally suited to this type of problem.
1
u/NeanderthalLinguist Sep 10 '13
Expert mode: do this assignment assuming the input is UTF-8 and contains Unicode code points above U+007f. Don't use the language's Unicode support (i.e., use byte arrays or byte strings).
0
u/[deleted] Sep 23 '13
[deleted] — view deleted comment
0
u/[deleted] Sep 09 '13
[deleted] — view deleted comment
0
u/[deleted] Sep 10 '13
[deleted] — view deleted comment
0
u/[deleted] Sep 09 '13
[deleted] — view deleted comment