This code shows "Terminated due to timeout" error on some large inputs on Hackerrank but works fine for the rest of the cases. Help me improve this code please.
John Watson performs an operation called a right circular rotation on an array of integers, . After performing one right circular rotation operation, the array is transformed from to .
Watson performs this operation times. To test Sherlock's ability to identify the current element at a particular position in the rotated array, Watson asks queries, where each query consists of a single integer, , for which you must print the element at index in the rotated array (i.e., the value of ).
Input Format
The first line contains space-separated integers, , , and , respectively.
The second line contains space-separated integers, where each integer describes array element (where ).
Each of the subsequent lines contains a single integer denoting .
Constraints
Output Format
For each query, print the value of the element at index of the rotated array on a new line.
Sample Input
3 2 3
1 2 3
0
1
2
Sample Output
2
3
1
MY CODE
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int n,k,q,temp=0,c=0;
Scanner sc=new Scanner(System.in);
try{
n=sc.nextInt();
k=sc.nextInt();
q=sc.nextInt();
int[] arr=new int[n];
int qrr[]=new int[q];
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
while(sc.hasNext()){
qrr[c++]=sc.nextInt();
}
for(int j=1;j<=k;j++){
temp=arr[n-1];
for(int i=n-2;i>=0;i--){
arr[i+1]=arr[i];
}
arr[0]=temp;
}
for(int i=0;i<q;i++){
System.out.println(arr[qrr[i]]);
}
}
catch(Exception ae){
System.out.println(ae.getMessage());
}
}
}
import java.io.*;
import java.util.*;
public class Solution {
public static int m,n,k,q,i=0,c=0;
public static int errorflag = 0;
public static int array[];
public static int rotated[];
public static Scanner in = new Scanner(System.in);
public static int[] getArray(int n){
array = new int[n];
for(i=0;i<n;i++){
array[i] = in.nextInt();
}
return(array);
}
public static int[] rotate(int[] original){
int[] rotated = new int[original.length];
for(i=0;i<original.length;i++){
rotated[(i+k)%original.length] = original[i];
}
return(rotated);
}
The above function works with a worst case O(n) complexity.
Basically what you're doing is assigning a new index for the elements such that they are right rotated or incremented by an amount k and the overflow is taken care of by the modulus operation.
public static void main(String[] args) {
n = in.nextInt();
k = in.nextInt();
q = in.nextInt();
array = getArray(n);
int m[] = new int[q];
for(i=0;i<m.length;i++){
m[i] = in.nextInt();
}
rotated = rotate(array);
for(i=0;i<m.length;i++){
System.out.println(rotated[m[i]]);
}
}
}
Related
I'm in the process of making a program that can take the #'s from a credit card and check to see if it's valid.
here is my code so far:
import java.util.Scanner;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader=new Scanner(System.in);
System.out.println("Please enter your credit card #");
String Ccard=reader.nextLine();
int length=Ccard.length();
doubleDig(Ccard,length);
int []digits=doubleDig(Ccard,length);
/*for(int x=0;x<digits.length;x++){
System.out.println(digits[x]);
}test array*/
}
public static int[] doubleDig(String cardNum,int length){
int []nums=new int[length];
for(int x=0;x<cardNum.length();x++){
nums[x]=cardNum.charAt(x);
System.out.println(cardNum.charAt(x));
}//makes array
//System.out.println(nums.length);
for(int x=nums.length;x<0;x-=2){
nums[x]=nums[x]*2;
}
return nums;
}//end doubleDig
}
I went to see if the array was set up correctly so I used:
System.out.println(nums[x]); in the loop but got values that I didn't understand. I then went and used:
System.out.println(cardNum.charAt(x)); in the loop to see what was up.
I then noticed that the array was somehow being displayed a 2nd time. The size of the array should be equal to the length of the string the user put in (I'm using 5491946915444920 as my test value), which is 16 in this case. 16 numbers display, but then it loops over itself again somehow and the values display a 2nd time(displaying 32 total #'s). Any clues?
you can use this:
public static int[] doubleDig(String cardNum, int length) {
int[] nums = new int[length];
int num;
for (int x = 0; x < cardNum.length(); x++) {
nums[x]=Integer.parseInt(cardNum.substring(x, x+1));
}
System.out.println(nums.length);
return nums;
}
Because at this line of code nums[x] = cardNum.charAt(x); you are actually printing char values i.e [53, 52, 57,etc] for 5491946915444920
I want to write a program which reverses all the integers entered in an array but my code displayed here isn't working properly. Here is my code:
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) throws Exception {
//code
Scanner ss=new Scanner(System.in);
int[] arr = new int[31];
int T=ss.nextInt();
int rem,p=0;
for(int i=1;i<=T;i++){
int a=ss.nextInt();
if(a<=1000000000){
while(a!=0){
rem=a%10;
p=p*10+rem;
a=a/10;
}
System.out.println(p);
} else
System.out.println("wrong input");
}
}
}
input:
2
56
78
expected output:
65
87
actual output:
65
6578
What is wrong?
Possible solution could be
if(a<=1000000000){
p=0; // reinitialize p
while(a!=0){
rem=a%10;
p=p*10+rem;
a=a/10;
}
For better understanding just add this line System.out.println("P is :"+ p); in if and you will see why p=0; was required.
if(a<=1000000000){
System.out.println("P is :"+ p);
while(a!=0){
rem=a%10;
p=p*10+rem;
a=a/10;
}
OutPut:
2
65
P is :0
56
78
P is :56
5687
There are couple of mistakes in your code (arguably), if reviewed by peer. You are trying to print p, which is not being re-initialized. Lot of unused variables in your code are removed in this answer.
You just declared an array, but never used in your program. Not sure whether you wanted to store the user inputs in the array and once all the inputs are received, you might want to compute the reverse and display or compute the reverse and store them in your array directly. So, I just removed it
The check a <= 1000000000 I believe is to ensure that values entered are within int range. Java provides you a constant for this in Integer wrapper class, Integer.MAX_VALUE (which is 2^31 - 1)
The code was lacking modularity. Hence, I extracted it to the method reverse(int num) which takes care of computation
Importing all classes from the package is not recommended, rather import only those classes that are used in your code.
import java.util.Scanner;
public class GFG {
public static void main(String[] args) throws Exception {
Scanner ss = new Scanner(System.in);
int T = ss.nextInt();
for (int i = 1; i <= T; i++) {
int a = ss.nextInt();
if (a <= Integer.MAX_VALUE) {
a = reverse(a);
System.out.println(a);
} else {
System.out.println("wrong input");
}
}
}
private static int reverse(int num) {
int reverse = 0;
while( num != 0 ) {
reverse = reverse * 10;
reverse = reverse + num % 10;
num = num/10;
}
return reverse;
}
}
On a side note, if you look at GhostCat's answer of converting the number to String and reversing it, the approach fails for negative numbers.
Example: When user input is -51, the output would be 15-
However, it is common practice in industry to store certain long values as String. One such example is credit/debit card numbers
Probably you are just learning how to do things; thus you want to solve this problem "mathematically", but there is a different perspective in here.
It seems that you simply want to reverse the digits within any number; and you treat this as mathematical problem. But one can see this as string manipulation problem; which allows you to use existing functions to solve the problem:
int originalNumber = ....
String originalNumberAsString = Integer.toString(originalNumber);
String reversedNumberAsString = new StringBuilder(originalNumberAsString).reverse().toString();
int reversedNumber = Integer.parseInt(reversedNumberAsString);
Please note: there is also no need to check for the size of your input here; but you probably should check for >=0 (or do what is appropriate in your case for negative numbers).
I just want to write a program that sorts 3 integers. The integers are entered from the input dialog. My code is really simple. I just need to get some data and put them in array called num. and then I create a method to sort the data by using bubble-sort logic. that method called sort. I have added command to display the sorted result with System.out.println("Sorted Result : "+Arrays.toString(num)) but that's not working.
The output just let me input data and then nothing happen.
Can anyone please tell me something I miss or what I did wrong?
Thank you.
package numThree;
import java.util.Scanner;
import java.util.Arrays;
public class sort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] num = new int[3];
//INPUT DATA
System.out.println("Enter integers : ");
for(int i=0;i<=num.length;i++){
num[i]=sc.nextInt();
}
sort(num);
}
//SORTING
public static void sort (int[] num){
for(int i=0;i<=num.length-1;i++){
for(int j=0;j<=num.length-i;j++){
if(num[j-1]>num[j]){
int temp = num[j];
num[j] = num[j-1];
num[j-1] = temp;
}
}
System.out.println("Sorted Result : "+Arrays.toString(num));
}
}
}
I believe you need a boolean flag to implement a bubble sort as you cannot know in advance how many times the loop will perform the swapping of consecutive elements.
Try this:
package numThree;
import java.util.Scanner;
import java.util.Arrays;
public class sort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] num = new int[3];
//INPUT DATA
System.out.println("Enter integers : ");
for(int i=0;i<=num.length;i++){
num[i]=sc.nextInt();
}
sort(num);
}
//SORTING
public static void sort (int[] num){
boolean swapped = true;
while(swapped){
swapped = false;
for(int i=0;i<num.length-1;i++){
if(num[i]>num[i+1]){
int temp = num[i];
num[i] = num[i+1];
num[i+1] = temp;
swapped = true;
}
}
}
System.out.println("Sorted Result : "+Arrays.toString(num));
}
}
Note that it can still be slightly improved: each time around the loop the largest number will end up as far as it can get towards the end of of the array: there's no need to check or swap till the end each time.
By using a variable as the upper limit of the index i and decreasing its value after the for loop you can reduce the total number of iterations.
int end = num.length-1;
while(swapped){
swapped = false;
for(int i=0;i<end;i++){
if(num[i]>num[i+1]){
int temp = num[i];
num[i] = num[i+1];
num[i+1] = temp;
swapped = true;
}
}
end--;
}
I'm currently stuck on a problem, let's say I want to find the middle value the user inputted, is there a function in Java wherein I can peek or return the middle value?
import java.util.*;
public class PQueue {
public static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int arr;
PriorityQueue<Integer> queueB = new PriorityQueue<Integer>();
for(int j=0; j<=4; j++)
{
System.out.println("Input Intergers: ");
arr = console.nextInt();
queueB.add(arr);
}
System.out.print(queueB.peek());
}
}
Just pop half the values off the PQ. The last one popped is the middle one.
The case where N is even is left as an exercise for the reader.
Of course this is assuming that by 'middle' you mean 'median'. If you mean 'mean', you're using the wrong data structure: you should use an array, sort it, and evaluate (array[0]+array[last])/2.
I'm not very good at programming, but I am obliged to write a program that calculates the product of two matrices by two methods :
The first method in a direct way.
The second using Threads so that the computation time is minimal.
I wrote this program for the first method :
Matrix.java
public class Matrix {
public int [][] M;
public int line,col;
static int [][]MProd=null;
//Constructeur
public Matrix (int [][] M,int line,int col) {
this.M=M;
this.col=col;
this.line=line;
for ( int i=0;i<this.line;i++){
for (int j=0;j<this.col;j++)
{
M[i][j]=(int)(Math.random()*100);}}
}
static int [][] prod(Matrix Mat1, Matrix Mat2 ){
for (int j=0;j<Mat2.col;j++){
for (int i=0;i<Mat1.col;i++){
for (int k=0;k<Mat1.line;k++){
MProd[k][j] += Mat1.M[k][i]*Mat2.M[i][j];
}}}
return MProd ;
}}
Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int [][] M = null,N = null;
int line1,line2,col1,col2;
int [][] P=null;
Scanner scanner = new Scanner(System.in);
System.out.println("enter the line number of the first matrix");
line1=scanner.nextInt();
System.out.println("enter the number of columns of the first matrix");
col1=scanner.nextInt();
Matrix Mat= new Matrix (M,line1,col1);
System.out.println("enter the line number of the 2nd matrix");
line2=scanner.nextInt();
System.out.println("enter the number of columns of the 2nd matrix");
col2=scanner.nextInt();
Matrix Mat1= new Matrix (N,line2,col2);
if (col1==line2)
{
P=Matrix.prod(Mat,Mat1) ;
System.out.println("matrix product :");
for (int i=0;i<Mat.line;i++)
{
for (int j=0;j<Mat1.col; j++)
System.out.print( + P[i][j]+" ");
System.out.println();
}}
else {
System.out.println("the matrices product is impossible");
}
}}
when I run the program it shows me :
Exception in thread "main" java.lang.NullPointerException
at Matrice.(Matrice.java:18)
at Main.main(Main.java:15)
Can someone help me to correct this program, and shows me how to write this program with Threads ?
Your NullPointerException is due to this:
public static void main(String[] args) {
int [][] M = null,N = null; // all declared null
// ...
Matrix Mat= new Matrix (M,line1,col1); // here you use a null value, M
// ...
Matrix Mat1= new Matrix (N,line2,col2); // and same here, N is null
When you call, M[i][j]=(int)(Math.random()*100); in your Matrix class, M is null so this will fail. You must first create a Matrix, your 2D array, before you can use it.
Edit
You ask:
Can you explain me more.
You're passing a null reference into your Matrix constructor and then trying to use it as a variable. You should pass a non-null 2D array instead:
int[][] myArray = new int[x][y]; // where x and y are appropriate numbers
Matrix Mat= new Matrix (myArray, line1, col1);
Also, please study and use standard Java Coding Conventions (please see link) including:
All class, enum and interface names begin with an uppercase letter.
All method and variable names begin with a lowercase letter.
Learn to use judicious use of white space including a space between parameters.
Do this and folks will be better able to read and understand your code and then be able to give you better help.