r/dailyprogrammer • u/rya11111 3 1 • Mar 26 '12
[3/26/2012] Challenge #30 [easy]
Write a program that takes a list of integers and a target number and determines if any two integers in the list sum to the target number. If so, return the two numbers. If not, return an indication that no such integers exist.
Edit : Note the "Intermediate" challenge #30 has been changed. Thank you!
4
Upvotes
5
u/gsg_ Mar 27 '12 edited Mar 27 '12
This is a much more interesting problem if you insist on doing better than O(n^2). My (slightly flawed) O(nlogn) implementation:
1
u/namekuseijin Mar 27 '12
hmm, most solutions seem to imply the list (1 2 3) got 2 integers that sum 2. Which is wrong, because the problem asks for 2 integers, not the same one twice.
3
u/luxgladius 0 0 Mar 26 '12 edited Mar 26 '12
Perl, N time:
3
u/gjwebber 0 0 Mar 26 '12
Python:
Usage: print can_sum([1, 2, 3, 4, 5], 6) => (1, 5)
2
u/tehstone Mar 26 '12
After my Google search-enabled crash course on list comprehension and generator expressions in Python, I wrote this:
2
u/namiisc Mar 27 '12
Python:
I think this is the right solution given on the description. Said to find two numbers, in my opinion [1,2,3,4,5] (3,3) is not a solution, also to find any numbers given that sum it's enough to print like (1,5) but the idea @tehstone to put it in a list is also nice, but duplicates in the list are not nice :D
2
u/[deleted] Mar 29 '12
I'm a bit short of time so this isn't real code, but I'm quite new to programming and would be interested in any feedback on my solution in pseudo-code:
Thanks.
1
u/met48 Mar 26 '12
Python:
1
u/DanielJohnBenton 0 0 Mar 26 '12
C++. Sorry it's not too clean, coded in a hurry in 5 minutes.
1
u/robin-gvx 0 2 Mar 26 '12
This language doesn't have a name yet:
1
u/[deleted] Mar 26 '12
Javascript
1
u/namekuseijin Mar 26 '12
plain scheme
1
u/silverslayer33 Mar 26 '12 edited Mar 26 '12
I wrote a function in C# for this a while ago for one of the Google Code Jam practice problems, but I can't find it right now. I'll try and edit this later with it if I find it, and if I don't, I'll probably just redo it in Python and post that.
EDIT: Found it! Edit2: Formatting was messed up, gotta get used to how reddit does things. I'll try again in a minute...
Edit3: Well, I feel dumb, but I can't format this even though I keep following the "4 spaces" thing D:Beginners mistake for myself... I fixed it... but now I know!1
u/mazzer Mar 26 '12
Groovy:
1
u/magwhich Mar 27 '12
python
1
u/Yuushi Mar 27 '12
Python, O(N):
1
u/CarNiBore Mar 27 '12
Ruby
1
u/zip_000 Sep 21 '12
PHP: