1D Array, multiples of 5. Simple but new to coding - java

Write a program that assigns and stores the first 20 multiples of 5 in the array called Data, no other array can be used in the program. The program should output the elements of the array, according to the following:
write only the commands to assign and store the values in Data
output the array: 10 numbers/line with the sum of each line
output the array: in reversed order, 5 numbers/line with the sum for each line
the odd indexed position values (Data[1], Data[3], Data[5],...), 5 values/line and their sum
the even indexed position values (Data[3], Data[4], Data[6],...), 5 values/line and their sum
I have part 1. so far:
int data[]=new int[21]; int sum=0;
for(int i=1;i<21;i++){
data[i]=5*i;
sum+= data[i];
if(i%11==0)
System.out.println();
System.out.print(data[i] + " ");
}
System.out.println("sum " + sum);
int a[]=new int[21];
for(int i=1;i<21;i++){
a[i]=5*i;
//System.out.print(a[i] + " ");
}
System.out.println();
I need help with the rest.

As told in comments, we're not here to code for you, you will lose really important experience about learning how to program.
But I can give you some tips that may help in your assignment.
write only the commands to assign and store the values in Data
output the array: 10 numbers/line with the sum of each line
DONE, RIGHT? ;)
output the array: in reversed order, 5 numbers/line with the sum for each line
We wont speak now in built in functions of Arrays or Collections. Do it easy: to reverse array reverse the loop:
for(int i=20i>=0;i--){
Better use the array length:
for(int i=data.length-1;i>=0;i--){
To make increments (for example by 5) you can use d[i] += 5 equivalent to d[i] = d[i] + 5 in the same way a++ is a = a + 1.
you need 5 values per line right? To know when to finish a line, use modulus or remainder operator %.
if (i % 5 == 0)
That means, if modulus of i / 5 equals 0 (so 5 multiple), use it to print sum and new line (println)
the odd indexed position values (Data1, Data[3], Data[5],...), 5 values/line and their sum
Remembering for this part: i+=2 is same than i = i + 2 ;)
the even indexed position values (Data[3], Data[4], Data[6],...), 5 values/line and their sum
To sum, create a new variable to store values OUTSIDE the loop, and sum inside:
int total = 0;
for(int i=1;i<21;i++){
total += data[i]; // equals to total = total + data[i]
// more code
if (i % 5 == 0) {
// print total of the line and skip line
// reset total variable total = 0;
}
// more code
}

Related

Why does my CalcOddIntegers method always return zero?

This method is supposed to take user input for the length of the array, and then the integers that are part of the array, and return the amount of odd numbers in the array. However, it always returns zero for the count of odd integers and I am unsure as to why. The scanner is declared outside of this method.
System.out.print("Enter length of sequence\n");
int length = console.nextInt();
int[] array = new int[length];
System.out.print("Enter the sequence: \n");
int count = 0;
int i = 0;
for (i = 0; i < length; i++) {
array[i] = console.nextInt();
}
for (i = 0; i < length -1; i++); {
if (array[i] % 2 != 0) {
count++;
}
}
System.out.printf("The count of odd integers in the sequence is %d\n", count);
}
Example of console:
2. Calculate the factorial of a given number
3. Calculate the amount of odd integers in a given sequence
4. Display the leftmost digit of a given number
5. Calculate the greatest common divisor of two given integers
6. Quit
3
Enter length of sequence
4
Enter the sequence:
1
2
3
4
The count of odd integers in the sequence is 0
I have tried experimenting with the for statements with different variables to see if something was conflicting but nothing has worked.
Remove the semi-colon (;) in the line
for (i = 0; i < length -1; i++);
the semi-colon terminates the loop hence an assumption that your line does nothing.
After the second for there is a semicolon that shouldn't be there. The syntax is technically correct however, there is nothing to execute so the block that checks for odd numbers is going to be executed only once. I suggest using a debugger that will help you troubleshoot issues easier.

Circular Array Rotation Time Limit Exceeded(TLE)

I am really confused why my java code is not working it is giving TLE on Code Monks on Hacker Earth.
Here is the link to the question - Link to Question
the first question MONK AND ROTATION
import java.util.Scanner;
class TestClass {
static int[] ar=new int[100001];
public static void main(String args[] ){
Scanner in=new Scanner(System.in);
byte t=in.nextByte();
while(--t>0){
int n=in.nextInt();
int k=in.nextInt()%n;
for(int i=0;i<n-k;i++)
ar[i]=in.nextInt();
for(int i=0;i<k;i++)
System.out.print(in.nextInt()+" ");
for(int i=0;i<n-k;i++)
System.out.print(ar[i]+" ");
System.out.println();
}
}
}
I don't know why is it giving TLE I think there is some infinite loop going.
the question at the site is-
Monk and Rotation
Monk loves to perform different operations on arrays, and so being the principal of HackerEarth School, he assigned a task to his new student Mishki. Mishki will be provided with an integer array A of size N and an integer K , where she needs to rotate the array in the right direction by K steps and then print the resultant array. As she is new to the school, please help her to complete the task.
Input:
The first line will consists of one integer T denoting the number of test cases.
For each test case:
The first line consists of two integers N and K, N being the number of elements in the array and K denotes the number of steps of rotation.
The next line consists of N space separated integers , denoting the elements of the array A.
Output:
Print the required array.
Constraints:
1<=T<=20
1<=N<=10^5
0<=K<=10^6
0<=A[i]<=10^6
Sample Input
1
5 2
1 2 3 4 5
Sample Output
4 5 1 2 3
Explanation
Here T is 1, which means one test case.
denoting the number of elements in the array and , denoting the number of steps of rotations.
The initial array is:
In first rotation, 5 will come in the first position and all other elements will move to one position ahead from their current position. Now, the resultant array will be
In second rotation, 4 will come in the first position and all other elements will move to one position ahead from their current position. Now, the resultant array will be
Time Limit: 1.0 sec(s) for each input file
Memory Limit: 256 MB
Source Limit: 1024 KB
Think from a different perspective. Instead of splitting the string and converting it into an array and applying the iterative logic, we can apply a different logic.
The trick is you just need to find the position of the input string where we have to split only once.
By that I mean,
input=>
6 2       //4 is the length of numbers and 2 is the index of rotation
1 2 3 4 5 6     //array (take input as a string using buffered reader)
Here, we just need to split the array string at the 2nd last space i.e. 4th space. So the output can be achieved by just splitting the string once-
5 6 1 2 3 4
first split- 5 6 + space + second split- 1 2 3 4
This logic worked for me and all the test cases passed.
Also don't forget to cover the corner case scenario when array input string is just one number.
Code Snippet-
int count=0;
for(int k=0; k<arr.length(); k++) {
if(arr.charAt(k)==' ')
count++;
if(count==size-rot) {
System.out.println(arr.substring(k+1,arr.length())
+ " " + arr.substring(0,k));
break;
}
}
Problem is here
for(int i=0;i<n-k;i++) //this loop you are using for storing input elements in array
ar[i]=in.nextInt();
for(int i=0;i<k;i++) // here you again taking the input you don't need this loop
System.out.print(in.nextInt()+" ");
for(int i=0;i<n-k;i++)
System.out.print(ar[i]+" ");
You also need to change the condition in while loop while(--t>0) to while(--t >= 0). It should be >= 0 other wise it will not work. Other solution is to use post decrement while(t-- > 0)
You are trying to print right rotation of the array. So you need to start printing the elements from index n - k. Then you need to calculate the end index it is (n - k) + n this is because array has n elements. Then you can access array elements like this arr[i % n].
Here is the complete working solution
class TestClass {
static int[] ar = new int[100001];
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
byte t = in.nextByte();
while (--t >= 0) {
int n = in.nextInt();
int k = in.nextInt() % n;
for (int i = 0; i < n; i++)
ar[i] = in.nextInt();
for (int i = n - k; i < n + (n - k); i++)
System.out.print(ar[i % n] + " ");
System.out.println();
}
}
}

Why does my code fail the hidden input test cases?

This is the problem to be solved:
John is assigned a new task today. He is given an array A containing N integers. His task is to update all elements of array to some minimum value x , that is, A[i] = x; 1 <= i <= N; such that sum of this new array is strictly greater than the sum of the initial array.
Note that x should be as minimum as possible such that the sum of the new array is greater than the sum of the initial array.
Input Format:
First line of input consists of an integer N denoting the number of elements in the array A.
Second line consists of N space separated integers denoting the array elements.
Output Format:
The only line of output consists of the value of x.
Sample Input:
5
12345
Sample Output:
4
Explanation:
Initial sum of array= 1 + 2 + 3 + 4 + 5 = 15
When we update all elements to 4, sum of array = 4 + 4 + 4 + 4 + 4 = 20 which is greater than 15.
Note that if we had updated the array elements to 3, sum = 15 which is not greater than 15. So, 4 is the minimum value to which array elements need to be updated.
** ==> Here is my code. How can I improve it? or What is the problem in this code? **
import java.util.Scanner;
public class Test2 {
public static void main(String []args){
Scanner s=new Scanner(System.in);
int check=0, sum=0, biggest=0;
int size=s.nextInt();
if(size>=1 && size<=100000) {
int[] arr=new int[size];
for(int i=0; i<size; i++){
int temp=s.nextInt();
if(temp>=1 && temp<=1000) {
arr[i] = temp;
biggest=biggest > temp ? biggest:temp;
sum=sum+temp;
}
else break;
}
for(int i=1; i<biggest; i++){
check=(size*i)>sum ? i:0;
}
System.out.print(check);
}
else System.err.print("Invalid input size");
}
}
Issue:
for(int i=1; i<biggest; i++){
check=(size*i)>sum ? i:0;
}
There are 2 problems with this, hence it doesn't work. They are as follows-
(size*i)>sum ? i - The problem statement states that it needs minimum possible sum greater than sum of array of elements. Your code blindly assigns i to check without checking the minimality.
check=(size*i)>sum ? i:0 - So, even if you had come across some integer previously, you lost it because you assigned it to 0 if the condition is not satisfied.
I will share my idea of how would I go about this.
Approach 1
Sum all elements like you did.
Now, take average of elements - sum / size of the array. Let's say we store it in a variable average.
Print average + 1 as your answer, as that is the value that could give you minimum possible sum > sum of array itself.
Time Complexity: O(n), where n is size of the array.
Space Complexity: O(1)
Approach 2
Sum all elements like you did.
Calculate min and max for the array and store it in variables, say mini and maxi.
Now, do a binary search between mini and maxi and keep checking the minimum sum > sum criteria.
In this process, you will have variables like low, mid and high.
low = mini,high = maxi
while low <= high:
mid = low + (high - low) / 2
If mid * size <= sum,
low = mid + 1
else
high = mid - 1
Now, print low as your answer.
Let range = maxi - mini.
Time Complexity: O(n) + O(log(range)) = O(n) asymptotically, where n is size of the array.
Space Complexity: O(1)
Not sure if I completely followed what your attempt was, but there should be a pretty straightfoward solution. You know the size of the array and you can easily iterate through the array to get the value of the elements stored in it. All you need to do to find your min x is to take sumOfArray/size of array and then add one to the result to make your result higher.
In your example 15/5=3. 3+1 = 4 so that's your answer. If the numbers summed to 43, 43/5 = 8 r 3, so your answer is 9 (9*5=45). Etc.
When trying some other test cases, then the results are wrong. Try:
Input:
5
1 1 1 1 5
Expected Output: 2 Actual Output: 4
and
Input:
5
5 5 5 5 5
Expected Output: 6 Actual Output: 0

Adding Two Elements in an Array (Java)

I need to write a method that adds the two last elements of two arrays together and add the sum on another array. But if the two elements are more than 10, then I would need to carry that number to the next array.
This program should be similar to what an odometer does.
Here is my sample code.
int [] sum(int []number1, int []number2)
{
int [] total;
int carry = 0;
for ( int k = numbers1 - 1; k >= 0; k++)
{
sum = number1[k] + number2[k] + carry;
carry = sum/10;
total[k] = sum
}
return total;
}
An example output would be:
0 1 2 3 4
0 8 9 9 9
4 5 7 0 3
5 4 7 0 2
So the top array is just a visual aid that tells where the position for the number is.
The program is suppose to add the next two arrays together. i.e. 9 + 3 = 12
Since 12 is above 9, it carries over the 10 to the next set of arrays, that is why the third array only has a 2 in its place, and that is why the next array is 9 + 0 = 0; because the 10 was carried over.
I am not sure why my code won't work. I don't get the right numbers. Could anyone give any hints or solution to the problem?
-Thanks
I assume numbers1 is the number of elements in the array.
In this case it should be k-- instead of k++ because you are starting from the last element and moving backword.

Java, can't find average of an array

I need to write a program that finds an average of all values in the array and then returns ones larger than the average.
import java.util.*;
public class AboveAverage {
public static void main(String args[]) throws Exception {
Scanner kbd = new Scanner(System.in);
int count=0, num;
int nums[] = new int[1000];
double sum = 0;
double average = 0;
System.out.println("Input +ve integers, to stop type 0");
num = kbd.nextInt();
while( num > 0 ) {
nums[count] = num;
count = count + 1;
num = kbd.nextInt();
}
int d = 0;
while ( d < 1000 ) {
sum += nums[d];
d++;
average = sum / nums[d];
}
for(int i=0; i < count ; i=i+1) {
System.out.print(nums[i] + " ");
}
System.out.println(average);
}
}
In my opinion problem is in this line
I tried the one below which gives an exception
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1000
at AboveAvarage.main(AboveAvarage.java:23)
average = sum / nums[d];
I also tried
average = sum / nums.length;
Which gave me the sum instead of the average.
Remember that array indices in Java go from zero? This means the allowed indices in your nums array are 0 through 999.
Now look at this loop:
int d = 0;
while ( d < 1000 ) {
sum += nums[d];
d++;
average = sum / nums[d];
}
First, it adds the current number to the sum. This is correct.
Then, it increments the number.
Then it uses the incremented number to access nums[d] to calculate the average.
Now, imagine that you are at the last round. d is 999.
First, it adds the current number to the sum.
Then it increments d. Now it is 1000.
Then it uses the incremented number to access nums[d]. But this means nums[1000]. And that's an illegal index.
So this explains why you have an ArrayIndexOutOfBoundsException. You should never use the index again after you incremented it, because the while only guaranteed that its previous value was less than 1000. If you change the value, you need to test again. This is why normally the increment step is the last in the loop.
As for your logic:
To calculate an average, you first need to know the sum. After you know the sum, you can divide by the number of items you are averaging. So you need to divide the sum by the number of items you read.
So:
You should not do a loop up to 1000. If you entered 0 after 5 numbers when you inputted the data, then there will be no values in the rest of the array (or rather, there will be zeros there).
You can calculate the sum, as another answer told you, in the first loop. No need to do that in the second loop.
You don't calculate the sum and the average in the same step. You first have to complete calculating the sum (finish the loop, be it the first or the second), and only then you can divide by the number of items (which you saved in count).
Then you have to go through another loop, that prints the numbers that are larger than the average. Your print loop prints all the numbers. You should check each number, see if it is greater than the average you calculated, and only if it is, print it.
Hint: there should really only be two loops: One that reads the numbers and calculates the count and the sum. Then you calculate the average, but that's not a repeating action, so it should not be in a loop. The second loop is for printing the numbers that are above average.
In the while loop that is gathering values, you are using count to track how many values are provided.
In the subsequent loop to calculate the average, you should only look at count items of the array:
int d = 0;
while(d<count) {
sum += nums[d];
}
average = sum/count;
Note you don't need to calculate average within the loop - do it once you've summed the values.
You don't need the other while loop, add up sum upon input. When done, just divide by count
while( num > 0 ) {
nums[count] = num;
count = count + 1;
sum += num;
num = kbd.nextInt();
}
average = sum / count;

Categories