Question

In: Computer Science

JAVA write a code for Task 1 and Task 2 and pass the test cases. Imagine...

JAVA write a code for Task 1 and Task 2 and pass the test cases.

Imagine you have a rotary combination lock with many dials. Each dial has the digits 0 - 9. At any point in time, one digit from each dial is visible. Each dial can be rotated up or down. For some dial, if a 4 is currently visible then rotating the dial up would make 5 visible; rotating the dial down would make 3 visible. When 0 is the visible digit then rotating down would make 9 visible. Similarly, when 9 is visible then rotating up would make 0 visible. We have devised a robotic finger to manipulate such combination systems. The robotic finger takes as input a String that indicates the operations to be performed. An L moves the finger one dial to the left, an R moves the finger one dial to the right, and a + rotates the dial that the finger is at up and a - rotates the dial that the finger is at down.

The robotic finger always starts at the leftmost dial.

Task 1

Given a sequence of operations in String form, as well as an initial arrangement of the dials, determine the digits that will be visible after the operations have been performed.

Task 2

Given an initial state of the dials and a final state, return a String that represents a sequence of operations of shortest length that transforms the initial state to the final state.

Task 1

 @param initialState represents the state of the combination dials and {@code 0 <= initialState[i] <= 9} for all {@code 0 <= i < initialState.length}.
 * @param ops          represents the operations to perform and only contains the characters 'L', 'R', '+' and '-' or {@code ops} is empty
 * @return the new state
 */
public int[] rotate(int[] initialState, String ops) {

//code in here

}

Test cases for task 1:

int[] initialState = {7, 0, 2, 9, 1, 5, 6};
String ops = "R-R++R+++R+RR--";
int[] expectedState = {7, 9, 4, 2, 2, 5, 4};

Task2

/**
 * Transform the initial state to a given new state using the shortest sequence of operations
 *
 * @param initialState represents the initial state of the dials, and {@code 0 < initialState.length <= 10}, and {@code 0 <= initialState[i] <= 9} for all {@code 0 <= i < initialState.length}.
 * @param newState     represents the new (desired) state of the dials, and {@code 0 < initialState.length <= 10}, and {@code 0 <= initialState[i] <= 9} for all {@code 0 <= i < initialState.length}. Also {@code newState.length() == initialState.length()}.
 * @return a representation of a shortest operation sequence that ensures that the initial state is transformed to the new state.
 */
public String getRotationSequence(int[] initialState, int[] newState) {
//code in here
    return null;
}

Test cases for task 2

int[] initialState = {1, 2, 4, 4, 4, 7};
int[] finalState = {2, 7, 3, 4, 8, 9};
int expectedLength = "+R+++++R-RR++++R++".length();

Solutions

Expert Solution

Hello! :)

Here are the documented codes to solve this assignment:

Main.java:

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {

        // object to run tests on
        Robot robot = new Robot();

        // task 1
        {
            int[] initialState = {7, 0, 2, 9, 1, 5, 6};
            String ops = "R-R++R+++R+RR--";
            int[] expectedState = {7, 9, 4, 2, 2, 5, 4};
            int[] finalState = robot.rotate(initialState, ops);
            assert Arrays.equals(expectedState, finalState) : "task 1 failed";
        }

        // task 2
        {
            int[] initialState = {1, 2, 4, 4, 4, 7};
            int[] finalState = {2, 7, 3, 4, 8, 9};
            int expectedLength = "+R+++++R-RR++++R++".length();
            String rotationSequence = robot.getRotationSequence(initialState, finalState);
            assert expectedLength == rotationSequence.length() : "task 2 failed";
        }
    }
}

Robot.java:

public class Robot {
    /**
     * Determine the digits that will be visible after the operations have been performed
     *
     * @param initialState represents the state of the combination dials and {@code 0 <= initialState[i] <= 9} for all {@code 0 <= i < initialState.length}.
     * @param ops          represents the operations to perform and only contains the characters 'L', 'R', '+' and '-' or {@code ops} is empty
     * @return the new state
     */
    public int[] rotate(int[] initialState, String ops) {

        int[] finalState = initialState.clone(); // copy of initialState that will be modified and returned

        int stateID = 0; // position of robotic finger

        for(int opsID = 0; opsID < ops.length(); ++opsID) {

            char character = ops.charAt(opsID);

            switch(character) {
                case 'L':
                    --stateID; // moving left
                    break;
                case 'R':
                    ++stateID; // moving right
                    break;
                case '+':
                    finalState[stateID] = (finalState[stateID] + 1) % 10; // dialing up
                    break;
                case '-':
                    finalState[stateID] = (finalState[stateID] + 9) % 10; // dialing down
            }
        }

        return finalState;
    }

