Hello I'm trying to make a code that takes three integers from the command line and sorts them into the min, mid, and max values. I can't figure out the mid programming. It won't always sort them properly. Can you help?
public class SortInteger{
public static int max3(int a, int b, int c) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
return max;
}
public static int min3(int a, int b, int c) {
int min = a;
if (b < min) min = b;
if (c < min) min = c;
return min;}
public static int sort(int a, int b, int c){
int sort = a;
if (sort > b && sort < c) sort = a;
else sort = b;
if (sort > a && sort < c) sort = b;
else sort =c;
if (sort > c && sort < a) sort = c;
else sort =b;
if (sort > c && sort < b) sort = c;
else sort = b;
if (sort > a && sort < b) sort = c;
else sort = c;
return sort;
}
public static void main(String[] args){
int a= Integer.parseInt(args [0]);
int b=Integer.parseInt(args[1]);
int c=Integer.parseInt(args[2]);
StdOut.println("Min is " + min3(a, b, c));
StdOut.println("Mid is " + sort(a, b, c));
StdOut.println("Max is " + max3(a, b, c));
}
}
Try:
public static int mid(int a, int b, int c){
return a + b + c - max(a,b,c) - min(a,b,c);
}
Also for the min and max just use Math:
public static int min(int a, int b, int c){
return Math.min(Math.min(a,b),c);//Replace with Math.max for max.
}
You're stepping all over your own toes inside the sort function. Take, for instance, your first two if statements:
if (sort > b && sort < c) sort = a;
else sort = b;
if (sort > a && sort < c) sort = b;
else sort =c;
If a is between b and c, your first if statement will be true, and sort will be kept as the value of a. But, then consider your next one. The value in a will not be greater than a, so the second if statement will be false, and change sort to c, even though you already found a to be the middle value. Not what you wanted. To fix this, you could change the code you execute when your if statements are true to just return the value of sort. So, like:
if (sort > b && sort < c) return sort;
else sort = b;
if (sort > a && sort < c) return sort;
else sort =c;
// etc.
Try the following:
public class SortInteger
{
//use general sorting algorithm for arbitrary length, this is for 3 length specifically
public static int[] sort(int[] inputs)
{
int k;
if(inputs[0] >= inputs[1])
{
k = inputs[0];
inputs[0] = inputs[1];
inputs[1] = k;
}
if(inputs[1] >= inputs[2])
{
k = inputs[1];
inputs[1] = inputs[2];
inputs[2] = k;
}
//incase our last element is less than our first we repeat:
if(inputs[0] >= inputs[1])
{
k = inputs[0];
inputs[0] = inputs[1];
inputs[1] = k;
}
return inputs
}
public static void main(String[] args)
{
int[] x = new int[3];
x[0] = Integer.parseInt(args[0]);
x[1] = Integer.parseInt(args[1]);
x[2] = Integer.parseInt(args[2]);
x = sort(x);
System.out.println("min is: " + x[0]);
System.out.println("mid is: " + x[1]);
System.out.println("max is: " + x[2]);
}
}
Related
How I find among all pairs a and b with a "least common multiple" LCM(a,b) = 498960 and a "greatest common divisor" GDM(a, b) = 12 a pair with minimum sum a + b?
I solved this with O(n^2) time:
public class FindLcmAndGcdClass {
private int findGcd(int a, int b) {
if (a % b == 0) {
return b;
}
return findGcd(b, a % b);
}
private int findLcm(int a, int b, int gcd) {
return (a * b) / gcd;
}
private void run() {
int minSum = Integer.MAX_VALUE;
int foundNumberOne = 0;
int foundNumberTwo = 0;
for (int i = 12; i <= 498960; i += 12) {
for (int j = i; j <= 498960; j += 12) {
int gcd;
if (i < j) {
gcd = findGcd(j, i);
} else {
gcd = findGcd(i, j);
}
int lcm = findLcm(i, j, gcd);
if (gcd == 12 && lcm == 498960 && i + j < minSum) {
minSum = i + j;
foundNumberOne = i;
foundNumberTwo = j;
}
}
}
System.out.println(minSum);
System.out.println(foundNumberOne);
System.out.println(foundNumberTwo);
}
public static void main(String[] args) {
var o = new FindLcmAndGcdClass();
o.run();
}
}
And it executes quite slowly! I guess the problem can be solved with Dynamic Programming. Can anyone help with more fast solution?
I am not sure if this question can be solved with dynamic programming, but I think of a solution with time complexity O(sqrt(LCM * GCD)).
It is well known that for any two integers a and b, LCM(a, b) * GCD(a, b) = a * b. Therefore, you can first calculate the product of the gcd and lcm, (which is 5987520 in this question). Then for all its factors under sqrt(LCM * GCD), let a be one of the factors, then b = LCM * GCD / a. Test if gcd(a, b) = the required gcd, if so calculate the sum a + b, then find the minimum among the sums, and you are done.
This question already has answers here:
Sort 4 numbers without array
(2 answers)
Closed 5 years ago.
I have a homework where I'm supposed to prompt the user to enter five numbers and arrange them from min to max and since we didn't take arrays
I'm only left with Math.min & Math.max or if statement.
I wrote a code where the first, second and last number are always correct But I can't seem to figure out how to do the 3rd and 4th number
Here's an example:
if (a <= b && a <= c && a <= d && a <= e) {
System.out.println("Numbers in Ascending order "
+ a + " " +Math.min(Math.min(b, c), Math.min(d, e)) +
" " + "?" +
" " + "?" +
" " +Math.max(Math.max(b, c), Math.max(d, e)));
}
If you know any idea that might help me solve this task?
Here is one possible solution
public static void main(String... args) {
int a = 32;
int b = 42;
int c = 2;
int d = 88;
int e = 92901;
int counter = 0;
while (counter < 5) {
int currentMin = findMin(a, b, c, d, e);
// Printing smallest number yeat
System.out.print(currentMin + " ");
if (a == currentMin){
a = Integer.MAX_VALUE;
}
if (b == currentMin){
b = Integer.MAX_VALUE;
}
if (c == currentMin){
c = Integer.MAX_VALUE;
}
if (d == currentMin){
d = Integer.MAX_VALUE;
}
if (e == currentMin){
e = Integer.MAX_VALUE;
}
counter++;
}
}
private static int findMin(int a, int b, int c, int d, int e) {
int smallest = Math.min(a, Math.min(b, Math.min(c, Math.min(d, e))));
return smallest;
}
Notice how I am using the Integer.MAX_VALUE to remove the smallest number yeat for example in the first iteration 2 will be returned which is equals to c now I have to make the code somehow to ignore c in the next iteration because it was already used if I was using the Integer object i could have set c to be null but int cannot be setted to null so what i can do is to set it to number so large that findMin function would never choose it again that's why I use MAX_VALUE
If you have to do it using if,else if statements then you will have to write one if statement and 119 else if statements i.e. number of ways in which 5 numbers can be arranged. 5!=120.
if you are allowed to use for loop check this link
int aux;
if (b < a){
aux = b; b = a; a = aux;
}
if (c < a){
aux = c; c = b; b = a; a = aux;
}
else{
if (c < b){
aux = c; c = b; b = aux;
}
}
...
I guess you get the idea, in the end a will be the smallest and e will be the biggest
For more information, since it looks like you're getting started to programming and sorting algorithms, this is called Insertion Sort (I believe). More information here https://en.wikipedia.org/wiki/Insertion_sort
This is a possible answer. Since loop and arrays cannot be used, much of the code is repetition. In the end a,b,c,d,e contain the values arranged from min to max. Hope this helps.
import java.io.*;
class SortFiveElements {
//utility function
//returns index as a:1, b:2, c:3, d:4, e:4
public static int find_min_index(int a,int b, int c,int d, int e, int min)
{
return a==min?1:(b==min?2:(c==min)?3:(d==min?4:5));
}
public static void main (String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int a = Integer.parseInt(br.readLine());
int b = Integer.parseInt(br.readLine());
int c = Integer.parseInt(br.readLine());
int d = Integer.parseInt(br.readLine());
int e = Integer.parseInt(br.readLine());
//temp is a temporary var to store the i-th value which may get replaced
//smallest stores the min value among i-th to 5th element
//idx stores the minimum value's index
int temp,smallest,idx;
//i=1, i.e element 'a'
//temp has value of 1st element that is a
//find minimum among 5 elements in 'smallest', its index in 'idx'
//then swap
temp = a;
smallest = Math.min(a,Math.min(b,Math.min(c,Math.min(d,e))));
idx = find_min_index(a,b,c,d,e,smallest);
a = smallest;
if(idx==1)
a=temp;
else if(idx==2)
b = temp;
else if(idx==3)
c = temp;
else if(idx==4)
d = temp;
else
e = temp;
//i=2, i.e element 'b'
//temp has value of 2nd element that is b
//find minimum among 4 elements in 'smallest', its index in 'idx'
//NB: a already has the smallest value, so replace a with MAX_VALUE while finding index
//then swap
temp = b;
smallest = Math.min(b,Math.min(c,Math.min(d,e)));
idx = find_min_index(Integer.MAX_VALUE,b,c,d,e,smallest);
b = smallest;
if(idx==1)
a=temp;
else if(idx==2)
b = temp;
else if(idx==3)
c = temp;
else if(idx==4)
d = temp;
else
e = temp;
//repeat above process for 'c' and 'd'.
//'e' will automatically fall in place
temp = c;
smallest = Math.min(c,Math.min(d,e));
idx = find_min_index(Integer.MAX_VALUE,Integer.MAX_VALUE,c,d,e,smallest);
c = smallest;
if(idx==1)
a=temp;
else if(idx==2)
b = temp;
else if(idx==3)
c = temp;
else if(idx==4)
d = temp;
else
e = temp;
temp = d;
smallest = Math.min(d,e);
idx = find_min_index(Integer.MAX_VALUE,Integer.MAX_VALUE,
Integer.MAX_VALUE,d,e,smallest);
d = smallest;
if(idx==1)
a=temp;
else if(idx==2)
b = temp;
else if(idx==3)
c = temp;
else if(idx==4)
d = temp;
else
e = temp;
//we have the values in sorted order in a,b,c,d,e
System.out.println(a+" "+b+" "+c+" "+d+" "+e);
}
}
My goal is to sort an matrix with events according to their dates (Stored in the matrix as events[eventIndex][1]. Somehow I get the almost correct output, except the section showed in bold
Do i have to sort the year, months, and days seperately?
Or do I have som logical error in my compare method?
Before sorting:
12/24/2015
12/19/2015
12/30/2015
11/13/2015
12/30/2015
01/15/2016
12/31/2015
01/15/2016
12/24/2015
12/19/2015
12/31/2015
01/15/2016
After sorting:
11/13/2015
12/19/2015
12/19/2015
12/24/2015
12/24/2015
12/30/2015
12/31/2015
12/30/2015
12/31/2015
01/15/2016
01/15/2016
01/15/2016
Here is my code.
public void quickSort(String[][] event, int low, int high, Compare c) {
if (event == null || event.length == 0)
return;
if (low >= high)
return;
// pick the pivot
int middle = low + (high - low) / 2;
// make left < pivot and right > pivot
int i = low, j = high;
while (i <= j) {
while (c.compare(i, middle)) {
i++;
}
while (c.compare(middle, j)) {
j--;
}
if (i <= j) {
String[] temp = event[i];
event[i] = event[j];
event[j] = temp;
i++;
j--;
}
}
// recursively sort two sub parts
if (low < j)
quickSort(event, low, j,c);
if (high > i)
quickSort(event, i, high,c);
}
//Interface for comparing two types
public interface Compare {
boolean compare(int first, int second);
}
public class CompareDate implements Compare {
#Override
public boolean compare(int first, int second) {
//Splitting up the date string and converts into int
//Splitting first index
String[] temp = event[first][1].split("/");
int firstYear = Integer.parseInt(temp[2]);
int firstMonth = Integer.parseInt(temp[0]);
int firstDay = Integer.parseInt(temp[1]);
//Splitting second index
temp = event[second][1].split("/");
int secondYear = Integer.parseInt(temp[2]);
int secondMonth = Integer.parseInt(temp[0]);
int secondDay = Integer.parseInt(temp[1]);
//Comparing the values
if (firstYear < secondYear) return true;
else if (secondYear < firstYear) return false;
else if (firstMonth < secondMonth) return true;
else if (secondMonth < firstMonth) return false;
return (firstDay < secondDay);
}
}
Here is a nice solution using recursion. It may not be optimal but it works fine.
public static void quickSort(String[] event) {
String temp;
int a, b, c, d, e, f;
// Sorting years
for (int i = 0 ; i < event.length - 1 ; i++){
a = Integer.valueOf(event[i].split("/")[2]);
b = Integer.valueOf(event[i+1].split("/")[2]);
// Sorting years
if (a > b){
temp = event[i];
event[i] = event[i+1];
event[i+1] = temp;
quickSort(event);
} else if (a == b){
c = Integer.valueOf(event[i].split("/")[0]);
d = Integer.valueOf(event[i+1].split("/")[0]);
// Sorting months
if (c > d){
temp = event[i];
event[i] = event[i+1];
event[i+1] = temp;
quickSort(event);
} else if (c == d){
e = Integer.valueOf(event[i].split("/")[1]);
f = Integer.valueOf(event[i+1].split("/")[1]);
// Sorting days
if (e > f){
temp = event[i];
event[i] = event[i+1];
event[i+1] = temp;
quickSort(event);
}
}
}
}
}
The simpler approach I can think of is converting the dates into a long and then comparing them. It is simpler.
The other option would be using the Java Calendar class.
https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
I am trying to create a recursive algorithm that determines if a String c is an ordered shuffle of Strings a and b. An ordered shuffle means that String c is made up by interspersing the characters of String a and b in a way that still maintains the left to right order of the two strings.
I have attempted the code for this algorithm and it works to some extent, however i have come across a problem when trying to test for a certain shuffled word as can be seen in my code below. I believe this is something to do with index errors in my if statements, however cannot figure out a way to fix this statement or go around it, any feedback or guidance would be very much appreciated.
public class StringShuffleTest {
public static boolean isOrderedShuffle(String a, String b, String c){
//boolean to determine if String c is an ordered shuffle.
boolean isShuffled = false;
//variables for the size of Strings a, b and c.
int n = a.length();
int m = b.length();
int len = c.length();
//if the length of c is not the length of a + b return false.
if (len != (n + m)){
return isShuffled;
}
//if the length of a or b is 0, and c equals a or b, return true, otherwise,
//return false.
if (n == 0 || m == 0){
if (c.equals(a) || c.equals(b)){
return true;
}
else
return isShuffled;
}
//if String a has length 1, remove String a from String c and make String a empty.
if (n == 1){
c = c.substring(0, c.indexOf(a.charAt(0))) + c.substring(c.indexOf(a.charAt(0)) +1);
a = "";
return isOrderedShuffle(a, b, c);
}
else
//Recursive algorithm to determine if String c is an ordered shuffle of a and b.
if (c.indexOf(a.charAt(0)) >= 0){
int indexOfFirst = c.indexOf(a.charAt(0));
int indexOfSecond = c.indexOf(a.charAt(1));
if (indexOfFirst <= indexOfSecond){
c = c.substring(0, indexOfFirst) + c.substring(indexOfFirst +1);
a = a.substring(1, n);
System.out.println(a);
System.out.println(c);
return isOrderedShuffle(a, b, c);
}
else
return isShuffled;
}
return isShuffled;
}
public static void main(String[] args) {
System.out.println(StringShuffleTest.isOrderedShuffle("castle", "cat", "catcastle"));
}
}
You could simplify this by creating a method which calls the recursive method, e.g.:
private static String a, b, c;
public static boolean isOrderedShuffle(String a, String b, String c) {
if (a.length() + b.length() != c.length())
return false;
StringShuffleTest.a = a; StringShuffleTest.b = b; StringShuffleTest.c = c;
return isOrderedShuffle(0, 0);
}
private static boolean isOrderedShuffle(int n, int m) {
if (n + m == c.length())
return true;
if (n < a.length() && a.charAt(n) == c.charAt(n + m) && isOrderedShuffle(n + 1, m))
return true;
if (m < b.length() && b.charAt(m) == c.charAt(n + m) && isOrderedShuffle(n, m + 1))
return true;
return false;
}
You are given a sequence A of N (N <= 50000) integers between -10000 and 10000. On this sequence you have to apply M (M <= 50000) operations:
modify the i-th element in the sequence or for given x y print max{Ai + Ai+1 + .. + Aj | x<=i<=j<=y }.
Problem Link
I am using Segment Tree for this but i am not getting the correct output , please Help me where i have committed the mistake
CODE:
Making a Tree:
public static void maketree(int current , int a , int b ,int[] arr){
if(b<a) return;
if(b==a) {dp[current] = arr[a]; return ;}
maketree(2*current, a, (a+b)/2, arr);
maketree(2*current+1,1+ (a+b)/2, b, arr);
if(dp[2*current]>0 && dp[2*current+1]>0) dp[current] = dp[2*current] + dp[2*current+1];
else if(dp[2*current]>dp[2*current+1]) dp[current] = dp[2*current];
else dp[current] = dp[2*current+1];
}
Updating Function
public static void update(int current , int a , int b , int c , int value){
if(a>b || c<a || c>b) return ;
if(a==b){ dp[current] = value; return ; }
update(2*current, a, (a+b)/2, c, value);
update(2*current+1, (b+a)/2 +1, b, c, value);
if(dp[2*current]>0 && dp[2*current+1]>0) dp[current] = dp[2*current] + dp[2*current+1];
else if(dp[2*current]>dp[2*current+1]) dp[current] = dp[2*current];
else dp[current] = dp[2*current+1];
}
Query Function:
public static int query(int current , int a , int b , int i , int j){
int ans =0;
if(a>j || b<i || a>b) return Integer.MIN_VALUE;
if(a>=i && b<=j) return dp[current];
int x = query(2*current, a, (a+b)/2, i, j);
int y = query(2*current+1, (a+b)/2 +1, b, i, j);
if(x>0 && y>0) ans= x+y;
else if(x>y) ans = x;
else ans =y;
return ans;
}
I don;t know where i have made mistake please help , What will storage capacity required for dp array i.e. size of dp
when you are merging two nodes,then it may be like given below.execute any simple example so that you can feel it :)
void merge(node a , node b)
{
sum = a.sum + b.sum;
pre = max(a.pre , (a.sum + b.pre));
suf = max(b.suf , (b.sum + a.suf));
result = max(a.suf + b.pre,max(a.result , b.result));
}
it is quite overcomplicated imo...
int tree[1 << 17]; // 2 ^ 17 >= N * 2
int M = 1; //base of tree or sth i dont remember english name
int query(int L, int R){
int res = -10000; //minimum possible value in array
L += M - 1;
R += M - 1;
while(L <= R){
if(L % 2 == 1) res = max(res, tree[L++];
if(R % 2 == 0) res = max(res, tree[R++];
L /= 2;
R /= 2;
}
return res;
}
void update(int v, int value){
v += M - 1;
tree[v] = value;
while(v > 0){
v /= 2;
tree[v] = max(tree[v * 2], tree[v * 2 + 1]);
}
}
void make_tree(){
int n;
cin >> n;
while(M < n) M *= 2; // M is half of the size of tree
for(int i = 0;i < n;i++)
cin >> tree[i + M]; // just reading input to tree;
for(int i = M - 1;i > 0;i--) // first update for all nodes other than leafs
tree[i] = max(tree[i * 2], tree[i * 2 + 1]);
}