Java 在二维数组中移动元素

Java 在二维数组中移动元素,java,arrays,multidimensional-array,Java,Arrays,Multidimensional Array,我想在空白空间中移动错误元素(就像谢林的隔离模型一样)。 这是数组..(数组中的元素是随机放置的) 位于(0,4)、(1,2)、(2,1)、(3,1)的元素为false,因为它周围没有类似的元素,或者周围没有足够的单元格我想将这些假元素移动到数组中的空白位置“”并将这些假位置设为空白“”。false元素可以移动到数组中的任何空位置,使其看起来像这样 'X' 'X' 'X' 'O' ' ' 'X' 'X' ' ' 'O' 'O' 'X' ' ' 'O' 'O' 'O' ' ' ' ' ' '

我想在空白空间中移动错误元素(就像谢林的隔离模型一样)。 这是数组..(数组中的元素是随机放置的)

位于(0,4)、(1,2)、(2,1)、(3,1)的元素为false,因为它周围没有类似的元素,或者周围没有足够的单元格我想将这些假元素移动到数组中的空白位置“”并将这些假位置设为空白“”。false元素可以移动到数组中的任何空位置,使其看起来像这样

'X' 'X' 'X' 'O' ' ' 
'X' 'X' ' ' 'O' 'O' 
'X' ' ' 'O' 'O' 'O' 
' ' ' ' ' ' ' ' ' ' 
' ' ' ' ' ' ' ' ' ' 
这就是我得到的

'X' 'X' 'X' 'O' 'X' 
'X' 'X' 'X' 'X' 'O' 
'X' 'O' 'O' 'O' 'O' 
'O' 'O' 'O' 'O' 'O' 
'' '' '' '' ''
这是我的密码

//isArrGood is a method that checks if the element is false or true
//arr is 2D array that is being passed in the method

    char[] falseCell = new char[arr.length * arr[0].length];

    for(int row=0; row<arr.length; row++){
        for(int col=0; col<arr[row].length; col++){
            if(!isArrGood(arr,row,col)){
                falseCell[row] = arr[row][col];
                arr[row][col] = ' ';
                }
            }
        }


    for(int i=0; i<arr.length; i++){
        for(int j=0; j<arr[0].length; j++){
            if(arr[i][j] == ' '){
                arr[i][j] = falseCell[i];
            }
        }
    }
//isArrGood是一种检查元素是false还是true的方法
//arr是在方法中传递的二维数组
char[]false单元格=新字符[arr.length*arr[0].length];

