Robert Smith avatar Robert Smith committed 0078383

greatly simplify REVERSE-WORDS!

Comments (0)

Files changed (1)

miscellaneous_exercises/reverse-words.lisp

         :do (rotatef (aref string i)
                      (aref string j))))
 
-(defun reverse-words (string)
-  "Reverse the words in the string STRING in place."
-  (labels ((reverse-next-word (word-start)
-             (if (>= word-start len)
-                 string
-                 (let ((word-end (or (position #\Space string :start word-start
-                                                              :test #'char=)
-                                     (length string))))
-                   (reverse-substring! string word-start word-end)
-                   (reverse-next-word (1+ word-end))))))
-    (reverse-next-word 0)))
+(defun reverse-words! (string)
+  "Reverse the individual words in the string STRING in place."
+  (let ((len (length string))
+        (start 0))
+    (dotimes (i (1+ len) string)
+      (when (or (= len i) (char= #\Space (aref string i)))
+        (reverse-substring! string start i)
+        (setf start (1+ i))))))
 
 ;; Note that 0 bytes were allocated during the REVERSE-WORDS
 ;; computation.
 ;;
 ;; CL-USER> (let ((s (copy-seq "Hello my 1 name is quad")))
-;;            (time (reverse-words s)))
+;;            (time (reverse-words! s)))
 ;;
 ;; Timing the evaluation of (REVERSE-WORDS S)
 ;;
 ;; Allocation   = 0 bytes
 ;; 0 Page faults
 ;; "olleH ym 1 eman si dauq"
+
+
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.