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 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 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...
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...
PLEASE CODE IN JAVA In this assignment you will write a program in that can figure...
PLEASE CODE IN JAVA In this assignment you will write a program in that can figure out a number chosen by a human user. The human user will think of a number between 1 and 100. The program will make guesses and the user will tell the program to guess higher or lower.                                                                   Requirements The purpose of the assignment is to practice writing functions. Although it would be possible to write the entire program in the main function, your...
Please can you draw a flow chart for the following code : Program code for Payroll,java:...
Please can you draw a flow chart for the following code : Program code for Payroll,java: public class Payroll { public Payroll(String name,int ID,double payRate) { this.name=name; this.ID=ID; this.payRate=payRate; } private String name; private double payRate,hrWorked; private int ID; public Payroll() { name="John Doe"; ID=9999; payRate=15.0; hrWorked=40; } public String getName() { return name; } public int getID() { return ID; } public void setPayRate(int payRate) { this.payRate=payRate; } public void setHrWorked(double hrWorked) { this.hrWorked=hrWorked; } public double getPayRate() {...
Can you please add comments to this code? JAVA Code: import java.util.ArrayList; public class Catalog {...
Can you please add comments to this code? JAVA Code: import java.util.ArrayList; public class Catalog { String catalog_name; ArrayList<Item> list; Catalog(String cs_Gift_Catalog) { list=new ArrayList<>(); catalog_name=cs_Gift_Catalog; } String getName() { int size() { return list.size(); } Item get(int i) { return list.get(i); } void add(Item item) { list.add(item); } } Thanks!
PYTHON PLEASE!! ALSO: if you can include an explanation of what the code means that would...
PYTHON PLEASE!! ALSO: if you can include an explanation of what the code means that would be appreciated 8.19 LAB*: Program: Soccer team roster (Dictionaries) This program will store roster and rating information for a soccer team. Coaches rate players during tryouts to ensure a balanced team. (1) Prompt the user to input five pairs of numbers: A player's jersey number (0 - 99) and the player's rating (1 - 9). Store the jersey numbers and the ratings in a...
It's Java; the code should be the same as the output sample below; please, thank you....
It's Java; the code should be the same as the output sample below; please, thank you. Note: create a single-file solution that has multiple class definitions. Also, note that the static main() method should be a member of the Vehicle class. Create a class called Vehicle that has the manufacturers name (type String), number of cylinders in the engine (type int), and owner (type Person given next). Then, create a class called Truck that is derived from Vehicle and has...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT