r/dailyprogrammer • u/Coder_d00d 1 3 • Jun 27 '14
[6/27/2014] Challenge #168 [Easy] String Index
What no hard?:
So my originally planned [Hard] has issues. So it is not ready for posting. I don't have another [Hard] so we are gonna do a nice [Easy] one for Friday for all of us to enjoy.
Description:
We know arrays. We index into them to get a value. What if we could apply this to a string? But the index finds a "word". Imagine being able to parse the words in a string by giving an index. This can be useful for many reasons.
Example:
Say you have the String "The lazy cat slept in the sunlight."
If you asked for the Word at index 3 you would get "cat" back. If you asked for the Word at index 0 you get back an empty string "". Why an empty string at 0? Because we will not use a 0 index but our index begins at 1. If you ask for word at index 8 you will get back an empty string as the string only has 7 words. Any negative index makes no sense and return an empty string "".
Rules to parse:
- Words is defined as [a-zA-Z0-9]+ so at least one of these and many more in a row defines a word.
- Any other character is just a buffer between words."
- Index can be any integer (this oddly enough includes negative value).
- If the index into the string does not make sense because the word does not exist then return an empty string.
Challenge Input:
Your string: "...You...!!!@!3124131212 Hello have this is a --- string Solved !!...? to test @\n\n\n#!#@#@%$**#$@ Congratz this!!!!!!!!!!!!!!!!one ---Problem\n\n"
Find the words at these indexes and display them with a " " between them: 12 -1 1 -100 4 1000 9 -1000 16 13 17 15
10
u/skeeto -9 8 Jun 28 '14
JavaScript.
Usage:
6
u/Edward_H Jun 28 '14
COBOL:
4
u/Befriendswbob Jun 27 '14 edited Jun 27 '14
First post, solution in C#!
Pretty simple. Made an object to handle the concept and rules of a string array using words, then called it in a loop with the given indices. Probably could condense it with some LINQ trickery, but I prefer being able to read my code :)
Output:
4
u/Godd2 Jun 28 '14
This one was pretty straightforward with a regex in Ruby:
3
u/dohaqatar7 1 1 Jun 27 '14 edited Jun 27 '14
I'm a little sad to no see a hard challenge today, but I'll get over it. Here's my solution in Haskell
Haskell
3
u/Reverse_Skydiver 1 0 Jun 27 '14
Here's my solution in Java. I could make it even shorter but that would just be messy!
public class C0168_Easy2 {
3
u/jnazario 2 0 Jun 28 '14
F#, a fairly direct solution (e.g. nothing special about the language or FP in general being used here).
output:
3
u/joeyGibson Jun 28 '14
Here's my simple solution in Clojure. As always, a pretty-printed version is available at https://github.com/joeygibson/dailyprogrammer
and the output is this:
This one was pretty easy (of course, that was in the title...).
2
u/7f0b Jun 27 '14
Solution in PHP.
Here is the input string and indexes to find:
And this outputs the solution:
2
u/FerdErik Jun 27 '14
Another solution in Java 8. Again with Streams, Lambdas and RegExes.
2
u/guitar8880 Jun 27 '14 edited Jun 27 '14
Python 3.4
My first solution for /r/dailyprogrammer/. I'm very new to Python, so I am open to all comments and criticism on my style, efficiency, or anything else that I should know.
Result:
2
u/sradloff23 Jun 28 '14
This is my first submission to this sub, but I have been following it for a while. I couldn't get the full solution for the challenge input using Ruby, but I was able to get the example solution relatively easily.
2
u/bricocard Jun 28 '14
First submission in daily programmer. My solution in C
2
u/killedbythegrue Jun 28 '14
Erlang
outuput:
2
u/cooper6581 Jun 30 '14
Erlang:
2
u/logicalish Jul 01 '14
Python 2.7:
Challenge Output:
2
u/wtf_are_my_initials Jul 02 '14
Node.js solution
input.txt:...!!!@!3124131212 Hello have this is a --- string Solved !!...? to test @\n\n\n#!#@#@%$**#$@ Congratz this!!!!!!!!!!!!!!!!one ---Problem\n\n
indexes.txt:12 -1 1 -100 4 1000 9 -1000 16 13 17 15
Challenge output:
3
u/mr_wonderful Jun 27 '14 edited Jun 30 '14
Edit: New Swift solution using regular expressions:
Old solution:
And the result of both:
2
u/Godspiral 3 3 Jun 27 '14 edited Jun 28 '14
J has its own parser verb with rules different than this. It is good at parsing both the language and regular written language.
reddit ": ;: 'The lazy cat slept in the sunlight.'
(<'cat') i.~ ;: 'The lazy cat slept in the sunlight.'
2 NB. 0 based
:: uses the left verb as an alternate if the right verb produces an error { selects from left using indexes on right.
Using J's parser rules (not problem's regex which I may do later):
the rx version: (_1 is valid index, and J does not read embedded /n in strings as C)
2
u/toodim Jun 27 '14
Python 3.4
1
u/poeir Jun 27 '14
Approach in Python 2.7, extend the str class. The argparse module is overkill here, but it adds handy flexibility for testing. The 1-based indexing threw me off, I'm so used to starting counting at 0.
Usage:
1
u/dontbeanegatron Jun 27 '14
Here's my version in Javascript, pretty quick 'n dirty: http://jsbin.com/zehixili/2/edit
Edit: I added a wordAt() function to String's prototype that splits the string into bits and returns the word at the given index.
1
u/thinksInCode Jun 27 '14
Trying another one in Groovy:
1
u/zenodotus Jun 27 '14
First post, feedback welcome! Javascript solution intended to be executed by node.js:
1
u/dreamyeyed Jun 27 '14
Lua:
1
u/mortenaa Jun 27 '14
Solved with Dart. Only slight problem was the $ characters, which are used for string interpolation in Dart. I used a raw string to avoid the problem, but this created another problem, the quoted newlines (\n) got interpreted as two characters instead of newlines. Solved this by replacing them with literal newlines in the raw string.
Challenge Output
1
u/r_s Jun 27 '14 edited Jun 27 '14
C++ (C11)
1
u/mdlcm Jun 27 '14
Used R. Steps: (1) data input (2) extract word from string (3) find indices to keep (4) construct the sentence
Output
1
u/eslag90 Jun 28 '14
Seems like cheating to use regular expressions, but here is python 2.7
1
u/Komorebi Jun 28 '14
My solution in Python 2.7. Still getting the hang of this language. Decided to try some doctests for this one, as well as the challenge input. Comments welcome. Thanks.
1
u/flugamababoo Jun 28 '14 edited Jun 28 '14
Python 3.4:
Output:
1
u/uilt Jun 28 '14
Here's a solution in Julia. Haven't thoroughly tested the parsing yet, though. Julia's [] can be overloaded by adding a getindex function.
1
u/tally_in_da_houise Jun 28 '14
Python 2.7 solution:
1
u/jeaton Jun 28 '14
JavaScript Harmony:
1
u/marchelzo Jun 28 '14
Haskell:
It started out really clean and then deteriorated to what it is now :/
1
u/BryghtShadow Jun 28 '14
SWI-Prolog 6.6.6
Output:
1
u/Regimardyl Jun 28 '14
Haskell, pretty sure I could make it shorther but this should be very readable at least.
1
u/bearcherian Jun 28 '14
Solution in D. New to the language, coming from Java.
Going by the parsing rules alone, just as they are, then 'n' is a valid word and '' is part of the buffer between words.
This is my initial solution.
And the initial output:
But taking in the assumption that '\n' is to be treated as a single newline character, this is my second solution.
And the output is
1
u/[deleted] Jun 28 '14
4 lines of Clojure:
Output:
1
u/unptitdej Jun 28 '14 edited Jun 28 '14
Here's a C solution with a char lookup table. It's the next fastest way after the compile time regex. Fastest if the string is not known at compile time.
https://github.com/mitchi/dailyprogrammer-challenges
1
u/MrP_123 Jun 28 '14
Java once again:
Didn't know you could use a for each like this.
1
u/dreugeworst Jun 28 '14 edited Jun 30 '14
Haven't seen a c++ answer yet:
[edit] apparently r_s had a c++ solution that I missed. Like his use of standard algorithms, so changed mine to use them.
1
u/BryghtShadow Jun 28 '14
Python 3.4
Indexes can be int, str, or list.
Out:
1
u/jonnywoh Jun 28 '14
Powershell
1
u/mm865 Jun 29 '14
Python 2.7 OOP type implicit solution :)
To test:
1
u/sadwhaleissad Jun 29 '14 edited Jun 29 '14
Just using Lua :) Edit: Formatting
1
u/Olidan Jun 29 '14
First Dailyprogrammer, with a C# soloution Feedback is welcome.
Output:
1
u/kuzux 0 0 Jun 29 '14
My haskell solution:
1
u/its_that_time_again Jun 29 '14
C implementation, a little verbose but fairly readable:
1
u/dp_account Jun 30 '14
Python 3:
Output:
1
u/undergroundmonorail Jun 30 '14
Python 2.7 - 117 bytes
Usage examples:
I feel like I was supposed to interpret your
\ns as literal newlines, rather than a backslash and an 'n', but you didn't specify and this saves me characters.I love code golf. If you've never heard of code golf, it's similar to regular golf: Golfers try to put a ball in a hole with the least strokes, and code golfers try to solve some kind of problem with the least keystrokes; that is, the smallest source code. Generally speaking, 1 character == 1 byte, so this is a 120 character solution.
Code golfers don't care about things like "code style" or "efficiency", so you definitely shouldn't look at golfed code and think "I'll try that in my real projects!", but it's a fun exercise nonetheless.
How it works
The first line gets a line of input and turns it into a list split at non-alphanumeric characters. I could have done this with regular expressions, but I didn't for a couple reasons:
/\W+/would match the spec.To do this, we define a generator expression like so:
All this means is "For every character in the first line of input, call that character
c. Then, return the result of[' ',c][c.isalnum()]for everyc.c.isalnum()is a function that returns True ifcis a letter or number andFalseotherwise. However, python is a very weakly typed language, and has no problem converting thosebools toints silently if it needs to. For our purposes, we'll say it returns1ifcis alphanumeric and0otherwise.[' ',c]is just a list. It has a string with a single space character, and it has the originalcfrom the input.We use the result of
c.isalnum()to index into this list. Remember, we're dealing with the return value as anint. Lists are 0 indexed, so we get out the space string ifcisn't alphanumeric, and the originalcif it is.joinis a useful function. You stick it onto some string, feed it an iterable, and it creates a string with every element from the iterable separated by the string you stuck it on. Here, we do''.join(meaning "no delimiter") and feed it the generator we just made. This gives us the same string we had at the very beginning, except every non-alphanumeric character has been replaced with a space.Calling
split()on a string gives us a list of that string, split at every instance ofsplit's argument, or all whitespace by default. We just replaced our non-alnum characters with whitespace, so we just got a list of the words we need! Stick in in a variable calledsand we're done our first line. Only one more to go!There's another generator expression in the second line:
In python2,
input()basically meanseval(raw_input()). It turns whatever the input is into a python data structure. You'll notice that in my examples, I put commas between the indexes I wanted the program to look at. That way, it gets turned into atupleofints. (One quirk of this is that if you only want one word, you have to type it as, for example, "5,".)This expression spits out the result of
s[i-1]if 0<i<=len(s)else""for eachiin the input. (We can't use theboolindexing trick we used earlier since we need it to "short-circuit" this time. That's not too important so I won't explain it unless someone asks.) This checks to make sure thatiis greater than 0 and not longer than the number of words in our first input. If that is true, we give up and output an empty string directly. Otherwise, though, we subtract 1 fromi(to account for 1-indexing) and get the word at that index from the list we saved before.We use
joinagain, this time with a space as the delimiter. Then, we simply print the result and we are done! Hooray! \o/Sorry about how long this got! One of the great ironies in life is that shorter code needs a longer explanation. :P
I can move the explanation off-site and link to it if it's a problem. Otherwise, enjoy!
1
u/poltergeistt Jul 01 '14
First time submitting a solution. I used Haxe to solve this challenge. Comments make up more than half of the code, though. I always overdo it with the comments.
I'm guessing there's probably a better way of doing this because I really haven't put too much thought in it. Either way, I'm happy with the outcome.
1
u/dailyRubyProgrammer Jul 01 '14
Here's my solution in - you guessed it - Ruby:
1
u/allcentury Jul 01 '14
I decided to write my own [] method in ruby...
The test suit looks like this:
1
u/compmstr Jul 01 '14
My Haskell Solution:
1
u/hellectric Jul 02 '14
A bit late, but a solution in Groovy:
1
u/this_shall_pass Jul 02 '14 edited Jul 02 '14
C++ Solution:
1
u/dnerd Jul 04 '14
c#
1
u/[deleted] Jul 05 '14
First time poster here. This is my humble solution in Golang. :)
1
u/DeliveryNinja Jul 05 '14
I did a solution in Scala, just learning! Made it immutable, also bit late to the party
1
u/-AMD- Jul 05 '14
Python 2.7
1
u/VerifiedMyEmail Jul 05 '14
python 3.3 not pretty
1
u/Carnitin Jul 08 '14
PHP
1
u/Flapling Jul 14 '14
Rust (0.12.0-pre-nightly (5d200dd60dabf94323d13b98b6c3d0b88f100b85 2014-07-13 01:16:34 +0000))
1
u/chunes 1 2 Jul 14 '14
Learning Haskell:
1
u/Coplate Jul 14 '14
COBOL
gist here
It Doesn't return in the requested format becasue I don't know how to do that yet.
Its also hard coded to add 1 to the index, becasue of the same data starting with a seperator, so it wont work on a normal string.
OUTPUT
1
u/[deleted] Jul 24 '14
My C# solution. I created an extension method so that you can call myString.Word(index).
1
u/verydapeng Aug 19 '14
clojure
run the codes
0
u/[deleted] Jun 27 '14
[deleted] — view deleted comment
0
u/[deleted] Jun 27 '14
[deleted] — view deleted comment
0
u/[deleted] Jun 29 '14
[deleted] — view deleted comment