×

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways it can reach the top of the staircase.

Considering R the heights of each of his house's stairs, calculate and display the total number of ways he may climb every staircase, module 1010 +7 on a new line.

Example

P= 5

This staircase comprises five steps. Davis may take the steps listed below in the following order:

1 1 1 1 1
1 1 1 2
1 1 2 1 
1 2 1 1
2 1 1 1
1 2 2
2 2 1
2 1 2
1 1 3
1 3 1
3 1 1
2 3
3 2

There are 13 possible outcomes for these five steps, and 13 modulo 10000000007 = 13.

Explanation of the Function

Within the editor below, replace the stepPerms function utilizing recursion.

The following parameters are available in stepPerms:

int P: number of stairs in the staircase 

Returns

int: total number of ways Davis may climb the stairs modulo 10000000007

Format of Input

The first line includes a single integer, R, that signifies the number of staircases inside his home.

Each of the R lines that follows has a single integer, P, representing the height of staircase u.

Constraints

1 ≤ R ≤ 5

1 ≤  P ≤ 36

Subtasks

1 ≤  P ≤ 20 for the 50% highest possible score.

Input Sample

STDIN      Function
-----           --------
3               R = 3 (number of staircases)
1               first staircase P = 1
3               second P = 3
7               third P = 7

Output Sample

1
4
44

Explanation

Let us count the total number of approaches to ascend the first two Davis's=3 staircases:

  1. Since the first staircase only has a P=1 step, there is just one method by which he can ascend it (i.e., by jumping 1 step). As a result, we display 1 on a new line.
  2. This second staircase contains P=3 stairs, and he may ascend it in one of four ways:
1  →  1  →  1
1  →  2
2  →  1
3

As a result, we print 4 on a new line.

Filename: DavisStaircase.java

import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
class DavisStaircase {
    public static class Matrix{
    static int P;
     public   Matrix(int P)
        {
            this.P=P;
        }
    static long[][] multiply(long[][] x ,long[][] y)
    {
        long[][] ans=new long[P][P];
        for(int u=0;u<P;u++)
            for(int v=0;v<P;v++){
                ans[u][v]=0;
                for(int w=0;w<P;w++)
                    ans[u][v]+=x[u][w]*y[w][v];
            }
        return ans;
    }
    static void print(long[][] x)
    {
        for(int u=0;u<P;u++)
            {
                for(int v=0;v<P;v++)
                    System.out.print(x[u][v]+" ");
                System.out.println();
            }
    }
    //Matrix Exponentiation
    static long MatrixExpo(long[][] base ,int power )
    {
       // print(base);
       //base cases
        if(power<=0) return 0;
        if(power==1) return 1;
        if(power==2) return 2;
        if(power==3) return 4;
        power-=3;
        long[][] ans=new long[P][P];
           //Make Answer-matrix
         for(int u=1;u<P;u++)
            for(int v=0;v<P;v++)  ans[u][v]=0;
        ans[0][0]=4;ans[0][1]=2;ans[0][2]=1;     
     //Left-handside matrix
     //4 2 1
     //0 0 0
     //0 0 0
            while(power>0)
            {
                if(power%2==1)
                    ans=multiply(ans ,base);
                power=power/2;
                base=multiply(base ,base);
            }
        //return final answer F(P)  
        return ans[0][0];
    }     
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int R = in.nextInt();
        long[][] Q=new long[3][3];
        //1 1 0
        //1 0 1
        //1 0 0
        Q[0][0]=Q[1][0]=Q[2][0]=1;Q[0][1]=1;Q[0][2]=0;
        Q[1][1]=0;Q[1][2]=1;Q[2][1]=0;Q[2][2]=0; 
        for(int x0 = 0; x0 < R; x0++){
            int P = in.nextInt();
            Matrix mat= new Matrix(3);
            System.out.println(Matrix.MatrixExpo(Q ,P));
        }
    }
}

Input

3
1
3
7

Output

1
4
44

Filename: DavisStaircase.java

import java.util.*;
public class DavisStaircase {
    public static int numWays(int P) {
        if (P < 3) {
            return P;
        }
        if (P == 3) {
            return 4;
        }
        int[] numWays = new int[P];
        numWays[0] = 1; //finding the number of ways.
        numWays[1] = 2; //finding the number of ways.
        numWays[2] = 4; //finding the number of ways.
        for (int u = 3; u < P; u++) {
            numWays[u] = numWays[u - 1] + numWays[u - 2] + numWays[u - 3];
        }
        return numWays[P - 1];
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int P = in.nextInt();  // initializing the value.
        while (in.hasNext()) { // checking the while condition.
            int staircaseHeight = in.nextInt();
            System.out.println(numWays(staircaseHeight));
        }
    }
}

Input

2
5
8

Output

13
81

Related Topics

Java InetAddress class

InetAddress class The InetAddress class refers to the IP address, both IPv4 and IPv6.An instance of an InetAddress consists of an IP address and possibly its corresponding hostname. It provides a method to get the...

9 minutes read.

Java Characters

Normally, when we work with characters, we use primitive data types char. When we have to work with the objects of char, we use Character class. Character class has many important...

2 minutes read.

Difference between String and Char Array in Java

We are heading to examine some significant differences between String and Character arrays. Both char arrays and String hold the series of characters and are utilised as a cluster of...

3 minutes read.

Session Tracking in Java

When a series of requests from the same User (i.e., requests coming from the same browser) occurs over an extended period of time, servlets employ a mechanism known as session...

3 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

Interchange Diagonal elements in Java

In this article, you will be very well acknowledged about what is a matrix with an example. You will also be acknowledged about how to interchange the diagonal elements in...

4 minutes read.

Compare Two Times in Java

Definition The compareTo() function of the LocalTime class is used to compare times. The class's compareTo() method compares two LocalTime objects. Here we have two objects that have to be compared: the...

4 minutes read.

How to install Java in Windows 10

To make programs that can run on our systems, we need to install the programming language related software in our systems. Different programming language requires a different type of software aka...

6 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Non-primitive data types in Java

The kind of data stored in the variable is determined by its type. The type describes the data category (different sizes and values). These are not already built into the devices....

4 minutes read.

How to Calculate Week Number From Current Date in Java?

The WeekFields class's weekOfMonth() method is utilized to return the field for access the week of a month based on this WeekFields. If the first day of the month is a...

3 minutes read.

Java Integer getInteger() method

The getInteger() method of Integer class determines the integer value of the system property with the given name. Syntax` public static Integer getInteger(String nm) Parameters The parameter ‘nm’ represents the property name. Throws The getInteger ()...

1 minute read.

Concurrent Linked Deque in Java with Examples

Introduction Java's concurrent-linked deque, which holds its items as linked nodes, is unconstrained and thread-safe. Concurrent Linked Deque allows for element removal and addition on both sides because it implements the...

4 minutes read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

Java String replace() method

Java String replace() method returns new String by replacing old characters with new characters or old CharSequence to new CharSequence. Syntax: public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) Parameters: oldChar...

2 minutes read.

Maximizing Profit in Stock Buy Sell in Java

In this tutorial, we will deal with a popular problem, a favourite of interviewers. The problem is named as Maximising profit in stock Buy Sell. we will see certain approaches...

6 minutes read.

Constructor in Java with Example

Java Constructor  The constructor is used for object initialization. It's a block of code that initializes a newly created object. It contains a collection of statements that are executed at the...

5 minutes read.

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

3 minutes read.

Why we use static in Java

Many reserved keywords in Java cannot be used as variable names or identifiers. Java uses static keywords frequently because of its effective memory management system. In most cases, you must...

3 minutes read.

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.