Question

In: Computer Science

can you please convert this python code into java? Python code is as shown below: #...

can you please convert this python code into java?

Python code is as shown below:

# recursive function
def row_puzzle_rec(row, pos, visited):
   # if the element at the current position is 0 we have reached our goal
   if row[pos] == 0:
       possible = True
   else:
       # make a copy of the visited array
       visited = visited[:]
       # if the element at the current position has been already visited then it's a loop.
       # as then its not possible to reach the last element, set possible to False
       if visited[pos]:
           possible = False
       else:
           # set visitied for the element as True
           visited[pos] = True
           possible = False
           # if its possible to move left then recurse in the left direction
           if pos - row[pos] > 0 and row_puzzle_rec(row, pos - row[pos], visited):
               # return immediately if the goal is reached
               return True
           # if its possible to move right then recurse in the right direction
           if pos + row[pos] < len(row) and row_puzzle_rec(row, pos + row[pos], visited):
               # return immediately if the goal is reached.
               return True
   return possible

def row_puzzle(row):
   # visited array will be used to check if a particular element was visited
   # initialize the array to False
   visited = [False for item in range(len(row))]
   # second argument is the token position initialized to 0
   return row_puzzle_rec(row, 0, visited)

possible = row_puzzle([2, 4, 5, 3, 1, 3, 1, 4, 0])
print(possible)
possible = row_puzzle([1, 3, 2, 1, 3, 4, 0])
print(possible)

Solutions

Expert Solution

Java Code:

public class Main
{
    public static boolean row_puzzle_rec(int row[], int pos, boolean visited[]) {
        boolean possible;
        // if the element at the current position is 0 we have reached our goal
        if(row[pos]==0) {
            possible = true;
        }
        else {
            // make a copy of the visited array
            visited = visited;
            // if the element at the current position has been already visited then it's a loop.
            // as then its not possible to reach the last element, set possible to False
            if(visited[pos]) {
                possible = false;
            }
            else {
                // set visitied for the element as True
                visited[pos] = true;
                possible = false;
                // if its possible to move left then recurse in the left direction
                if(pos - row[pos] > 0 && row_puzzle_rec(row, pos - row[pos], visited)) { 
                    // return immediately if the goal is reached
                    return true;
                }
                // if its possible to move right then recurse in the right direction
                if(pos + row[pos] < row.length && row_puzzle_rec(row, pos + row[pos], visited)) {
                    // return immediately if the goal is reached.
                    return true;
                }
            }
        }
        return possible;
    }
        public static boolean row_puzzle(int row[]) {
            boolean visited[] = new boolean[row.length];
            // visited array will be used to check if a particular element was visited
        // initialize the array to False
            for(int i = 0; i < row.length; i++)
            visited[i] = false;
            // second argument is the token position initialized to 0
            return row_puzzle_rec(row, 0, visited);
        }
        
        public static void main(String[] args) {
                boolean possible;
                possible = row_puzzle(new int[]{2, 4, 5, 3, 1, 3, 1, 4, 0});
        System.out.println(possible);
        possible = row_puzzle(new int[]{1, 3, 2, 1, 3, 4, 0});
        System.out.println(possible);
        }
}

Output:

Please name the java file as Main.java


Related Solutions

Please convert This java Code to C# (.cs) Please make sure the code can run and...
Please convert This java Code to C# (.cs) Please make sure the code can run and show the output Thank you! Let me know if you need more information. Intructions For this assignment you will be creating two classes, an interface, and a driver program: Class Calculator will implement the interface CalcOps o As such it will implement hexToDec() - a method to convert from Hexadecimal to Decimal. Class HexCalc will inherit from Calculator. Interface CalcOps will have abstract methods...
Please convert this code written in Python to Java: import string import random #function to add...
Please convert this code written in Python to Java: import string import random #function to add letters def add_letters(number,phrase):    #variable to store encoded word    encode = ""       #for each letter in phrase    for s in phrase:        #adding each letter to encode        encode = encode + s        for i in range(number):            #adding specified number of random letters adding to encode            encode = encode +...
Can someone please convert this java code to C code? import java.util.LinkedList; import java.util.List; public class...
Can someone please convert this java code to C code? import java.util.LinkedList; import java.util.List; public class Phase1 { /* Translates the MAL instruction to 1-3 TAL instructions * and returns the TAL instructions in a list * * mals: input program as a list of Instruction objects * * returns a list of TAL instructions (should be same size or longer than input list) */ public static List<Instruction> temp = new LinkedList<>(); public static List<Instruction> mal_to_tal(List<Instruction> mals) { for (int...
Convert this code written in Python to Java: # Definition of a function isprime(). def isprime(num):...
Convert this code written in Python to Java: # Definition of a function isprime(). def isprime(num):     count=2;     flag=0;     # Loop to check the divisors of a number.     while(count<num and flag==0):         if(num%count!=0):             # Put flag=0 if the number has no divisor.             flag=0         else:             # Put flag=1 if the number has divisor.             flag=1         # Increment the count.         count=count+1     # Return flag value.     return flag # Intialize list. list=[]...
Can you convert this code (Python) to C++ def decrypt(message, key): decryptedText = "" for i...
Can you convert this code (Python) to C++ def decrypt(message, key): decryptedText = "" for i in message: M = ord(i) k = int(key, 16) xor = M ^ k decryptedText += chr(xor) return decryptedText def encrypt(message, key): encryptedText = "" for i in message: M = ord(i) k = int(key, 16) xor = M ^ k encryptedText += chr(xor) return encryptedText # main function userText = input("Enter text: ") userKey = str(input("Enter a key: ")) encryptedMessage = encrypt(userText, userKey)...
Convert the attached C++ code to working Java code. Be judicious in the change that you...
Convert the attached C++ code to working Java code. Be judicious in the change that you make. This assignment is not about re-writing or improving this code, but rather about recognizing the differences between C++ and Java, and making the necessary coding changes to accommodate how Java does things. PLEASE DO NOT use a built-in Java QUEUE (or any other) container. Additional resources for assignment: #include <iostream> #include <string> using namespace std; class pizza { public: string ingrediants, address; pizza...
Convert this code written in Python to Java: students = int(input("How many students are in your...
Convert this code written in Python to Java: students = int(input("How many students are in your class?" )) while students<0:     print("Invalid # of students, try again.")     students = int(input("How many students are in your class?" )) tests = int(input("How many tests in this class? ")) while tests<0:     print("Invalid # of tests, try again.")     tests = int(input("How many tests in this class? ")) print("Here we go!") # Here we are creating a list called class_average to store average of all students....
Complete the code so that it can convert the date to day of week using python,...
Complete the code so that it can convert the date to day of week using python, the code should pass the doctest def convert_datetime_to_dayofweek(datetime_string): """ This function takes date in the format MON DAY YEAR HH:MM(PM/AM) and returns the day of the week Assume input string is UTC    >>> convert_datetime_to_dayofweek('Jun 1 2005 1:33PM') 'Wednesday' >>> convert_datetime_to_dayofweek('Oct 25 2012 2:17AM') 'Thursday' """ # code goes here
1. Convert the following code shown below to C++ code: public class HighwayBillboard { public int...
1. Convert the following code shown below to C++ code: public class HighwayBillboard { public int maxRevenue(int[] billboard, int[] revenue, int distance, int milesRes) { int[] MR = new int[distance + 1]; //Next billboard which can be used will start from index 0 in billboard[] int nextBillBoard = 0; //example if milesRes = 5 miles then any 2 bill boards has to be more than //5 miles away so actually we can put at 6th mile so we can add...
I need convert this java code to C language. There is no string can be used...
I need convert this java code to C language. There is no string can be used in C. Thank you! import java.util.Scanner; public class Nthword { public static void main( String args[] ) { String line; int word; Scanner stdin = new Scanner(System.in); while ( stdin.hasNextLine() ) { line = stdin.nextLine(); word = stdin.nextInt(); stdin.nextLine(); // get rid of the newline after the int System.out.println( "Read line: \"" + line + "\", extracting word [" + word + "]" );...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT