Array - Time difference in minutes [duplicate] - java

This question already has answers here:
Getting minimum time difference
(4 answers)
Closed 2 years ago.
I have four different timestamps where I have to find the smallest difference in minutes. I'm confused on how to do this.
Example:
String array: ["2:10pm", "1:30pm", "10:30am", "4.42pm"]
How can I find the smallest difference in minutes. Do I use LocalDate?

This will help you to get smallest in minutes from array
public class Main
{
public static void main(String[] args) {
String[] myarr = {"2:10pm", "1:20pm", "10:30am", "4:42pm"};
int index = 0;
int smallest = Integer.parseInt(myarr[0].substring(myarr[0].lastIndexOf(":") + 1,myarr[0].lastIndexOf(":") + 3));
for (int i = 1; i < myarr.length; i++){
int myValue = Integer.parseInt(myarr[i].substring(myarr[i].lastIndexOf(":") + 1,myarr[i].lastIndexOf(":") + 3));
if (myValue < smallest){
smallest = myValue;
index = i;
}
}
System.out.println(myarr[index] + " is smallest in minutes");
}
}

Related

WAP to compute the sum of the first n terms of the following series [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 10 months ago.
S = 1 + 1/2! + 1/3! + 1/4!.....
Here is my code:
import java.util.Scanner;
public class question{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n =sc.nextInt();
int[] fact= new int[n];
fact[0] =fact[1] =1;
for(int i=2;i<=n;i++)
{
fact[i]= fact[i-1]*i;
}
double sum=0;
for(int i=1;i<=n;i++){
sum+=1/fact[i];
}
System.out.println(sum);
}
}
This code is giving error
input:3
Exception in thread "main" java.lang.ArrayIndexOutOfBoindsException: Index 33 out of bounds for length 3 at question.main(question.java.12)
What is the reason for this error? How to resolve it?
The array is one element too small, it should be
int[] fact = new int[n+1];
Also note that sum+=1/fact[i] will be an integer division. You can use
sum += 1.0/ fact[i]
to get a floating point division.
Also you do not need to store the factorials in an array as the purpose is just to sum. You could do the following:
int fact = 1;
double sum = 0;
int n = 15;
for(int i = 1; i<=n; i++){
sum += 1.0/fact;
fact *= i;
}

Is this a optimal way of initializing an array with 1 through 5? [duplicate]

This question already has answers here:
Fill arrays with ranges of numbers
(7 answers)
Closed 2 years ago.
The usage of i - 1 concerns me the most. Should i use another variable for the indexing or is this fine?
public class MainClass {
public static void main(String[] args) {
int[] array = new int[5];
for(int i = 1; i<=array.length; i++) {
array[i-1] = i;
}
for(int x: array)
System.out.println(x);
}
}
Technically, it doesn't matter. However, you may do
for (int i = 0; i < array.length;)
array[i] = ++i;
to generate the same output:
1
2
3
4
5

How to extract integers from a separated string in java [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 4 years ago.
Examples of the String
131-5923-213
1421-41-4-12-4
1-1
How would I extract the integers into an Array or find the sum of these integers? My code so far goes
int hyphenCount = socialNum.length()-socialNum.replaceAll("-", "").length();
ArrayList<Integer> sum = new ArrayList<Integer>();
for(int i = 0; i < hyphenCount; i++)
{
//my brain is too small
}
What I want to do is make a function like the following
public void extractSum(String s)
{
int outputSum;
//stuff
return outputSum;
}
Using Streams you can do:
int sum = Arrays.stream(str.replace("-", "").split("")).mapToInt(Integer::valueOf).sum();
Which will replace the hyphen and then split each character, parse the integer, and return the sum
Output: (For the String "131-5923-213")
30
If you want the sum of 131 + 5923 + 213 you could do:
int sum = Arrays.stream(str.split("-")).mapToInt(Integer::valueOf).sum();
Which will split on a hyphen, parse the integers, and return the sum
Apart from #GBlodgett's answer using stream, you could simply run a for loop to calculate the sum.
String string = "131-5923-213";
String[] num = string.split("-"); //<----num[0] = "131" ,num[1]="5923",num[2] = "213"
int hyphenCount = num.length; //<----it would give you 3 as length
int mySum = 0; //initialize the sum as 0
for(int i = 0; i < hyphenCount; i++)
{
mySum+= Integer.parseInt(num[i]); //<---convert the string to an int
}
Output: 6267

Random generated array does not print small value correctly [duplicate]

This question already has answers here:
minimum value in java won't work
(4 answers)
Closed 4 years ago.
my code is not working because it is always printing small value as 0.
Thanks in advance for your help.
public class Tests {
public static void main(String [] args){
int [] num=new int[10];
Random random= new Random();
//1st time both big and small value will be at 0
int big=num[0];
int small=num[0];
for(int i=0;i<num.length;i++){
num[i]=random.nextInt(10);
System.out.print(num[i] +" ");
if(num[i]>big){
big=num[i];
}
if(num[i]<small){
small=num[i];
}
}
System.out.println();
System.out.println("Big " + big);
System.out.println("Small " + small);
}
}
See below the issue:
Good Result:
5 1 1 3 8 3 5 1 1 0
Big 8
Small 0
Bad Result:
6 8 8 1 7 5 2 6 8 4
Big 8
Small 0
This is because small is 0 and every random value will be generated between 0 and 10, so 0 is the smallest.
To fix it, change to
int small = Integer.MAX_VALUE;
When you initiated the int array int [] num=new int[10]; it assigned zero(0) to all index.
So, when you let int small=num[0]; it contain zero(0)
So, whatever the value are coming, following block always comparing small as zero(0). So, not changing the small variable!
if(num[i]<small){
small=num[i];
}
assign int small=Integer.MAX_VALUE; AND int big=Integer.MIN_VALUE; then it will all work!
Declare int small as:
int small = Integer.MAX_VALUE;
And now it will work.
Note: And also it is better to declare int big as
int big = Integer.MIN_VALUE;
init array in another loop. when you init int array all of them are 0.
public class Test {
public static void main(String[] args) {
int[] num = new int[10];
Random random = new Random();
for (int i = 0; i < num.length - 1; i++) {
num[i] = random.nextInt(10);
}
//1st time both big and small value will be at 0
int big = num[0];
int small = num[0];
for (int i = 0; i < num.length - 1; i++) {
System.out.print(num[i] + " ");
if (num[i] > big) {
big = num[i];
}
if (num[i] < small) {
small = num[i];
}
}
System.out.println();
System.out.println("Big " + big);
System.out.println("Small " + small);
}
}
When you say int [] num=new int[10]; , num array will be initialized with 0 for all 10 places i.e. num[0]= 0, num[1]=0...
and so as suggested by others use int small = Integer.MAX_VALUE;
Always remember, when you initialize something to a variable which stores the biggest, initialize a small value like 0 and for a small variable initialize it with the biggest number possible.

Assign more than one variable to a method [duplicate]

This question already has answers here:
Variable might not have been initialized error
(12 answers)
Initializing multiple variables to the same value in Java
(7 answers)
Closed 5 years ago.
I am trying to assign 3 integer arrays to a method that returns one version. But when i try this it says variable bubbleArray and variable insertionArray have not been initialized. Is there another way to do this and still keep the same original values from the method.
Integer[] bubbleArray,insertionArray,selectionArray = numGenerator();
bubbleSort(radioValue,bubbleArray);
selectionSort(radioValue,selectionArray);
insertionSort(radioValue,insertionArray);
public Integer[] numGenerator() {
Random rn = new Random();
originalOutput.setText("");
sortedOutput.setText("");
referenceArray.clear();
if (number10Button.isSelected()) {
for (int i = 0; i < 10; i++) {
int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
referenceArray.add(answer);
originalOutput.append(referenceArray.get(i).toString() + "\n");
}
} else if (number100Button.isSelected()) {
for (int i = 0; i < 100; i++) {
int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
referenceArray.add(answer);
originalOutput.append(referenceArray.get(i).toString() + "\n");
}
} else if (number1000Button.isSelected()) {
for (int i = 0; i < 1000; i++) {
int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
referenceArray.add(answer);
originalOutput.append(referenceArray.get(i).toString() + "\n");
}
} else if (number5000Button.isSelected()) {
for (int i = 0; i < 5000; i++) {
int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
referenceArray.add(answer);
originalOutput.append(referenceArray.get(i).toString() + "\n");
}
}
Integer[] bubbleArray = referenceArray.toArray(new Integer[referenceArray.size()]);
return bubbleArray;
}
Your code declares 3 Integer[] variables and assigns the last one to what numGenerator() returns.
Integer[] bubbleArray,insertionArray,selectionArray = numGenerator();
Now since you want three arrays, not just three variables pointing to one array you need to make copies of the array, for example with clone(). If you don't make copies you will have one array which is sorted by bubble sort and the other sorting methods will try to sort an already sorted array, which is not what you want.
Integer[] bubbleArray = numGenerator();
Integer[] insertionArray = bubbleArray.clone();
Integer[] selectionArray = bubbleArray.clone();

Categories

Resources