Logo

Programming-Idioms

History of Idiom 19 > diff from v16 to v17

Edit summary for version 17 by :

Version 16

2015-09-04, 09:08:04

Version 17

2015-10-29, 14:05:12

Idiom #19 Reverse a list

Reverse the order of the elements of list x .
This may reverse "in-place" and destroy the original ordering.

Idiom #19 Reverse a list

Reverse the order of the elements of list x .
This may reverse "in-place" and destroy the original ordering.

Code
(reverse x)
Code
(reverse x)
Doc URL
http://clojuredocs.org/clojure.core/reverse
Doc URL
http://clojuredocs.org/clojure.core/reverse
Imports
import std.range;
Imports
import std.range;
Code
auto y = x.retro;
Code
auto y = x.retro;
Comments bubble
This doesn't allocate a new list or modify the original, but creates an iterator that traverses the list in reverse order.
Comments bubble
This doesn't allocate a new list or modify the original, but creates an iterator that traverses the list in reverse order.
Demo URL
http://dpaste.dzfl.pl/ebf4256b37c4
Demo URL
http://dpaste.dzfl.pl/ebf4256b37c4
Code
for i, j := 0, len(x)-1; i < j; i, j = i+1, j-1 {
	x[i], x[j] = x[j], x[i]
}
Code
for i, j := 0, len(x)-1; i < j; i, j = i+1, j-1 {
	x[i], x[j] = x[j], x[i]
}
Comments bubble
This loop reverts "in-place" (in the original list, not creating a new one).
Comments bubble
This loop reverts "in-place" (in the original list, not creating a new one).
Origin
http://stackoverflow.com/a/19239850/871134
Origin
http://stackoverflow.com/a/19239850/871134
Demo URL
http://play.golang.org/p/vkJg_D1yUb
Demo URL
http://play.golang.org/p/vkJg_D1yUb
Imports
import std.algorithm;
Imports
import std.algorithm;
Code
reverse(x);
Code
reverse(x);
Comments bubble
Reverses x in-place.
Comments bubble
Reverses x in-place.
Doc URL
http://dlang.org/phobos/std_algorithm.html#reverse
Doc URL
http://dlang.org/phobos/std_algorithm.html#reverse
Imports
import java.util.List;
Imports
import java.util.List;
Code
static <T> void reverse(List<T> x){
	int n = x.size();
	for(int i=0;i<n/2;i++){
		T tmp = x.get(i);
		x.set(i, x.get(n-i-1));
		x.set(n-i-1, tmp);
	}
}
Code
static <T> void reverse(List<T> x){
	int n = x.size();
	for(int i=0;i<n/2;i++){
		T tmp = x.get(i);
		x.set(i, x.get(n-i-1));
		x.set(n-i-1, tmp);
	}
}
Comments bubble
This method works for lists of any element type T .

In case of an odd number of elements, the central element doesn't need to be swapped.
Comments bubble
This method works for lists of any element type T .

In case of an odd number of elements, the central element doesn't need to be swapped.
Demo URL
http://ideone.com/kxgipq
Demo URL
http://ideone.com/kxgipq