    /**
     * Transform the initial state to a given new state using the shortest sequence of operations
     *
     * @param initialState represents the initial state of the dials, and {@code 0 < initialState.length <= 10}, and {@code 0 <= initialState[i] <= 9} for all {@code 0 <= i < initialState.length}.
     * @param newState     represents the new (desired) state of the dials, and {@code 0 < initialState.length <= 10}, and {@code 0 <= initialState[i] <= 9} for all {@code 0 <= i < initialState.length}. Also {@code newState.length() == initialState.length()}.
     * @return a representation of a shortest operation sequence that ensures that the initial state is transformed to the new state.
     */
    public String getRotationSequence(int[] initialState, int[] newState) {

        StringBuilder rotationSequence = new StringBuilder(); // to store the rotation sequence

        for(int stateID = 0; stateID < initialState.length; ++stateID) {

            int initialValue = initialState[stateID];
            int newValue = newState[stateID];

            int dialUpDistance = (newValue < initialValue ? newValue + 10 : newValue) - initialValue; // number of dial ups needed at this position
            int dialDownDistance = initialValue - (newValue > initialValue ? newValue - 10 : newValue); // number of dial downs needed at this position

            // appending the moves with the minimum length
            if(dialUpDistance <= dialDownDistance) {
                rotationSequence.append(new String(new char[dialUpDistance]).replace("\0", "+"));
            } else {
                rotationSequence.append(new String(new char[dialDownDistance]).replace("\0", "-"));
            }

            // moves right
            rotationSequence.append('R');
        }

        // removing "R"s from the end if any
        while(rotationSequence.length() > 0 && rotationSequence.charAt(rotationSequence.length() - 1) == 'R') {
            rotationSequence.deleteCharAt(rotationSequence.length() - 1);
        }

        return rotationSequence.toString();
    }
}

Here is the snapshot of a demo run:

As you can see, the process exited with a zero return value, which means the code passes the assertions in both the tasks.

Hope this helps! :)


Related Solutions

Write a java code that gets student test scores from the user. Each test score will...
Write a java code that gets student test scores from the user. Each test score will be an integer in the range 0 to 100. Input will end when the user enters -1 as the input value. After all score have been read, display the number of students who took the test, the minimum score, the maximum score, the average score (with decimal point, and the number of A where an A is a score in the range 90-100.
Write a java code that: 1) Takes as an argument an integer number, say N 2)...
Write a java code that: 1) Takes as an argument an integer number, say N 2) Creates an array of size N 3) Populates the array with random numbers between 0 and 10 * N. This is, the values of the elements of the array should be random numbers between 0 and 10 * N. 4) Finally, the code outputs the index of the smallest element and the index of the largest element in the array
write a java code to calculate 1+2-3+4-5 …-99+100
write a java code to calculate 1+2-3+4-5 …-99+100
please write the java code so it can run on jGRASP Thanks! 1 /** 2 *...
please write the java code so it can run on jGRASP Thanks! 1 /** 2 * PassArray 3 * @Sherri Vaseashta 4 * @Version 1 5 * @see 6 */ 7 import java.util.Scanner; 8 9 /** 10 This program demonstrates passing an array 11 as an argument to a method 12 */13 14 public class PassArray 15 { 16 public static void main(String[] args) 17 { 18 19 final int ARRAY_SIZE = 4; //Size of the array 20 // Create...
Writing a Java Code Requirements of the JAVA program: Your task is to calculate geometric area...
Writing a Java Code Requirements of the JAVA program: Your task is to calculate geometric area for 3 shapes(square, rectangle and circle). You need to build a menu that allows users to enter options. Possible options are 'S' for square, 'R' for rectangle and 'C' for circle. HINT: you can use switch statement to switch on string input Invalid input should throw a message for the user. Example: Invalid input, please try again Each options should ask users for relevant...
Write in java The submission utility will test your code against a different input than the...
Write in java The submission utility will test your code against a different input than the sample given. When you're finished, upload all of your .java files to Blackboard. Grading: Each problem will be graded as follows: 0 pts: no submission 1 pts: submitted, but didn't compile 2 pts: compiled, but didn't produce the right output 5 pts: compiled and produced the right output Problem 1: "Letter index" Write a program that inputs a word and an unknown number of...
java code: adds a new regular task, delete a task , show all tasks, and show...
java code: adds a new regular task, delete a task , show all tasks, and show regular tasks, mark a task as important (possibly through ID), complete task, show all completed tasks, show important tasks. I also need a UML diagram for the code update: The "task" is like something in a to do list. example) task 1. name: get carrots important: no completed: yes. you can run my code as an example if needed
please write the java code so it can run on jGRASP Thanks! CODE 1 1 /**...
please write the java code so it can run on jGRASP Thanks! CODE 1 1 /** 2 * SameArray2.java 3 * @author Sherri Vaseashta4 * @version1 5 * @see 6 */ 7 import java.util.Scanner;8 public class SameArray29{ 10 public static void main(String[] args) 11 { 12 int[] array1 = {2, 4, 6, 8, 10}; 13 int[] array2 = new int[5]; //initializing array2 14 15 //copies the content of array1 and array2 16 for (int arrayCounter = 0; arrayCounter < 5;...
Task 2/2: Java program Based upon the following code: public class Main {   public static void...
Task 2/2: Java program Based upon the following code: public class Main {   public static void main( String[] args ) {     String alphabet = "ABCDEFGHIJKLMNMLKJIHGFEDCBA";     for( <TODO> ; <TODO> ; <TODO> ) {       <TODO>;     } // Closing for loop   } // Closing main() } // Closing class main() Write an appropriate loop definition and in-loop behavior to determine if the alphabet string is a palindrome or not. A palindrome is defined as a string (or more generally, a token) which...
Task 1. to be completed. 1.1 - Write a small Python snippet code that can revert...
Task 1. to be completed. 1.1 - Write a small Python snippet code that can revert an array of N element (Please do not use the default function “reverse()). 1.2 - There is a famous programming (algorithm) concept that can vastly reduce the complexity of Recursive Fibonacci Algorithm. 2 .a) What is the name of this concept 2.b) Write the execution time and memory complexity of Fibonacci sequences, once this concept is applied 2.c) Explain the main idea behind this...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT