How to manipulate the array in Java? - java

Starting with a 1-indexed array of zeros and a list of operations, for each operation, I have to add value to each of the array elements between two given indices, inclusive. Once all operations have been performed, I have to return the maximum value in the array. But the wrong answer is coming every time for most test cases and for some test cases time limit is exceeding. Kindly help me to solve this problem.
I am using arrayManipulation function to get the number of array elements and queries array. And update function is used to update(add the element) the array.
import java.util.*;
import java.util.Arrays;
public class sample
{
public static void main(String args[])
{
int maximum=0;
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int queries[][]=new int[m][3];
for(int x=0;x<m;x++)
{
for(int y=0;y<3;y++)
{
queries[x][y]=sc.nextInt();
}
}
maximum=arrayManipulation(n,queries);
System.out.println(maximum);
}
public static int arrayManipulation(int num,int qry[][])
{
int a=0,b=0,k=0;
int max=Integer.MIN_VALUE;
int arr[]=new int[num];
int arr2[]=new int[num];
for(int i=0;i<num;i++)
{
arr[i]=0;
}
for(int j=0;j<qry.length;j++)
{
for(int kl=0;kl<qry[0].length;kl++)
{
a=qry[j][kl];
b=qry[j][kl+1];
k=qry[j][kl+2];
break;
}
arr2=update(a,b,k,arr);
int lengtharr2=arr2.length;
max=Math.max(max,arr2[lengtharr2-1]);
}
return max;
}
public static int[] update(int a1,int b1, int k1,int array[])
{
for(int i=a1;i<b1;i++)
{
array[i]+=k1;
}
Arrays.sort(array);
return array;
}
}
Input: 10 means the number of array elements and 3 is no. of queries which consist of a,b,k values which mean like this: the left index, right index, and summand
10 3
1 5 3
4 8 7
6 9 1
My output:
11
expected output:
10

In this for loop:
for(int kl=0;k<qry[0].length;k++)
{
a=qry[j][kl];
b=qry[j][kl+1];
k=qry[j][kl+2];
break;
}
Why are you using two different variables (k and kl) in your loop condition?
Regardless, you should use a variable other thank k for the loop, as you are updating the value of k and then executing k++ at each iteration of your loop, which is very likely to mess up your output.
Consider something like:
for(int l=0;l<qry[0].length;l++)
{
a=qry[j][kl];
b=qry[j][kl+1];
k=qry[j][kl+2];
break;
}

Related

Rotate Array by k

Given an array and a number k we have to rotate array k times.
Sample Input
1 //number of of testcases
5 2 //5(array size) 2(K value)
1 2 3 4 5 /array elements
Sample output
4 5 1 2 3
Here is my code
import java.util.*;
class TestClass {
public static void main(String args[] ) throws Exception {
// Write your code here
Scanner input=new Scanner(System.in);
int testcases=input.nextInt();
for(int i=0;i<testcases;i++)
{
int size=input.nextInt();
int rotationNo=input.nextInt();
rotateArray(size, rotationNo, input);
}
}
public static void rotateArray(int size, int rotationNo, Scanner input)
{
int[] arr=new int[size];
int[] result=new int[size];
rotationNo=rotationNo%size;
for(int i=0;i<size;i++)
{
arr[i]=input.nextInt();
}
int resultIndex=0;
int index=size-rotationNo;
int k=index,t=0,track=0;
while(true)
{
if(k<size)
{
System.out.print(arr[k++]+" ");
++track;
if(track==size)
{
break;
}
else
{
continue;
}
}
if(t<index)
{
if(t==(index-1))
{
System.out.print(arr[t++]);
}
else
{
System.out.print(arr[t++]+" ");
}
++track;
if(track==size)
{
break;
}
else
{
continue;
}
}
}
System.out.println();
}
}
This question was asked in a programming competition. My all testcases were passing except one which showed time limit exceeded. But I am not understanding what is the cause of time limit exceed. Loops will always halt whatever be the testcase.
Time Complexity of my code is O(n).
Is there another better and efficient solution?
Start outputting the input directly (i.e. without storing it) as soon as k values have been read and stored.
Then output the k initially read and stored values.
The shifting inside the array, is the relevant operation here.
The fewer shifts are done (the distance of shifting is not really relevant here, if implemented correctly), the better. It includes the storing and retrieving to/from an array. I consider the reading and outputting, if done without any processing in between, to be negligible. I.e. I focus on the shifting.
Strictly speaking, the reading and outputting is processing and that would mean that no improvement of O() can be calculated.
But allow me to ignore the reading and outputting for an O() estimation of the improvement:
The proposed recommendation will improve the number of array-accesses during shifting from O(n) to O(k). Admittedly the reading and outputting is ignored here. Storing and retrieving from an array and especially the shifting inside the array is avoided here and that is the O(k) part which is relevant here.
So the relevant operations are O(k), ignoring n-k values in O(1).
A test case like
1
10000 1
1 2 3 4 5 6 7 8 ...
will easily eliminate programs which after reading and before outputting, do O(4*10000), i.e. store all, read and write all for shifting and then read all for outputting. Compared to O(2*1) for only storing a single value and reading again for outputting at the end.
(Yes, I know clean O() analysis does not use factors, or any digits. You stil get the point, I hope. ;-)
Here is a code proposal (simplified to a single testcase):
import java.util.*;
public class Test {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int testcases= input.nextInt(); //ignored, assuming 1
int size = input.nextInt();
int rotation = input.nextInt();
int i=0;
int[] newArr = new int[rotation%size]; //small array
// based on the nice idea by User-Upvotedon'tsayThanks
for(; i<rotation%size; i++)
{
newArr[i] = input.nextInt(); // few write accesses
}
for(; i<size; i++)
{
System.out.println( input.nextInt()); //many direct outpots
}
for(i=0; i<rotation%size; i++)
{
System.out.println(newArr[i]); // few outputs from array
}
return;
}
}
For an input of:
1
5 2
1 2 3 4 5
It gets you an output of:
3
4
5
1
2
Same output for a modulo-requiring input of:
1
5 7
1 2 3 4 5
I have provided a solution below which will directly output the scanner input up until the size of input has been met. It has a constant time o(n) for input, however it only touches each item once. and avoids the use of a while loop that may otherwise increase the multiplier of the iterations.
public class Test {
public static void main(String[] args) {
int rotation = new Scanner(System.in).nextInt();
int size = new Scanner(System.in).nextInt();
int[] values = rotate(rotation, size, new Scanner(System.in));
for(int i : values){
System.out.println(i);
}
}
public static int[] rotate(int rotation, int size, Scanner input){
int[] newArr = new int[size];
for(int i = 0; i<size; i++){
int newPosition = i + rotation;
newPosition = newPosition >= size ? newPosition - size : newPosition;
newArr[newPosition] = input.nextInt();
}
return newArr;
}
}

What will be the run time complexity for recursive algorithm for finding the largest number in an array. Compare it vs iterative loop code

I have written the code for the largest number in the iteration loop code. And I have found the run time complexity for the code is O(n). What will be the run time complexity for the recursive code of the largest number and how will it differ from the iteration loop. Which will be better. My code for the iteration loop is
package com.bharat;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the numbers you want to add in the array: ");
int number = scanner.nextInt();
int[] myIntgersArray = getIntegers(number);
System.out.println(Arrays.toString(myIntgersArray));
System.out.println(findBiggestNumber(myIntgersArray));
}
public static int[] getIntegers(int number){
Scanner scanner = new Scanner(System.in);
int[] values= new int[number];
for (int i =0;i<values.length;i++){
values[i]=scanner.nextInt();
}
return values;
}
public static int findBiggestNumber(int[] array){
int i=0;
int biggestNumber = array[i];
for ( i = 0;i<array.length;i++){
if (array[i]>biggestNumber){
biggestNumber=array[i];
}
}
return biggestNumber;
}
}
Recursive code which was posted in comments -
public static int findBiggestNumber(int[] array, int number) {
int highestNumber = array[0];
if (number==1) {
return highestNumber;
}
else {
if (highestNumber < array[number]) {
array[number] = highestNumber;
return highestNumber;
}
}
return findBiggestNumber(array, number-1);
}
Correct recursive code (assuming the array has at least 1 element) -
public static int findBiggestNumber(int[] array, int number)
{
if(number == 1) //only one element is there in array
{
return array[number - 1];
}
return Math.max( array[number - 1] , findBiggestNumber(array,number-1) );
}
The recursive code runs in O(n) time but it has extra space overhead of O(n) due to the recursive function call stack.
Why the recursive code has O(n) time ?
It solves n-1 smaller problems. And nth problem is solved in O(1) time from the result of n-1th problem.
How the recursive code works ?
If you have an array with n sized array, then maximum element of this array is either
1. last element array[n-1], or
2. the maximum element of the n-1 sized array.
To calculate the result of n-1 sized array, you repeat similarly.
The base case is, when you have only one element in the array, then that is the maximum.

Re-arranging array

I have an assignment they ask me to re-arrange an array from the even numbers to the odd numbers
like this:
Sample Output:
Please enter array of 5 integers:
1 2 5 6 4
the array after re-arranging:
2 6 4 1 5
I couldn't do it " I cant use methods" can anyone help me ?
this is my code:
public static void evenOdd(int[] arr){
int i=0;
int arr1[] = new int[5];
for (i=0;i<5;i++)
{
if (arr[i]%2==0)
arr1[i]=arr[i];
}
for (i=0;i<5;i++){
if(arr[i]%2!=0)
arr1[i]=arr[i];
}//end for
for(i=0;i<5;i++)
System.out.print(arr1[i]+" ");
System.out.println("");
}//end method
THANK YOU
The problem is when you add them into the new array you are putting them in the same position: i. Use a separate int to keep count of what part of the index you are on.
public static void evenOdd(int[] arr){
int i=0;
int count = 0;
int arr1[] = new int[5];
for (i=0;i<5;i++) {
if (arr[i]%2==0) {
arr1[count]=arr[i];
count++;
}
}
for (i=0;i<5;i++){
if(arr[i]%2!=0) {
arr1[count]=arr[i];
count++;
}
}//end for
for(i=0; i < 5; i++) {
System.out.print(arr1[i]+"\n");
}
}//end method

how can i find the average of this?

I'm new to java programming and i just cant figure out how to find the average of an array nor do i know how to print the array backwards. This is my code so far:
public static void forwards(int nums, int arrayNums[]){
for(int a=0;a<arrayNums.length;a++){
nums =(int)(Math.random()*90+10);
System.out.print(nums+" ");
}
System.out.println();
System.out.println();
//Average of the array
int average=0;
for(int b=0;b<arrayNums.length; b++){
average=(average+arrayNums[b]);
}
System.out.println();
System.out.println(average);
}
public static void backwards(int nums, int[] arrayNums){
//backwards of the array
for(int a=arrayNums.length; a>0;a--){
System.out.print(nums+" ");
}
}
public static void main (String [] args){
int[] arrayNums = new int [Integer.parseInt
(JOptionPane.showInputDialog("How many numbers do you want to input?"))];
int nums = 1;
forwards(nums,arrayNums);
System.out.println();
backwards(nums,arrayNums);
For average ---->
for (int i = 0; i < array.length; i++)
{
sum += array[i];
}
int avegare = sum / array.length;
For Backwards ---->
for(int i = Array.length - 1; i >= 0;i--)
Backwards should start with arrayNums.length-1:
public static void backwards(int nums, int[] arrayNums){
//backwards of the array
for(int a=arrayNums.length-1; a >= 0; a--){
System.out.print(arrayNums[a]+" ");
}
}
The reason is that indices go from 0 to array.length-1. That's basically what happens in a for loop.
For the average, you forgot a division by the number of elements...
"i just cant figure out how to find the average of an array nor do i know how to print the array backwards."
For averages, you should use a different method, instead of trying to it in the forwards method
public static double average(int[] arrayNums) {
double sum = 0;
...
double average = // how do you get the average of something?
return average;
}
I started you off with the basic outline. You basically need to add all the numbers to the sum, by looping through the array, then get the average by diving it by the total of numbers in the array. Then you can print out the average like
double average = average(array);
System.out.println(average)
for backwards, you want to print arrayNums[a] instead of nums. You should also start the loop from arrayNum.length - 1 as there is no index in the array arrayNums.length so you would get an ArerayOutOfBounds exception. Also you want the 0th index, so you want to use >=
for(int a = arrayNums.length - 1; a >= 0 ;a--) {
// print arrayNums[a]
You seem to be doing the same wrong thing for forwards as you are in backwards. You want to print the arrays value for each index a, and not nums
I would also create the random array in a different method
public static int[] randomArray(int num) {
int[] random = new int[nums];
.... may array by looping
return random;
}
Then you the main you could just do
int[] array = randomArray(num);
forwards(array);
backwards(array);
double average = average(array);
System.out.println(average);
As you can see, I pass no nums to the methods. I think you should take tha parameter out of the method signatures. I see no use for them.
Here is a simple way to find the average. Just add up each of the elements, and then divide by the total number of elements in the array:
public static double average(int[] array)
{
int average =0;
for(int i =0; i< array.length; i++ )
{
average += array[i];
}
return average/array.length;
}
Here is a backwards method. Start at array.length-1, which is the last index. From there, iterate down i--, and then end when i is zero.
public static void printBackwards(int[] array)
{
for(int i =array.length-1; i>= 0; i--)
{
System.out.print(array[i] +" ");
}
}
When you call the methods, this is the syntax you should use:
double avg = average(arrayNums);
System.out.println(avg);
printBackwards(arrayNums);

sorting an array and counting its elements

I tried to sort an array accending and count the array elements
please help me find whats missing, have debugged many times. here is my code and the output i got. Thanks
package habeeb;
import java.util.*;
public class Habeeb {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = new int[30];
int i, count=0;
System.out.println("Enter the integers between 1 and 100" );
for( i=0; i<num.length; i++){
num[i]= input.nextInt();
if(num[i]==0)
break;
count++;
}
calling the function here
Sorting(num, i, count);
}
public static void Sorting(int[] sort, int a, int con){
if (a<0) return;
/*am sorting the array here*/
Arrays.sort(sort);
int j, count=0;
for(j=0; j<con; j++){
if(sort[a]==sort[j])
count++;
}
System.out.println(sort[a]+" occurs "+count+" times");
Sorting(sort, a-1, con);
}
}
Here is the output:
run:
Enter the integers between 1 and 100
2
5
4
8
1
6
0
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
Your problem is that the array is of size 30 and when you sort it you have all the values you did not assign to equal to 0 and thus they go in the front of the sorted array. Later on out of the first 6 numbers all are 0 so the output you have is correct.
To aviod the problem you face I suggest you use ArrayList instead of simple array so that you can add elements dynamically to it.
Try this
The counting method
public int count(int[] values, int value)
{
int count = 0;
for (int current : values)
{
if (current == value)
count++;
}
return count;
}
Then use
int[] sorted = Arrays.sort(num);
for (int value : sorted)
{
System.out.println("" + value + " occurs " + count(sorted, value) + " times");
}
This works for sure.
You are doing a bit more work than is necessary. I would solve this like so:
Map<Integer, Integer> countMap = new HashMap<Integer,Integer>();
for( i=0; i<num.length; i++){
int current = input.nextInt();
if(countMap.get(current) != null)
{
int incrementMe = countMap.get(current);
countMap.put(current,++incrementMe);
}
else
{
countMap.put(input.nextInt(),1);
}
}

Categories

Resources