Last active
December 16, 2015 12:38
-
-
Save moomoohk/5435828 to your computer and use it in GitHub Desktop.
Added swap method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package mishael; | |
import java.util.ArrayList; | |
import java.util.Random; | |
public class CircularArrayList<Generic> | |
{ | |
private ArrayList<Generic> a; | |
public CircularArrayList() | |
{ | |
this.a = new ArrayList<Generic>(); | |
} | |
public CircularArrayList(Generic first) | |
{ | |
this.a = new ArrayList<Generic>(); | |
this.a.add(first); | |
} | |
public CircularArrayList(Generic[] first) | |
{ | |
this.a = new ArrayList<Generic>(); | |
for (Generic temp : first) | |
this.a.add(temp); | |
} | |
public void add(Generic o) | |
{ | |
this.a.add(o); | |
} | |
public Generic get(int index) | |
{ | |
if (this.a.size() == 0) | |
return null; | |
return this.a.get(index % this.a.size()); | |
} | |
public void set(int index, Generic o) | |
{ | |
if (this.a.size() == 0) | |
return; | |
this.a.set(index % this.a.size(), o); | |
} | |
public void swap(int index1, int index2) | |
{ | |
Generic temp=get(index2); | |
set(index2, get(index1)); | |
set(index1, temp); | |
} | |
public void mixup(int swaps) | |
{ | |
for(int i=1; i<=swaps; i++) | |
swap(new Random().nextInt(this.a.size()), new Random().nextInt(this.a.size())); | |
} | |
public String toString() | |
{ | |
String st = "["; | |
if (this.a.size() != 0) | |
st += this.a.get(0).toString(); | |
else | |
return "[Empty]"; | |
for (int i = 1; i < this.a.size(); i++) | |
st += ", " + this.a.get(i).toString(); | |
st += "]"; | |
return st; | |
} | |
public static void main(String[] args) | |
{ | |
CircularArrayList<Integer> test = new CircularArrayList<Integer>(new Integer[]{ 0, 1, 2 }); | |
System.out.println(test.toString()); | |
test.swap(0, 2); | |
System.out.println(test.toString()); | |
test.swap(0, 3); | |
System.out.println(test.toString()); | |
test.mixup(10); | |
System.out.println(test.toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment