473,398 Members | 2,525 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

efficient algorithm

13
Hey I'm looking for a solution to the belowe question. Any recommendations on how to write this algorithm???
Thanks:


You are given a sequence s of numbers, in increasing order, for example:

s = 2, 5, 7, 9, 13, 15.

You are also given a number n, say n = 16. You have to try to find two numbers x and y from s, such that x+y = n, if such numbers exist. In this example, you could take x = 7 and y = 9.

However, you must do so as efficiently as possible: you must not perform more additions than the number of elements in s. Describe an algorithm to do this.
Apr 18 '07 #1
9 1475
ghostdog74
511 Expert 256MB
efficiency not taken into consideration:
Expand|Select|Wrap|Line Numbers
  1. s = [2, 5, 7, 9, 13, 15]
  2. n = 16 
  3. l = [n] * len(s)
  4. if n in s:
  5.     print "16 + 0"
  6. else:
  7.     r = [ operator.sub(*i) for i in zip(l,s) ]
  8.     print set(s).intersection(set(r))
  9.  
I have not tried on other variations, so this method may not be what you want
Apr 19 '07 #2
Expand|Select|Wrap|Line Numbers
  1. buldu=0;
  2. left = 0;
  3. right= Length-1;
  4.  
  5. while (left == right || buldu==1) {
  6.     if a[left]+ a[right] > KEY
  7.     right--;
  8.     else if a[left]+ a[right]<KEY
  9.     left++;
  10.     else if a[left]+ a[right]==KEY
  11.     buldu = 1; 
  12. }
best optimized i coud find.
Jul 23 '07 #3
bvdet
2,851 Expert Mod 2GB
Hey I'm looking for a solution to the belowe question. Any recommendations on how to write this algorithm???
Thanks:


You are given a sequence s of numbers, in increasing order, for example:

s = 2, 5, 7, 9, 13, 15.

You are also given a number n, say n = 16. You have to try to find two numbers x and y from s, such that x+y = n, if such numbers exist. In this example, you could take x = 7 and y = 9.

However, you must do so as efficiently as possible: you must not perform more additions than the number of elements in s. Describe an algorithm to do this.
Assuming your sequence will always contain unique numbers (no duplicates):
Expand|Select|Wrap|Line Numbers
  1. s = [2, 5, 7, 9, 13, 15]
  2.  
  3. result = 16
  4.  
  5. # count the number of iterations
  6. i = 1
  7.  
  8. # no need to check the last element in the list
  9. while len(s) > 1:
  10.     print i
  11.     n = result - s[0]
  12.     if n in s:
  13.         print '%d + %d = %d' % (s[0], n, result)
  14.         # remove 'n' from list
  15.         s.remove(n)
  16.     # remove first element from list
  17.     s = s[1:]
  18.     i += 1
Output:
>>> 1
2
3
7 + 9 = 16
4
>>>

If your sequence is always increasing in value, you can stop iterating after result/s[0] = 1.
Jul 23 '07 #4
bartonc
6,596 Expert 4TB
Assuming your sequence will always contain unique numbers (no duplicates):
Expand|Select|Wrap|Line Numbers
  1. s = [2, 5, 7, 9, 13, 15]
  2.  
  3. result = 16
  4.  
  5. # count the number of iterations
  6. i = 1
  7.  
  8. # no need to check the last element in the list
  9. while len(s) > 1:
  10.     print i
  11.     n = result - s[0]
  12.     if n in s:
  13.         print '%d + %d = %d' % (s[0], n, result)
  14.         # remove 'n' from list
  15.         s.remove(n)
  16.     # remove first element from list
  17.     s = s[1:]
  18.     i += 1
Output:
>>> 1
2
3
7 + 9 = 16
4
>>>

If your sequence is always increasing in value, you can stop iterating after result/s[0] = 1.
I like it! But on line 17, instead of recreating/reassigning the list, I'd use
Expand|Select|Wrap|Line Numbers
  1. s.pop(0)
as an efficiency improvement.
Jul 23 '07 #5
bvdet
2,851 Expert Mod 2GB
I like it! But on line 17, instead of recreating/reassigning the list, I'd use
Expand|Select|Wrap|Line Numbers
  1. s.pop(0)
as an efficiency improvement.
You are correct Barton! Thanks.
BTW - Congrats on breaking the 5000 barrier.
Jul 23 '07 #6
bartonc
6,596 Expert 4TB
You are correct Barton! Thanks.
BTW - Congrats on breaking the 5000 barrier.
Thank you <takes a deep bow>, thank you very much.
Jul 23 '07 #7
dmr
4
Hi,

I don't know if you're still interested, but a much more efficient algorithm would be to not do a linear search (at least for an arbitrarily large sequence). The following code does a binary search which converges on the two values which would sum to the target value (based on the premise that if no values are repeated and the sequence is increasing then the first value < target/2 < second value).
Expand|Select|Wrap|Line Numbers
  1. from math import floor
  2. from math import ceil
  3. from random import choice
  4.  
  5. s = [0]
  6.  
  7. for i in range(1,10000):
  8.   s.append(s[i-1] + choice([1,2,3,4,5]))
  9.  
  10. n = float(raw_input( "Enter a test number: "))
  11.  
  12. testn = int(floor( n/2 ) )
  13.  
  14. oldlistlen = len(s)
  15. listlen = int( floor(len(s) / 2) )
  16. foundit = False
  17. keepgoing = True
  18. i = 0
  19. upperlen = oldlistlen
  20. lowerlen = 0
  21.  
  22. while keepgoing == True:
  23.   print "Testing listlen %d, %d and %d" % (listlen, s[listlen], s[listlen + 1])
  24.   listlentemp = listlen
  25.   i = i + 1
  26.  
  27.   if s[listlen] + s[listlen + 1] == n:
  28.     foundit = True
  29.     keepgoing = False    
  30.  
  31.   elif s[listlen] < testn and s[listlen + 1] > testn:
  32.     print "No solution (<> test)"
  33.     keepgoing = False
  34.  
  35.   elif listlen == 0 or listlen == oldlistlen - 1:
  36.     keepgoing = False
  37.  
  38.   elif s[listlen] > testn:
  39.     upperlen = listlen
  40.     listlen = lowerlen + int( floor( ( upperlen - lowerlen ) / 2 ) )
  41.  
  42.   elif s[listlen] == testn:
  43.     print "No solution (found testn)"
  44.     keepgoing = False
  45.  
  46.   else:
  47.     lowerlen = listlen
  48.     listlen = lowerlen + int( ceil( (upperlen - lowerlen) / 2 ) )
  49.  
  50. if foundit:
  51.   print "Found it after %d iterations at index %d." % (i, listlen)
  52.  
  53. else:
  54.   print "Not found after %d iterations." % (i)
  55.  
Let me know what you think.
Aug 2 '07 #8
Hi,

What is the solution if in case we need to select more than on digit?
for example : in our list [2,5,7,9,13,15] and we need to find 16.
16 = 2+5+9 . and also it might more than 3 digits for example
31 =2+5+9+15 and so on......

Regards
Aug 14 '07 #9
dmr
4
That is a much more difficult problem, which has it's own wikipedia page.
Aug 14 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: John Cho | last post by:
// CHO, JOHN #include<iostream> class fracpri{ int whole; int numer; int denom;
11
by: hoopsho | last post by:
Hi Everyone, I am trying to write a program that does a few things very fast and with efficient use of memory... a) I need to parse a space-delimited file that is really large, upwards fo a...
1
by: Al | last post by:
Hi, I need to store literally thousands if images and scanned document in the Database. I would like to know what is the most efficient algorithm both in terms of speed and storage for saving images...
1
by: pedagani | last post by:
Dear comp.lang.c++, I'm interested in knowing the general techniques used to handle large binary files (>10GB) efficiently such as tweaking with filebuf , etc. Reading chunk by chunk seems to be...
3
by: sovixi | last post by:
Hey I'm looking for a solution to the belowe question. Any recommendations on how to write this algorithm??? Thanks: You are given a sequence s of numbers, in increasing order, for example: ...
4
by: Luna Moon | last post by:
seeking highly efficient caches scheme for demanding engineering computing? HI all, To same the time of costly function evaluation, I want to explore the possibility of caching. Suppose in...
12
by: pedagani | last post by:
Dear comp.lang.c++, Could you make this snippet more efficient? As you see I have too many variables introduced in the code. //Read set of integers from a file on line by line basis in a STL...
82
by: Bill David | last post by:
SUBJECT: How to make this program more efficient? In my program, a thread will check update from server periodically and generate a stl::map for other part of this program to read data from....
5
by: seemanikam | last post by:
Can anyone suggest me how to devise an efficient divide-and-conquer algorithm for the Tower-of-Hanoi problem when the disks are colored alternately red and blue, and with the extra rule that no disk...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.