Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Jun 2nd, 2008, 5:53 PM   #1
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 2,028
Rep Power: 6 Sane will become famous soon enough
Send a message via MSN to Sane
SMAC #1 [05-08] - Mobile (Beginner) and "n Reach k" (Junior)

Attached to this post is the test data for both problems.


Mobile (Junior)

This solution required the ability to follow instructions and write a stable primality test. If using Python, you need to be careful about how large of a range you create with range(). Alternatives, such as xrange() and while loops, do exist.

Note: For this problem, it was left unclear what should happen if n=0. The "correct" solution converts 0 to 0. However, no test data exploits alternate behaviour.

Here is Jessehk's solution, written in Python (modified slightly for backwards compatibility):

Python Syntax (Toggle Plain Text)
  1. import math
  2.  
  3. INPUT_FILENAME = "move.in"
  4. OUTPUT_FILENAME = "move.out"
  5.  
  6. def isPrime(n):
  7. if n <= 1:
  8. return False
  9. else:
  10. limit = int(math.sqrt(n))
  11. for x in xrange(2, limit + 1):
  12. if n % x == 0:
  13. return False
  14.  
  15. return True
  16.  
  17. def nextMove(n):
  18. if n < 0:
  19. return abs(n)
  20. elif isPrime(n):
  21. return n - 1
  22. else:
  23. return n + 3
  24.  
  25. def fromString(string, *types):
  26. result = []
  27. for token, desired in zip(string.split(), types):
  28. result.append(desired(token))
  29.  
  30. if len(result) is not len(types):
  31. raise TypeError, "Expected %s" % (types,)
  32. else:
  33. return result
  34.  
  35. def readSpec(filename=INPUT_FILENAME):
  36. inf = open(filename, 'r')
  37. return fromString(inf.readline(), int, int)
  38.  
  39. def writeResult(result, filename=OUTPUT_FILENAME):
  40. outf = open(filename, 'w')
  41. outf.write("%d\n" % result)
  42.  
  43. def doSequence(start, length):
  44. current = start
  45. for x in xrange(length - 1):
  46. current = nextMove(current)
  47.  
  48. return current
  49.  
  50. def main():
  51. try:
  52. writeResult(doSequence(*readSpec()))
  53. except Exception, e:
  54. print e
  55.  
  56. if __name__ == "__main__":
  57. main()


And here is the official solution:

C Syntax (Toggle Plain Text)
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. int isprime(int i) {
  5. int k, lim;
  6.  
  7. if(i<2) return 0; // Less than 2 is composite
  8. if(i==2) return 1; // 2 is prime
  9. if(i%2==0) return 0; // Divisible by 2 is composite
  10.  
  11. lim = sqrt(i)+1;
  12. for(k=3; k<=lim; k+=2) // The standard primality test
  13. if(i%k==0) return 0;
  14.  
  15. return 1;
  16. }
  17.  
  18. int main() {
  19. int n, k;
  20.  
  21. freopen("move.in", "rt", stdin);
  22. freopen("move.out", "wt", stdout);
  23. scanf("%d %d", &n, &k);
  24.  
  25. while(--k) {
  26. if(isprime(n)) n -= 1; // Rule #3
  27. else if(n<0) n =- n; // Rule #1
  28. else if(n>0) n += 3; // Rule #2
  29. }
  30.  
  31. printf("%d\n", n);
  32. return 0;
  33. }


"n Reach k" (Junior)

This solution required you to write a recursive function. For each state, you need to branch off to all possible states. When you reach the end of recursion (the base case), you store the maximum n thus far. After taking all possible routes, the maximum value of n is the value of nRk.

To score full points, the primality test must be careful to not exhaustively try modulating by all values, or else it might run over time. Wikipedia has some efficient algorithms for primality tests.

Ooble implemented a very good primality test that runs very quickly even in Python. Here is his solution, also written in Python. This code by itself will not run. Functions that do I/O work were included in a separate module, and have therefore been left out.

Python Syntax (Toggle Plain Text)
  1. class SMAC:
  2. def isPrime (self, n):
  3. if n < 2:
  4. return False
  5. elif n == 2:
  6. return True
  7. elif n % 2 == 0:
  8. return False
  9. else:
  10. i = 3
  11. while i * i <= n:
  12. if n % i == 0:
  13. return False
  14. i += 2
  15.  
  16. return True
  17.  
  18. def junior (self):
  19. args = self.loadFile("reach.in").split()
  20. if len(args) != 2:
  21. raise EnvironmentError(1, "Invalid file contents.")
  22.  
  23. n = int(args[0])
  24. k = int(args[1])
  25.  
  26. r = max(self.juniorResults(n, k, 1))
  27. self.saveFile("reach.out", r)
  28.  
  29. def juniorResults (self, n, k, i):
  30. if i > k:
  31. return [n]
  32.  
  33. r = []
  34. r += self.juniorResults(n + i, k, i + 1)
  35. r += self.juniorResults(n - i, k, i + 1)
  36. if self.isPrime(n):
  37. r += self.juniorResults(n * 2, k, i + 1)
  38. return r
  39.  
  40. if __name__ == '__main__':
  41. smac = SMAC()
  42. smac.junior()


And here is the official solution:

C Syntax (Toggle Plain Text)
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. int max(int a, int b) {
  5. return a > b ? a : b;
  6. }
  7.  
  8. int isprime(int i) {
  9. int k, lim;
  10.  
  11. if(i<2) return 0; // Less than 2 is composite
  12. if(i==2) return 1; // 2 is prime
  13. if(i%2==0) return 0; // Divisible by 2 is composite
  14.  
  15. lim = sqrt(i)+1;
  16. for(k=3; k<=lim; k+=2) // The standard primality test
  17. if(i%k==0) return 0;
  18.  
  19. return 1;
  20. }
  21.  
  22. int reach(int n, int i, int k) {
  23. int r;
  24. if(i>k) return n;
  25.  
  26. r = max(reach(n+i, i+1, k), // Option #1
  27. reach(n-i, i+1, k)); // Option #2
  28. if(isprime(n)) // Option #3
  29. r = max(reach(n*2, i+1, k), r);
  30.  
  31. return r; // Return the maximum possible value from all 3 options
  32. }
  33.  
  34. int main() {
  35. int n, k;
  36.  
  37. freopen("reach.in", "rt", stdin);
  38. freopen("reach.out", "wt", stdout);
  39. scanf("%d %d", &n, &k);
  40.  
  41. printf("%d\n", reach(n,1,k));
  42. return 0;
  43. }
Attached Files
File Type: zip move.zip (1.0 KB, 2 views)
File Type: zip reach.zip (2.0 KB, 4 views)
__________________
Looking for tough programming challenges? Try participating in Sane's Monthly Algorithms Challenges!
Composing Techno is a little side hobby of mine. Techno by DJ Sane. All free for download.
Sane is offline   Reply With Quote
Old Jun 3rd, 2008, 1:41 AM   #2
anrchydrgn
Newbie
 
Join Date: May 2008
Posts: 2
Rep Power: 0 anrchydrgn is on a distinguished road
Re: SMAC #1 [05-08] - Mobile (Beginner) and "n Reach k" (Junior)

For test case #9 the solution you have is a negative number, I thought the file must be wrong or corrupted somehow, so I copied your code and compiled it and I got the same negative number, how can a negative number be the maximum or am I mistaken somehow

Edit: nvmd I posted this before looking at the test case and cant delete the post now
anrchydrgn is offline   Reply With Quote
Old Jun 3rd, 2008, 9:10 AM   #3
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 2,028
Rep Power: 6 Sane will become famous soon enough
Send a message via MSN to Sane
Re: SMAC #1 [05-08] - Mobile (Beginner) and "n Reach k" (Junior)

Yeah, don't be afraid to ask about things like that. There's a good chance I did make a mistake somewhere from rushing about.

I've got some good problems brewing for this month. They are less typical, and more plot based. I will try my best to get them posted by Friday or Saturday.
__________________
Looking for tough programming challenges? Try participating in Sane's Monthly Algorithms Challenges!
Composing Techno is a little side hobby of mine. Techno by DJ Sane. All free for download.
Sane is offline   Reply With Quote
Reply

Bookmarks

Tags
smac beginner solutions, smac junior solutions

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 7:27 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC