Programming Forums
User Name Password Register
 

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

Reply
 
Thread Tools Display Modes
Old Jul 1st, 2008, 10:54 AM   #1
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 1,888
Rep Power: 5 Sane will become famous soon enough
Send a message via MSN to Sane
SMAC #2 [06-08] - Swapping Stories (Beginner)

Attached to this post is the test data for swapping stories.


Swapping Stories (Beginner)

Swapping stories was mainly an exercise in reading comprehension and how well you know the language.

If you can manage basic string manipulation and searching, this problem should be a walk in the park.

The algorithm to complete the task is also fairly intuitive.

1) Read a query
2) If the query says "no", go back to step 1
3) If the query says "yes", find each floor in the stack of papers
4) Swap the position of the two floors
5) Repeat

The way you do step 3 is up to you. You can search the entire list, you can use a dictionary, etc...

My solution simply does a search with Python's ".index()" method. It's not as fast as a dictionary, but it's easy to code.

Here is Titanium Decoy's solution which implements his own "index" method. His solution scored perfect.


C Syntax (Toggle Plain Text)
  1. /*
  2.  * SMAC #2
  3.  * titaniumdecoy
  4.  */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8.  
  9. char *next_token(void)
  10. {
  11. static char buf[21];
  12. char *string = NULL;
  13.  
  14. scanf("%s", buf);
  15. string = (char *)malloc(sizeof(char) * (strlen(buf) + 1));
  16. strcpy(string, buf);
  17.  
  18. return string;
  19. }
  20.  
  21. int index_of(char **array, int array_len, char *str)
  22. {
  23. int i = 0;
  24.  
  25. for (i = 0; i < array_len; i++)
  26. if (strcmp(array[i], str) == 0)
  27. return i;
  28.  
  29. return -1;
  30. }
  31.  
  32. void swap(char **array, int a, int b)
  33. {
  34. char *tmp = NULL;
  35.  
  36. tmp = array[a];
  37. array[a] = array[b];
  38. array[b] = tmp;
  39. }
  40.  
  41. int main()
  42. {
  43. int i = 0;
  44. int n = 0, q = 0;
  45. char **floors = NULL;
  46. char s1[21];
  47. char s2[21];
  48. char yn[4];
  49. int x = 0, y = 0;
  50.  
  51. freopen("swap.in", "r", stdin);
  52. freopen("swap.out", "w", stdout);
  53.  
  54. scanf("%d %d", &n, &q);
  55.  
  56. floors = (char **)malloc(sizeof(char *) * n);
  57.  
  58. for (i = 0; i < n; i++)
  59. floors[i] = next_token();
  60.  
  61. for (i = 0; i < q; i++)
  62. {
  63. scanf("%s %s %s", s1, s2, yn);
  64.  
  65. if (strcmp(yn, "yes") == 0)
  66. {
  67. x = index_of(floors, n, s1);
  68. y = index_of(floors, n, s2);
  69.  
  70. swap(floors, x, y);
  71. }
  72. }
  73.  
  74. for (i = 0; i < n; i++)
  75. printf("%s\n", floors[i]);
  76.  
  77. return 0;
  78. }


Jimbo's solution overkills the problem with a dictionary. It also scored perfect.

C# Syntax (Toggle Plain Text)
  1.  
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.IO;
  7.  
  8. namespace SMAC2_Beginner
  9. {
  10. class Program
  11. {
  12. class SwapRule
  13. {
  14. public string First;
  15. public string Second;
  16. public bool Swap;
  17.  
  18. public SwapRule(string s)
  19. {
  20. string[] parts = s.Split(" ".ToCharArray());
  21. First = parts[0];
  22. Second = parts[1];
  23. Swap = parts[2].Equals("yes", StringComparison.InvariantCultureIgnoreCase);
  24. }
  25. }
  26.  
  27. // strategy:
  28. // Read all the stories into a List
  29. // Keep them also in a dictionary so I know the original order
  30. // Apply any swap rules that contain "yes"
  31. // Swap the items in the list to their final places after all the swapping logic is done
  32. static void Main(string[] args)
  33. {
  34. StreamReader swapIn = null;
  35. StreamWriter swapOut = null;
  36. try
  37. {
  38. swapIn = new StreamReader("swap.in");
  39. string buffer = swapIn.ReadLine();
  40. int n, q;
  41. string[] nums = buffer.Split(" ".ToCharArray());
  42. n = int.Parse(nums[0]);
  43. q = int.Parse(nums[1]);
  44. Dictionary<string, int> storyIndices = new Dictionary<string, int>();
  45. List<string> stories = new List<string>();
  46. List<SwapRule> swapRules = new List<SwapRule>();
  47.  
  48. // read in stories
  49. for (int i = 0; i < n; i++)
  50. {
  51. string storyName = swapIn.ReadLine();
  52. storyIndices.Add(storyName, i);
  53. stories.Add(storyName);
  54. }
  55. // read in swap rules
  56. for (int i = 0; i < q; i++)
  57. {
  58. String swapLine = swapIn.ReadLine();
  59. SwapRule temp = new SwapRule(swapLine);
  60. // swap if the rule says yes
  61. if (temp.Swap)
  62. {
  63. int a = storyIndices[temp.First];
  64. storyIndices[temp.First] = storyIndices[temp.Second];
  65. storyIndices[temp.Second] = a;
  66. }
  67. }
  68. // now sort them after the swapping's done
  69. for (int i = 0; i < stories.Count; i++)
  70. {
  71. // need to loop doing this until storyIndices[stories[i]] == i, or else we don't have the right one in place
  72. // even with the nested loop, number of swaps will be O(n), since with each swap, one element is put into the
  73. // correct index
  74. while (storyIndices[stories[i]] != i)
  75. {
  76. swapListItems<string>(stories, i, storyIndices[stories[i]]);
  77. }
  78. }
  79.  
  80. // dump results
  81. swapOut = new StreamWriter("swap.out");
  82. foreach (string s in stories)
  83. {
  84. #if DEBUG
  85. Console.WriteLine(s);
  86. #endif
  87. swapOut.WriteLine(s);
  88. }
  89. swapOut.Flush();
  90. }
  91. catch(Exception e)
  92. {
  93. Console.WriteLine(String.Format("Error encountered, aborting. Error: [{0}]", e.ToString()));
  94. }
  95. finally
  96. {
  97. if (swapIn != null)
  98. {
  99. swapIn.Close();
  100. swapIn = null;
  101. }
  102. if (swapOut != null)
  103. {
  104. swapOut.Close();
  105. swapOut = null;
  106. }
  107. }
  108. }
  109.  
  110. private static void swapListItems<T>(List<T> l, int a, int b)
  111. {
  112. T temp = l[a];
  113. l[a] = l[b];
  114. l[b] = temp;
  115. }
  116. }
  117. }



And the official solution in Python:

Python Syntax (Toggle Plain Text)
  1. def scanf(line, *args):
  2. toks = line.replace('\n', '').split(' ')
  3. for i in range(len(args)):
  4. yield args[i](toks[i])
  5.  
  6. fin = open("swap.in", "r").readlines()
  7. n, q = scanf(fin[0], int, int)
  8.  
  9. # Parse each floor name
  10. floors = []
  11. for i in range(n):
  12. floors.append(scanf(fin[i+1], str).next())
  13.  
  14. # Parse each query
  15. for i in range(q):
  16. f1, f2, cmd = scanf(fin[i+n+1], str, str, str)
  17.  
  18. if cmd == "yes":
  19. # Search for each floor name
  20. i1 = floors.index(f1)
  21. i2 = floors.index(f2)
  22.  
  23. # Swap the two floors names
  24. temp = floors[i1]
  25. floors[i1] = floors[i2]
  26. floors[i2] = temp
  27.  
  28. # Output the results
  29. fout = open("swap.out", "w")
  30.  
  31. for i in range(n):
  32. fout.write("%s\n"%floors[i])
  33.  
  34. fout.close()
Attached Files
File Type: zip swap.zip (32.7 KB, 1 views)
Sane is online now   Reply With Quote
Old Jul 1st, 2008, 1:35 PM   #2
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 1,888
Rep Power: 5 Sane will become famous soon enough
Send a message via MSN to Sane
Re: SMAC #2 [06-08] - Swapping Stories (Beginner)

I would also like to add Andrew's (anrchydrgn) solution to this thread. His code was very compact, clean, and worked perfectly.

C++ Syntax (Toggle Plain Text)
  1. // Program name: swap.cpp
  2. // Created by : Andrew Richardson
  3. // Created on : 6/4/08
  4. // Last Edited :
  5. // Purpose :
  6. //
  7.  
  8. #include <stdio.h>
  9. #include <string.h>
  10.  
  11. int main(void) {
  12. int n,q, s1, s2;
  13. char fname[100][21];
  14. char str1[21],str2[21],str3[4];
  15.  
  16. freopen("swap.in","r+",stdin);
  17. freopen("swap.out","w+",stdout);
  18.  
  19. scanf("%d",&n);
  20. scanf("%d",&q);
  21. for(int i=0;i<n;i++) {
  22. scanf("%s", fname[i]);
  23. }
  24.  
  25. for(int i=0;i<q;i++) {
  26. scanf("%s", str1);
  27. scanf("%s", str2);
  28. scanf("%s", str3);
  29. if(strcmp(str3,"yes")==0) {
  30. for(int c=0;c<n;c++) {
  31. if(strcmp(fname[c],str1)==0) s1=c;
  32. if(strcmp(fname[c],str2)==0) s2=c;
  33. }
  34. strcpy(str1,fname[s1]);
  35. strcpy(fname[s1],fname[s2]);
  36. strcpy(fname[s2],str1);
  37. }
  38. }
  39. for(int i=0;i<n;i++) {
  40. printf("%s\n", fname[i]);
  41. }
  42. }
Sane is online now   Reply With Quote
Reply

Bookmarks

Tags
smac beginner 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

Similar Threads
Thread Thread Starter Forum Replies Last Post
SMAC #1 [05-08] - Mobile (Beginner) and "n Reach k" (Junior) Sane Software Design and Algorithms 2 Jun 3rd, 2008 8:10 AM
SMAC #1 [05-08] - Results Sane Software Design and Algorithms 6 Jun 2nd, 2008 4:56 PM
I'm a Beginner Chuckiferd Python 37 Dec 19th, 2007 1:09 PM
what open source code is good to read for a beginner? linuxpimp20 Other Programming Languages 22 Aug 30th, 2005 3:01 PM
Please help a new beginner! woodzs PHP 4 May 18th, 2005 11:04 AM




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 10:50 PM.

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