Created
April 16, 2016 01:10
-
-
Save guyhughes/93bc628813a48789c70c8f8c32bfdd84 to your computer and use it in GitHub Desktop.
ITI1121 Apirl 2014 question 7 exam
This file contains hidden or 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
import java.util.List; | |
import java.util.LinkedList; | |
import java.util.Iterator; | |
import java.util.Random; | |
class Tuple { | |
private final char c; | |
private boolean visited; | |
public Tuple(char c){ | |
this.c = c; | |
visited = false; | |
} | |
public void toggle() { visited = !visited; } | |
public boolean visited() { return visited; } | |
public char getChar() { return c; } | |
public String toString() { | |
if(visited) | |
return "("+c+",t)"; | |
return "("+c+",f)"; | |
} | |
} | |
public class Frequency { | |
public static void frequency(List<Tuple> l ){ | |
while(true){ | |
final Iterator<Tuple> iter = l.iterator(); | |
char c = 0; | |
int count = 0; | |
while(iter.hasNext()){ | |
final Tuple e = iter.next(); | |
if(e.visited()) | |
continue; | |
if(c==0) | |
c = e.getChar(); | |
else if (c != e.getChar()) | |
continue; | |
e.toggle(); // here we know c == e.getChar() | |
count++; | |
} | |
if(c==0) | |
break; | |
System.out.print(c + ": "+ count+ " "); | |
} | |
} | |
private static Random r = new Random(System.currentTimeMillis()); | |
public static void main(String[] a){ | |
List<Tuple> l = new LinkedList<Tuple>(); | |
for(int i=0; i < 10; ++i){ | |
l.add(new Tuple((char)(r.nextBoolean()?'A':('a'+r.nextInt(26))))); | |
} | |
System.out.println(); | |
System.out.println(l); | |
System.out.println(); | |
System.out.println(); | |
frequency(l); | |
System.out.println(); | |
System.out.println(); | |
frequency(l); | |
System.out.println(); | |
System.out.println(); | |
System.out.println(l); | |
System.out.println(); | |
System.out.println(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment