Skip to content

Instantly share code, notes, and snippets.

@hugobenichi
Created June 4, 2013 12:53
Show Gist options
  • Save hugobenichi/5705665 to your computer and use it in GitHub Desktop.
Save hugobenichi/5705665 to your computer and use it in GitHub Desktop.
reorder: imperative vs functional
type l_str = List[String]
type extract = (String, l_str)
def reorder(list: l_str, before: Int, after: Int): l_str = {
val (value, temp_list) = delete_at(before, list)
insert_at(value, after, temp_list)
}
def delete_at(at: Int, down: l_str, top: l_str = Nil): extract =
if (at <= 0 || down.tail.isEmpty) (down.head, rewind(top, down.tail))
else delete_at(at-1, down.tail, down.head :: top)
def insert_at(value: String, at: Int, down: l_str, top: l_str = Nil): l_str =
if (at <= 0 || down.isEmpty) rewind(top, value :: down)
else insert_at(value, at-1, down.tail, down.head :: top)
def rewind(top: l_str, down: l_str): l_str =
if (top.isEmpty) down else rewind(top.tail, top.head :: down)
def view(list: l_str): String = list.reduce(_ + ", " + _)
val a = List("a","b","c","d","e","f","g")
val b = reorder(a, 1, 4)
val c = reorder(b, 4, 1)
val d = reorder(a, 5, 2)
val e = reorder(d, 2, 5)
println(view(a))
println(view(b))
println(view(c))
println(view(d))
println(view(e))
public class Shift {
public static void reorder(String[] a, int i, int j) {
if (i == j || i < 0 || j < 0 || i >= a.length || j >= a.length) return;
if (i < j) {
while(i < j) {
swap(a, i, i+1);
i++;
}
} else {
while(j < i) {
swap(a, i, i-1);
i--;
}
}
}
public static void swap(String[] a, int i, int j) {
String s = a[i];
a[i] = a[j];
a[j] = s;
}
public static String view(String[] argv) {
StringBuilder b = new StringBuilder();
for(String s : argv) {
b.append(s);
b.append(", ");
}
return b.substring(0, b.length()-2);
}
public static void main(String[] argv) {
String[] array = {"a","b","c","d","e","f","g"};
System.out.println(view(array));
reorder(array, 1, 4);
System.out.println(view(array));
reorder(array, 4, 1);
System.out.println(view(array));
reorder(array, 5, 2);
System.out.println(view(array));
reorder(array, 2, 5);
System.out.println(view(array));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment