Okay here's a Java assignment I've been having trouble with. I asked earlier about this and got some good comments and advice, but have since understood the assignment more clearly and the issue has changed a bit. So here's the assignment:
***
Your task is to complete the program below by writing three methods (askInfo, copyInfo and setArray). Program should ask for integers (max 100 integers) until the users types in zero. Integers can vary from one to one hundred and they are stored in an array that has 100 elements. Numbers are asked for with the askInfo method, which receives the array with numbers as parameter. Method returns the number of integers. The number zero is not saved in the array; it is merely used to stop giving input. The given numbers are then copied to another array which size is the amount of given numbers. Copying is done with copyInfo method which receives both arrays as parameters. After this the elements of the new array are put in ascending order with setArray method and printed on screen with printArray method.
Program to complete:
import java.util.*;
public class RevisionExercise {
public static void main(String[] args) {
int[] tempArray = new int[100];
System.out.println("Type in numbers. Type zero to quit.");
int amountOfNumbers = askInfo(tempArray);
int[] realArray = new int[amountOfNumbers];
copyInfo(realArray, tempArray);
setArray(realArray);
printArray(realArray);
}
// Your code here
public static void printArray(int[] realArray ) {
System.out.println("\Ordered array: ");
for(int i = 0; i < realArray .length; i++) {
System.out.println(realArray [i]);
}
}
Example print:
Type in numbers. Type zero to quit.
1. number: 3
2. number: 8
3. number: 5
4. number: 6
5. number: 9
6. number: 0
Ordered array:
9
8
6
5
3
I'm struggling with the askInfo method. So far I've written this but it returns only zeroes. Here's my askInfo method:
public static int askInfo(int[] tempArray) { //askinfo-metodi
Scanner reader = new Scanner(System.in);
int i;
for (i = 0; i < tempArray.length; i++) {
System.out.print((i+1) + ". number: ");
tempArray[i] = reader.nextInt();
if (tempArray[i] == 0) {
return tempArray[i];
}
}
return tempArray[i];
}
***
How can I make it to register the input and get the amount of numbers to be passed to the next method in the assignment as described in the assignment.
You never store your integer luku values in your array, so your array never changes from the default initialized integer values of all zeroes. Inside your loop, you need to add an
tempA[i] = luku;
After the if-statement confirms that luku is not 0. All in all:
if (luku == 0) {
return i;
}
tempA[i] = luku;
Related
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;
}
}
Input has to taken by the user. My code is given below. Why does it only output zeroes? What is the solution?
Output of the program is 0 0 0 0 (total number of input taken).
import java.util.Arrays;
import java.util.Scanner;
public class atlast {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] array = new int[107];
for (int i = 0; i < n; i++) {
array[i] = input.nextInt();
}
Arrays.sort(array);
for (int i = 0; i < n; i++) {
System.out.print(array[i] + " ");
}
}
}
int[] array = new int[107];
You are initializing a table that contains 107 value of 0.
So, if the n is small, the first elements will be 0.
To see the result replace n in the last loop by 107 and you will see the values
You initialized an array with size 107 which implies there are 107 zeroes in the array initially before accepting the input from the user. Since there are four zeroes in the output, you must have taken 4 values for input. So there are four non-zero values and 103 zero values in the array. When you apply Arrays.sort 103 zeros comes before 4 non-zero values. Hence when you print n values (which is 4 in this case) you get only zeroes.
You could use ArrayList instead so that numbers will be initialized only when user enters it.
I am having problems in creating a method that will find the index of the biggest integer.
I have tried creating plenty of methods but I was only recently introduced to finding the index of a value in a list, and I still am unable to find the best, let alone a working way. By index I assumed that it is the position of the value within the list given (please correct me if I am wrong).
My Current Code:
import java.util.ArrayList;
import java.util.Scanner;
public class FindBiggest2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> integerList = new ArrayList<Integer>();
System.out.println("Enter any amount integers (0 to stop): ");
int integer = input.nextInt();
while(integer != 0) {
integerList.add(integer);
integer = input.nextInt();
}
input.close();
if(integerList.size() == 0) {
System.out.println("list is empty");
return;
}
System.out.println("\nThe integers entered are: ");
// displaying ids
for(int i=0; i<integerList.size(); i++)
System.out.print(integerList.get(i)+" ");
System.out.println();
// finding biggest id
int bInt = integerList.get(0); // initializing bid id with first element
for(int i=1; i<integerList.size(); i++)
if(bInt < integerList.get(i))
bInt = integerList.get(i);
System.out.println("The biggest integer in the array is: "+ bInt);
}
}
My current output (Example):
Enter any amount of integers (0 to stop):
1
2
3
4
5
6
0
The integers entered are:
1 2 3 4 5 6
The biggest integer in the array is: 6
These are my requirements of my output:
The output of the program should firstly display all integers, and then
indicate the biggest integer among them as well as the index of the biggest integer in the 1D
array.
So your index in this loop:
int bInt = integerList.get(0); // initializing bid id with first element
for(int i=1; i<integerList.size(); i++) // i = index
if(bInt < integerList.get(i))
bInt = integerList.get(i);
would be i. Along with int bInt, you'll want an int maxIntegerIndex to hold that value until the for loop concludes.
One stylistic choice I'd suggest that you can feel free to ignore is using curly braces to explicitly declare what code is running in a loop / if statement. This will prevent issues later on in code reading and execution where it appears code should run but isn't. It'll save you a lot of time tracking down seemingly broken code down the road and costs almost nothing.
I am having problems in creating a method that will find the index of
the biggest integer.
In the same way that you are storing the largest value, also store the value of "i" in a separate variable:
// finding biggest id AND the index where it was found
int index = 0;
int bInt = integerList.get(0); // initializing bid id with first element
for(int i=1; i<integerList.size(); i++) {
if(bInt < integerList.get(i)) {
bInt = integerList.get(i);
index = i;
}
}
System.out.println("The biggest integer in the array is: "+ bInt);
System.out.println("It was found at Index: "+ index);
I am doing the Hackerrank questions to get better at solving puzzles. I've been working on the Simple Sum Array question in the Data Structures section for nearly 2 hours O_O
I seriously thought I solved it because I tested it on the terminal on my mac and it ran fine, but when I submit the code in Hackerrank, it failed all 3 test cases T_T
I don't understand where the problem is and why the test cases failed. Does anyone see the problem? Please help.
Below is the code:
import java.io.*;
import java.util.*;
public class Solution {
public static int sumArray( int[] arr ){ //arr stands for the array to pass in
int result = 0;
for (int i = 0; i < arr.length; i++){
result = result + arr[i];
}
return result;
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner input = new Scanner(System.in);
System.out.println("Print out the size of the array: ");
int size = input.nextInt();
int[] array = new int[size];
System.out.println("Type out the numbers you want in the array. One line only, each number is separated by a space");
String numbers = null;
String[] splitString = null;
while ( input.hasNextLine() ){
numbers = input.nextLine();
splitString = numbers.split("\\s");
if (splitString.length == size){
break;
}
}
//splitString = numbers.split("\\s");
int i = 0;
for (String s : splitString){
//System.out.println(s);
array[i] = Integer.parseInt(s);
i++;
}
System.out.println( sumArray(array) );
}
}
Also, here's the Hackerrank question to clarify what they wants:
Given an array of integers, can you find the sum of its elements?
Input Format:
The first line contains an integer, denoting the size of the array.
The second line contains space-separated integers representing the array's elements.
Output Format:
Print the sum of the array's elements as a single integer.
Sample Input:
6
1 2 3 4 10 11
Sample Output:
31
From the first time seeing your code you have two issues:
1- arr.length should be arr.length - 1
Because, your iteration starts from 0 and length not
2- the way you print your array is wrong
Because, you should use something like this:
Arrays.toString(array)
Use a one-dimensional array to solve the following problem:
Write an application that inputs five numbers, each between 10 and 100, inclusive. As each number is read, display it only if it’s not a duplicate of a number already read. Provide for the “worst case,” in which all five numbers are different. Use the smallest possible array to solve this problem. Display the complete set of unique values input after the user enters each new value.
My program is running fine for the most part. The only problem I'm facing is when i input the second element of the array to check when the first one is asked to input, it outputs "the number is not in the array". Even though the number is in the array. Please go easy on me because i am pretty naive with programming.
import java.util.Scanner;
public class DuplicateElimination {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// the variable to read the number
int number = 0;
// the array with the elements needed to be checked
int [] array = {12, 33, 54, 90, 100, 1};
// for loop to ask the question if the number is in the array.
for(int counter = 0; counter < array.length; counter++ )
{
System.out.print("Enter a number to check: ");
number = input.nextInt();
if (number == array[counter])
System.out.printf("The number %d is already in the array.\n\n", array[counter]);
else
System.out.printf("The number %d is not in the array.\n\n", number);
}
}
}
P.S this is not a homework I'm just doing it to keep me in practice.
Using this condition:
if (number == array[counter])
You're evaluating if the current value of number is equals to a single value inside the array. In order to evaluate if the value of number is stored in array is to check all the values inside array. Here's an example of how to achieve it:
boolean found = false;
for (int j = 0; j < currentSizeOfArray; j++) {
if (number == array[j]) {
found = true;
break;
}
}
if (found) {
//do something
}
Another hint to solve your homework: use a while loop to read the data, not a for loop. Also, have a temporal variable that maintains the current number of elements in the array, which is not the same as the length of the array.