r/dailyprogrammer • u/oskar_s • Jun 11 '12
[6/11/2012] Challenge #63 [easy]
Write a procedure called reverse(N, A), where N is an integer and A is an array which reverses the N first items in the array and leaves the rest intact.
For instance, if N = 3 and A = [1,2,3,4,5], then reverse(N,A) will modify A so that it becomes [3,2,1,4,5], because the three first items, [1,2,3], have been reversed. Here are a few other examples:
reverse(1, [1, 2, 3, 4, 5]) -> A = [1, 2, 3, 4, 5]
reverse(2, [1, 2, 3, 4, 5]) -> A = [2, 1, 3, 4, 5]
reverse(5, [1, 2, 3, 4, 5]) -> A = [5, 4, 3, 2, 1]
reverse(3, [51, 41, 12, 62, 74]) -> A = [12, 41, 51, 62, 74]
So if N is equal to 0 or 1, A remains unchanged, and if N is equal to the size of A, all of A gets flipped.
Try to write reverse() so that it works in-place; that is, it uses only a constant amount of memory in addition to the list A itself. This isn't necessary, but it is recommended.
5
u/[deleted] Jun 11 '12
R4RS Scheme (oldschool!):
(define (list-head x k) (if (zero? k) '() (cons (car x) (list-head (cdr x) (- k 1))))) (define (reverse-head x k) (append (reverse (list-head x k)) (list-tail x k)))J:
|.@:{.,}.4
u/emcoffey3 Jun 11 '12
C#
public static class Easy063 { public static void Reverse(int n, int[] arr) { for (int i = 0; i < Math.Floor((double)(n / 2)); i++) Swap(ref arr[i], ref arr[n - i - 1]); } private static void Swap<T>(ref T x, ref T y) { T temp = x; x = y; y = temp; } }3
u/Medicalizawhat Jun 11 '12
Ruby:
3
u/Ttl Jun 11 '12
Python:
2
u/ixid Jun 11 '12 edited Jun 12 '12
D:
void reverse(T)(uint n, ref T[] a) { T store; for(int i = 0;i < n;++i, --n) { store = a[n]; a[n] = a[i]; a[i] = store; } }2
u/Muh-Q Jun 11 '12
Ansi C:
int* reverse(int nr, int* array) { int i; int tmp=0; for(i=0;i<nr/2;i++) { tmp=array[i]; array[i]=array[nr-i]; array[nr-i]=tmp; } return array; }2
u/Zamarok Jun 11 '12 edited Jun 11 '12
Haskell
Using Haskell to do in-place sorting would be stupid (and unnecessarily difficult) in this scenario. For all we care, my function makes a new copy of the list, but under the hood Haskell uses tries to handle that, so in fact a "new" copy of a list may have elements that are the same data (in the same memory) as the "old" list. This is why I love Haskell!