First time poster, long time lurker.
Java
package challenge.easy236;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class TetrisPieceGeneratorSmall{
private static List<Character> pieces = Arrays.asList('O', 'I', 'S', 'Z', 'L', 'J', 'T');
private static int piecesWanted = 50;
public static void main(String[] args){
String generatedPieces = generate();
System.out.println("Generated Pieces: " + generatedPieces);
System.out.println("Are Generated Pieces Valid? " + verify(generatedPieces));
}
private static String generate(){
List<Character> bag = new ArrayList<Character>(pieces.size());
String output = "";
Random random = new Random();
for (int piecesGenerated = 0; piecesGenerated < piecesWanted; piecesGenerated++){ //Keep on grabbing pieces until 50 pieces have been generated.
if (!bag.isEmpty()) { //Grab a piece from the bag if it still has a piece within.
output += bag.remove(random.nextInt(bag.size())); //Add a random removed piece from the bag to the output.
}
else{
bag.addAll(pieces); //Refill bag.
}
}
return output;
}
private static boolean verify(String toVerify){
List<String> bags = new ArrayList<String>();
String currentBag = "";
for (int i = 0; i < toVerify.length(); i++){ //For every character in the toVerify string.
if (currentBag.length() < pieces.size()) { //If the current bag is smaller then the default bag size.
currentBag += toVerify.charAt(i); //Add current piece in toVerify string to current bag.
}
else{ //Bag is complete.
bags.add(currentBag); //Add current bag to list of bags.
currentBag = "" + toVerify.charAt(i); //Set current bag to current character only.
}
}
if (currentBag != "") { //If there are any leftover pieces in current bag.
bags.add(currentBag); //Add last leftover pieces to bag list.
}
for (String bag : bags){ //For every bag collected.
for (Character piece : bag.toCharArray()){ //For every piece within current bag (Piece1)
for (int i = 0; i < bag.length(); i++){ //For every piece within current bag (Piece2)
if (bag.indexOf(piece) != i && piece.equals(bag.charAt(i))) { //If the location of Piece1 is not the same as Piece2 and Piece1 is the same as Piece2
return false;
}
}
}
}
return true; //The string has no bags with duplicate characters, so it's valid!
}
}