对于(int row=0;row您是否可以发布更多代码,即您的问题的最小、完整和可验证的示例

对于所描述的问题,您可以使用我编写的代码来学习:

import java.util.Random;

public class ShellingSegregationModel
{
    public static final int EMPTY = 0;
    public static final int BLUE  = 1;
    public static final int RED   = 2;

    // number of elements for random
    public static final int ELEMENTS = 3;

    public static final double THRESHOLD = 0.15;        

    //size of the field
    public int size;

    int[][] field;
    // temporary field for the iteration
    int[][] temporary;

    public int iteration;

    public ShellingSegregationModel(int size)
    {    
        Random random = new Random();
        this.size = size;
        field     = new int[size][size];
        for (int y = 0; y < size; y++)
        {
            for (int x = 0; x < size; x++)
            {
                field[y][x] = random.nextInt(ELEMENTS);
            }
        }
    }

    public int getSize()
    {
        return size;
    }

    public void setField(int[][] field)
    {
        this.field = field;
    }

    public int[][] getField()
    {
        return field;
    }

    public void setTemporary(int[][] temporary)
    {
        this.temporary = temporary;
    }

    public int[][] getTemporary()
    {
        return temporary;
    }

    public int getIteration()
    {
        return iteration;
    }

    public void setIteration(int iteration)
    {
        this.iteration = iteration;
    }

    public double getThreshold()
    {
        return THRESHOLD;   
    }

    //how many neighbors needed for threshold
    public double getCalculatedThreshold()
    {
        return getThreshold()*8;//8 is the neighbors count total possible
    }

    public static String getSymbolFor(int x)
    {
        String s = "";
        switch (x)
        {            
            case BLUE:
                s = "x";
                break;
            case RED :
                s = "o";
                break;
            case EMPTY:
            default:
                s = " ";                
        }
        return s;
    }

    public boolean isEmpty(int x, int y)
    {
        return get(x,y) == EMPTY;
    }

    /**
     * Prints field
     */
    public void print(String message)
    {
        System.out.println(message);
        for (int y = 0; y < getSize(); y++)
        {          
            StringBuilder row = new StringBuilder();
            for (int x = 0; x < getSize(); x++)
            {                
                row.append("'").append(getSymbolFor(get(x,y))).append("' ");
            }
            System.out.println(row.toString());
        }
    }

    public void printSameNeighorsCount(String message)
    {
        System.out.println(message);
        for (int y = 0; y < getSize(); y++)
        {          
            StringBuilder row = new StringBuilder();
            for (int x = 0; x < getSize(); x++)
            {                
                row.append("'").append(sameNeighbors(x, y)).append("' ");
            }
            System.out.println(row.toString());
        }
    }

    public int get(int x, int y)
    {
        return getField()[y][x];
    }

    private int add(boolean c)
    {
        return c ? 1 : 0;
    }

    public int sameNeighbors(int x, int y)
    {
        return isEmpty(x,y) ? 0 : 
                  add(isSame(get(x,y),x  ,y-1)) 
                + add(isSame(get(x,y),x-1,y-1))
                + add(isSame(get(x,y),x-1,y  ))
                + add(isSame(get(x,y),x-1,y+1))
                + add(isSame(get(x,y),x  ,y+1))
                + add(isSame(get(x,y),x+1,y+1))
                + add(isSame(get(x,y),x+1,y  ))
                + add(isSame(get(x,y),x+1,y-1));
    }    

    private static void copyArray(int[][] src, int[][] dest)
    {        
        for (int i = 0; i < src.length; i++)
        {
            dest[i] = new int[src[i].length];
            System.arraycopy(src[i], 0, dest[i], 0, src[i].length);            
        }                
    }
    private void duplicateToTemporary()
    {
        setTemporary(new int[getField().length][]);
        copyArray(getField(),getTemporary());
    }

    //
    private void assignFromTemporary()
    {
        setField(new int[getField().length][]);
        copyArray(getTemporary(), getField());
    }

    public void iterate(int iterations)
    {        
        for (int i = 0; i < iterations; i++)          
        {
            duplicateToTemporary();
            for (int y = 0; y < getSize(); y++)
            {
                for (int x = 0; x < getSize(); x++)
                {
                    if (!isHappy(x,y))
                    {
                        swap(x,y);
                    }
                }
            }
            assignFromTemporary();
        }
        setIteration(getIteration()+iterations);
    }

    //Swaps with empty random from temporary
    public void swap(int i, int j)
    {
        Random random   = new Random();
        boolean swapped = false;
        while (!swapped)
        {
            for (int y = 0; !swapped && y < getSize(); y++)
            {
                for (int x = 0; !swapped && x < getSize(); x++)
                {
                    //swap semi-randomly
                    if (getTemporary()[y][x] == EMPTY && random.nextBoolean())
                    {                        
                        getTemporary()[y][x] = getTemporary()[j][i];
                        getTemporary()[j][i] = EMPTY   ;
                        swapped = true;
                    }
                }
            }
        }
    }

    public boolean isHappy(int x, int y)
    {
        return getCalculatedThreshold() < sameNeighbors(x, y);        
    }

    public boolean isSame(int me, int x, int y)
    {
        return 
                //check bounds
                x >= 0 && y >= 0 && x < getSize() && y < getSize()
                //check element
                && get(x,y) == me;
    }

    public static void main(String[] args)
    {
        ShellingSegregationModel ssm = new ShellingSegregationModel(10);
        ssm.print("Randomly generated field");       
        ssm.printSameNeighorsCount("Same neighbors count");
        ssm.iterate(5);
        ssm.print("Field after 5 iterations");       
        ssm.printSameNeighorsCount("Same neighbors count");
        ssm.iterate(5);
        ssm.print("Field after 10 iterations");       
        ssm.printSameNeighorsCount("Same neighbors count");
        ssm.iterate(5);
        ssm.print("Field after 15 iterations");       
        ssm.printSameNeighorsCount("Same neighbors count");
        ssm.iterate(50);
        ssm.print("Field after 65 iterations");       
        ssm.printSameNeighorsCount("Same neighbors count");
    }
}
import java.util.Random;
公共类ShellingSegregationModel
{
公共静态final int EMPTY=0;
公共静态最终整数蓝色=1;
公共静态最终整数红色=2;
//随机变量的元素数
公共静态最终整数元素=3;
公共静态最终双阈值=0.15;
//字段大小
公共整数大小;
int[][]字段;
//迭代的临时字段
int[][]临时;
公共整数迭代;
公共ShellingSegregationModel(整数大小)
{    
随机=新随机();
这个。大小=大小;
字段=新整数[大小][大小];
对于(int y=0;yimport java.util.Random;

public class ShellingSegregationModel
{
    public static final int EMPTY = 0;
    public static final int BLUE  = 1;
    public static final int RED   = 2;

    // number of elements for random
    public static final int ELEMENTS = 3;

    public static final double THRESHOLD = 0.15;        

    //size of the field
    public int size;

    int[][] field;
    // temporary field for the iteration
    int[][] temporary;

    public int iteration;

    public ShellingSegregationModel(int size)
    {    
        Random random = new Random();
        this.size = size;
        field     = new int[size][size];
        for (int y = 0; y < size; y++)
        {
            for (int x = 0; x < size; x++)
            {
                field[y][x] = random.nextInt(ELEMENTS);
            }
        }
    }

    public int getSize()
    {
        return size;
    }

    public void setField(int[][] field)
    {
        this.field = field;
    }

    public int[][] getField()
    {
        return field;
    }

    public void setTemporary(int[][] temporary)
    {
        this.temporary = temporary;
    }

    public int[][] getTemporary()
    {
        return temporary;
    }

    public int getIteration()
    {
        return iteration;
    }

    public void setIteration(int iteration)
    {
        this.iteration = iteration;
    }

    public double getThreshold()
    {
        return THRESHOLD;   
    }

    //how many neighbors needed for threshold
    public double getCalculatedThreshold()
    {
        return getThreshold()*8;//8 is the neighbors count total possible
    }

    public static String getSymbolFor(int x)
    {
        String s = "";
        switch (x)
        {            
            case BLUE:
                s = "x";
                break;
            case RED :
                s = "o";
                break;
            case EMPTY:
            default:
                s = " ";                
        }
        return s;
    }

    public boolean isEmpty(int x, int y)
    {
        return get(x,y) == EMPTY;
    }

    /**
     * Prints field
     */
    public void print(String message)
    {
        System.out.println(message);
        for (int y = 0; y < getSize(); y++)
        {          
            StringBuilder row = new StringBuilder();
            for (int x = 0; x < getSize(); x++)
            {                
                row.append("'").append(getSymbolFor(get(x,y))).append("' ");
            }
            System.out.println(row.toString());
        }
    }

    public void printSameNeighorsCount(String message)
    {
        System.out.println(message);
        for (int y = 0; y < getSize(); y++)
        {          
            StringBuilder row = new StringBuilder();
            for (int x = 0; x < getSize(); x++)
            {                
                row.append("'").append(sameNeighbors(x, y)).append("' ");
            }
            System.out.println(row.toString());
        }
    }

    public int get(int x, int y)
    {
        return getField()[y][x];
    }

    private int add(boolean c)
    {
        return c ? 1 : 0;
    }

    public int sameNeighbors(int x, int y)
    {
        return isEmpty(x,y) ? 0 : 
                  add(isSame(get(x,y),x  ,y-1)) 
                + add(isSame(get(x,y),x-1,y-1))
                + add(isSame(get(x,y),x-1,y  ))
                + add(isSame(get(x,y),x-1,y+1))
                + add(isSame(get(x,y),x  ,y+1))
                + add(isSame(get(x,y),x+1,y+1))
                + add(isSame(get(x,y),x+1,y  ))
                + add(isSame(get(x,y),x+1,y-1));
    }    

    private static void copyArray(int[][] src, int[][] dest)
    {        
        for (int i = 0; i < src.length; i++)
        {
            dest[i] = new int[src[i].length];
            System.arraycopy(src[i], 0, dest[i], 0, src[i].length);            
        }                
    }
    private void duplicateToTemporary()
    {
        setTemporary(new int[getField().length][]);
        copyArray(getField(),getTemporary());
    }

    //
    private void assignFromTemporary()
    {
        setField(new int[getField().length][]);
        copyArray(getTemporary(), getField());
    }

    public void iterate(int iterations)
    {        
        for (int i = 0; i < iterations; i++)          
        {
            duplicateToTemporary();
            for (int y = 0; y < getSize(); y++)
            {
                for (int x = 0; x < getSize(); x++)
                {
                    if (!isHappy(x,y))
                    {
                        swap(x,y);
                    }
                }
            }
            assignFromTemporary();
        }
        setIteration(getIteration()+iterations);
    }

    //Swaps with empty random from temporary
    public void swap(int i, int j)
    {
        Random random   = new Random();
        boolean swapped = false;
        while (!swapped)
        {
            for (int y = 0; !swapped && y < getSize(); y++)
            {
                for (int x = 0; !swapped && x < getSize(); x++)
                {
                    //swap semi-randomly
                    if (getTemporary()[y][x] == EMPTY && random.nextBoolean())
                    {                        
                        getTemporary()[y][x] = getTemporary()[j][i];
                        getTemporary()[j][i] = EMPTY   ;
                        swapped = true;
                    }
                }
            }
        }
    }

    public boolean isHappy(int x, int y)
    {
        return getCalculatedThreshold() < sameNeighbors(x, y);        
    }

    public boolean isSame(int me, int x, int y)
    {
        return 
                //check bounds
                x >= 0 && y >= 0 && x < getSize() && y < getSize()
                //check element
                && get(x,y) == me;
    }

    public static void main(String[] args)
    {
        ShellingSegregationModel ssm = new ShellingSegregationModel(10);
        ssm.print("Randomly generated field");       
        ssm.printSameNeighorsCount("Same neighbors count");
        ssm.iterate(5);
        ssm.print("Field after 5 iterations");       
        ssm.printSameNeighorsCount("Same neighbors count");
        ssm.iterate(5);
        ssm.print("Field after 10 iterations");       
        ssm.printSameNeighorsCount("Same neighbors count");
        ssm.iterate(5);
        ssm.print("Field after 15 iterations");       
        ssm.printSameNeighorsCount("Same neighbors count");
        ssm.iterate(50);
        ssm.print("Field after 65 iterations");       
        ssm.printSameNeighorsCount("Same neighbors count");
    }
}