We have 7 shirts in a random order, say 3 4 5 7 1 6 2. We can perform 4 operations on them. In each operation, the removed shirt is placed in the gap made.
- Remove the middle shirt and move the adjacent 3 shirts to the right.
- Remove the middle shirt and move the adjacent 3 shirts to the left.
- Remove the leftmost shirt and move the adjacent 3 shirts to the the left.
- Remove the rightmost shirt and move the adjacent 3 shirts to the right.
Given 7 shirts in random order, find the minimum number of operations required to put the shirts in serial order, i.e. , 1 2 3 4 5 6 7.
I tried a solution using permutations but that fails beyond 7 operations.
This is my solution:
import java.util.*;
class shirt2 {
public static void main(String[] ar)
{
Scanner sc = new Scanner(System.in);
String n = sc.next();
if(n.equals("1234567"))
{
System.out.println("0");
System.exit(0);
}
for(int i = 1; ; i++)
{
PermutationsWithRepetition gen = new PermutationsWithRepetition("1234",i);
List<String> v = gen.getVariations();
for(String j : v)
{
String t = n;
for(int k = 0;k < j.length(); k++)
{
int l = j.charAt(k) - '0';
t = operation(t,l);
}
if(t.equals("1234567"))
{
System.out.println(i + "\t" + j);
System.exit(0);
}
}
}
}
public static String operation(String t, int l)
{
if(l == 1)
return "" + t.charAt(3) + t.substring(0,3) + t.substring(4);
else if(l == 2)
return t.substring(0,3) + t.substring(4) + t.charAt(3);
else if(l == 3)
return t.substring(1,4) + t.charAt(0) + t.substring(4);
else
{
return t.substring(0,3) + t.charAt(6) + t.substring(3,6);
}
}
}
public class PermutationsWithRepetition {
private String a;
private int n;
public PermutationsWithRepetition(String a, int n) {
this.a = a;
this.n = n;
}
public List<String> getVariations() {
int l = a.length();
int permutations = (int) Math.pow(l, n);
char[][] table = new char[permutations][n];
for (int x = 0; x < n; x++) {
int t2 = (int) Math.pow(l, x);
for (int p1 = 0; p1 < permutations;) {
for (int al = 0; al < l; al++) {
for (int p2 = 0; p2 < t2; p2++) {
table[p1][x] = a.charAt(al);
p1++;
}
}
}
}
List<String> result = new ArrayList<String>();
for (char[] permutation : table) {
result.add(new String(permutation));
}
return result;
}
public static void main(String[] args) {
PermutationsWithRepetition gen = new PermutationsWithRepetition("abc", 3);
List<String> v = gen.getVariations();
for (String s : v) {
System.out.println(s);
}
}