Question

In: Computer Science

Create a swap method without a temporary variable. Implement an algorithm to figure out if someone...

  1. Create a swap method without a temporary variable.

  2. Implement an algorithm to figure out if someone has won a game of tic-tac-toe.

import java.util.Arrays;

public class ArrayReview {

    private int data[];

    public ArrayReview(int n) {
        data = new int[n];

        for (int i = 0; i < n; i++) {
            data[i] = (int) (Math.random() * 100);
        }
    }

    public int[] getData() {
        return data;
    }

    public void setData(int[] data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return Arrays.toString(data);
    }

    public void setKthItem(int k, int item) {
        if (k < 0 || k >= data.length) {
            return;
        }
        data[k] = item;
    }

    public int pickMaxIndex(int arr[], int start, int end) {
        int max = start;
        for (int i = start + 1; i <= end; i++) {
            if (arr[i] > arr[max]) {
                max = i;
            }
        }
        return max;
    }

    public void swap(int arr[], int i, int j) {
        if (arr[i] == arr[j]) {
            return;
        }
        arr[i] = arr[i] + arr[j];
        arr[j] = arr[i] - arr[j];
        arr[i] = arr[i] - arr[j];
    }

    public void selectionSort() {
        int i, j, max_index;
        int n = data.length;

        for (i = 0; i < n - 1; i++) {
            max_index = i;
            for (j = i + 1; j < n; j++)
                if (data[j] > data[max_index])
                    max_index = j;

            swap(data, max_index, i);
        }
    }

    public static void main(String[] args) {
        ArrayReview array = new ArrayReview(10);
        System.out.println(array);

        System.out.println("After sorting: ");
        array.selectionSort();
        for (int i : array.getData()) {
            System.out.printf("%-4d", i);
        }
        System.out.println();
    }

}

Solutions

Expert Solution

CODE

public void swap(int arr[], int i, int j) {
        if (arr[i] == arr[j]) {
            return;
        }
        arr[i] = arr[i] + arr[j];
        arr[j] = arr[i] - arr[j];
        arr[i] = arr[i] - arr[j];
    }

CODE

class TicTacToe
{
        public static final int X = 1, O = -1;
        public static final int EMPTY = 0;
        
        public int player = X;
        private int[][] board = new int[3][3];
        public boolean isEmpty = false;
        
        public void putSign(int x, int y)
        {
                if(x<0 || x>2 || y<0 || y>2)
                {
                        System.out.println("Invalid board position");
                        return;
                }
                if(board[x][y] != EMPTY)
                {
                        System.out.println("Board position occupied");
                        return;
                }
                board[x][y] = player;
                player = -player;
        }
        
        public boolean isWin(int player)
        {
                return ((board[0][0] + board[0][1] + board[0][2] == player*3) ||
                                (board[1][0] + board[1][1] + board[1][2] == player*3) ||
                                (board[2][0] + board[2][1] + board[2][2] == player*3) ||
                                (board[0][0] + board[1][0] + board[2][0] == player*3) ||
                                (board[0][1] + board[1][1] + board[2][1] == player*3) ||
                                (board[0][2] + board[1][2] + board[2][2] == player*3) ||
                                (board[0][0] + board[1][1] + board[2][2] == player*3) ||
                                (board[2][0] + board[1][1] + board[0][2] == player*3));
        }
        
        public void displayWinner()
        {
                if(isWin(X))
                {
                        System.out.println("\n X wins...!!");
                        isEmpty=false;
                }
                else if(isWin(O))
                {
                        System.out.println("\n O wins...!!");
                        isEmpty=false;
                }
                else
                {
                        if(!isEmpty)
                        {
                                System.out.println("its a tie");
                        }
                        
                }
        }
        
        public String toString()
        {
                StringBuilder s = new StringBuilder();
                isEmpty = false;
                for(int i=0;i<3;i++)
                {
                        for(int j=0;j<3;j++)
                        {
                                switch(board[i][j])
                                {
                                case X: 
                                        s.append(" X ");
                                        break;
                                case O: 
                                        s.append(" O ");
                                        break;
                                case EMPTY: 
                                        s.append("   ");
                                        isEmpty=true;
                                        break;
                                }
                                if(j<2)
                                {
                                        s.append("|");
                                }
                                
                        }
                        if(i<2)
                        {
                                s.append("\n-----------\n");
                        }
                }
                return s.toString();
        }
}

Related Solutions

(50’) Implement Quick-Sort algorithm in quickSort.cpp, where you are expected to implement three functions, swap(), partition()...
(50’) Implement Quick-Sort algorithm in quickSort.cpp, where you are expected to implement three functions, swap(), partition() and quickSort(). You are expected to call swap() within partition(), to call partition() within quickSort(), and you are not expected to declare/ implement other additional functions nor change the main() function. OPTIONAL: If you don’t need/ want to use swap() in your implementation, that is fine. Just delete/ comment it. quickSort.cpp #include <iostream> using namespace std;    // A helper function to facilitate swapping...
Is it possible to figure out, WITHOUT THE USE OF GRAPH, if the sample of a...
Is it possible to figure out, WITHOUT THE USE OF GRAPH, if the sample of a data comes from Normal Distribution? If it is possible that by doing some kind of mathematical calculation we can find if a distribution is normal or not? If you could share some example(s), that would be great.
How to make an array without setting size?c++ cant figure this out without wanting to make...
How to make an array without setting size?c++ cant figure this out without wanting to make a vector or set a fixed size to the numbers. Prompt the user to ask how many numbers you wish to read. Then based on that fill out the elements of one dimensional array with integer numbers. Then sort the numbers and print the original and sorted numbers in ascending order side by side.
Hello i need someone to implement in JAVA a radix sort algorithm forsorting strings in ascending...
Hello i need someone to implement in JAVA a radix sort algorithm forsorting strings in ascending order. The input to your algorithm should be a (multi)set S = [S1, S2, . . . , Sn] of strings each of which is of length m over the English alphabet [A…Z, a…z]. The output should be the set sorted in ascending lexicographical order. Number of strings is >= 100 and number of characters >= 50 i need the answer fast please
a)You meet a special someone after this course, and they figure out that you are now...
a)You meet a special someone after this course, and they figure out that you are now an amateur economist. Then, in a moment when the relationship is starting to take off, the crucial question comes: “I’ve heard a lot about this Adam Smith guy. Why was he so important for modern economics?” What is your answer? b)What is economics? c) So, what is macroeconomics?
Please write a Java algorithm solving the following problem: Implement a Java method to check if...
Please write a Java algorithm solving the following problem: Implement a Java method to check if a binary tree is balanced. For this assignment, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one. 1. First, please create the following two classes supporting the Binary Tree Node and the Binary Tree: public class BinTreeNode<T> { private T key; private Object satelliteData; private BinTreeNode<T> parent;...
Implement a method that does the following: (a) Create a Map data structure to hold the...
Implement a method that does the following: (a) Create a Map data structure to hold the associations between player name (key) and team affiliation (value) (b) Add at least 5 mappings to the map (c) Print out the current roster of mappings (d) Assuming some time has passed, change some of the mappings to simulate the players changing their affiliations (e) Again, print out the current roster of mappings 3. Implement a main method that calls the above methods, demonstrating...
I can't seem to figure out what the hybridization of PF6(-) is. could someone explain how...
I can't seem to figure out what the hybridization of PF6(-) is. could someone explain how to find it correctly for me?
Create a method named stringOperations () that accepts a string variable. This method must perform the...
Create a method named stringOperations () that accepts a string variable. This method must perform the following operations:                Split the sentence into an array                Display each element in the array on a seprate line using “ForEach”                Print the first element in the array, using the array syntax                Tell the user where the second word starts                Display the first 3 characters of the second word In your man method, ask the user to enter a sentence...
Program in Java Create a class and name it MyArray and implement following method. * NOTE:...
Program in Java Create a class and name it MyArray and implement following method. * NOTE: if you need more methods, including insert(), display(), etc. you can also implement those. Method name: getKthMin(int k) This method receives an integer k and returns k-th minimum value stored in the array. * NOTE: Items in the array are not sorted. If you need to sort them, you can implement any desired sorting algorithm (Do not use Java's default sorting methods). Example: Items...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT