How to swapplaces of largest and smallest value - java

I am new at learning Java and I have the following assignment:
Write a program which reads three integers a, b and c from the
keyboard and swaps the places of the largest and smallest among the
three values.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Program to find the largest and smalles value");
System.out.println("Please insert first number:");
int first = scanner.nextInt();
System.out.println("Please insert second number:");
int second = scanner.nextInt();
System.out.println("Please insert:");
int third = scanner.nextInt();
int largest = largest(first, second, third);
int smallest = smallest(first, second, third);
System.out.printf("The biggest value among %d, %d, и %d is : %d %n", first, second, third, largest);
System.out.printf("The smallest value among %d, %d, и %d is : %d %n", first, second, third, smallest);
scanner.close();
}
public static int largest(int first, int second, int third) {
int max = first;
if (second > max) {
max = second; }
if (third > max) {
max = third; }
return max; }
public static int smallest(int first, int second, int third) {
int min = first;
if (second < min) {
min = second; }
if (third < min) {
min = third; }
return min; }

I am not sure what "swap places" mean in this contents, but this is how you swap values (in general)
int smallest = 1;
int largest = 5;
int temp = 0;
temp = largest; // save one number to a temporary variable
largest = smaller; // override the variable you just saved
smaller = temp; // place the "temp" variable value into the second variable
If you were to print out smallest and largest, you'll find that their values are now swapped (largest will be 1 and smallest will be 5).

You don't need to swap anything. Here is how it works.
set a value min to the largest possible value.
set a value max to the smallest possible value.
Now for all your values, simply compare current min to that value and current max to that value and replace them as necessary.
When done, min and max should have their respective values.
Then, if you really want to swap them you can apply the technique that #hfontanez suggested.

The assignment does not ask you to find the largest and smallest values - it states that you should swap the position of the largest and smallest values. This implies that there is an ordering of these values. This is typically modeled as an array. So it sounds like you should be reading the three values into an array. Move your input code into a method with the return type int[]. After reading the input you put them in an array and return.
public static int[] getInputs() {
... read the inputs into first, second, third ...
int[] values = {first, second, third};
return values;
}
Once you have the array of values you need to identify the index of the largest values and the smallest value. You then swap the values at those positions. This is normally done with the help of a temporary variable to hold one of those values.
public static void swapPositionOfLargestAndSmallestValues(int[] values) {
int smallestIndex = findIndexOfSmallestValue(values);
int largestIndex = findIndexOfLargestValue(values);
int temp = values[smallestIndex];
values[smallestIndex] = values[largestIndex];
values[largestIndex = temp;
}
You will need to implement the methods that find the indexes of the largest and smallest values. Then your main looks something like this, where printValues(int[]) is a method that outputs the elements of the array in some fashion.
public static void main(String[] args) {
int[] values = getInputs();
printValues(values);
swapPositionOfLargestAndSmallestValues(values);
printValues(values);
}

Related

Optimize the given Solution without changing the logic of the program. Also calculate the Time Complexity

This is a GFG practice problem hence compiler cannot be configured
Question
Given an array of positive integers. Your task is to find the leaders in the array.
Note: An element of array is leader if it is greater than or equal to all the elements to its right side. Also, the rightmost element is always a leader.
Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N denoting the size of array.
The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.
Output:
Print all the leaders.
Constraints:
1 <= T <= 100
1 <= N <= 107
0 <= Ai <= 107
My Solution :
import java.util.*;
import java.io.*;
import java.lang.*;
public class Main
{
static BufferedReader z1 = new BufferedReader(new InputStreamReader(System.in));
public static void main (String[] args)throws Exception
{
int T=Integer.parseInt(z1.readLine());
while(T-- > 0)
{
int N=Integer.parseInt(z1.readLine());
solution ob = new solution();
int []a=new int[N];
a=ob.input(N,z1);
int x=0;
ob.leader(a,N,x);
}
}
}
class solution
{
static int[] input(int N, BufferedReader z1)throws Exception
{
int a[]=new int[N];
String s=z1.readLine();
String []str=s.split(" ");
/* for(int y=0;y<N;y++)
a[y]=Integer.parseInt(str[y]); */
toInts(str,a,0);
return a;
}
static void toInts(String[] strings, int[] ints, int start) {
if (start > strings.length - 1) {
return;
}
ints[start] = Integer.parseInt(strings[start]);
toInts(strings, ints, start+1);
}
static void leader(int []a,int N,int x)
{
int count = 0;
if(x==N-1)
System.out.println(a[x]);
else
{
count = compare(a,x,x+1,count,N);
/* for(int y=x+1;y<N;y++)
if(a[x]>=a[y])
count++; */
if(count==(N-x-1))
System.out.print(a[x]);
leader(a,N,x+1);
}
}
static int compare(int []a,int x,int y,int count,int N)
{
if(y==N)
return count;
else
{
if(a[x]>=a[y])
count ++;
return compare(a,x,y+1,count,N);
}
}
}
Error :
Runtime Error:
Runtime ErrorTime Limit Exceeded
Your program took more time than expected.Time Limit Exceeded
Expected Time Limit 3.00sec
A problem (and the likely cause for the long time it takes) is that your compare() method doesn't stop once it encounters a larger value and it is therefore obvious that the current element is not a leader. Instead it will always compare all values.
This makes the runtime of your code O(N^2) for an array of size N.
This problem can be solved in O(N).
Start on the right end of the array and print the last element as leader and set it as the current maximum. Then go left and check if the current element is greater or equal than the maximum. If yes print it as a leader and set is as the maximum. Continue until you reach the left end of the array.
You can also probably save some time by replacing your recursive toInts() method with a simple for-loop to convert the strings.

Recursion in Java, sum of k integers after integer m

I need to use recursion to make an algorithm which finds the sum of x integers after an integer m. For example, if m is 2 and n is 5, I would need to find the sum of 2+3+4+5+6 using recursion.
The code I have so far would (for the example illustrated above) works in such way: 2+3+3+3+3. Any help at all is greatly appreciated as I have an exam tomorrow and questions like these may be included.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input a value for n");
int n = input.nextInt();
System.out.println("Input a value for m");
int m = input.nextInt();
System.out.println(sho (m,n));
}
public static int sho (int m, int n){
int sum = 0;
if(n<=0){
return m;
}
sum = sho(m+1,n-1);
sum = sum +(m);
return sum;
}
You only need to implement the summation of a series using recursion. The starting and ending points are really just minor logic. The inductive case of the recursion is is that the current value is less than the end of the series. In this case, we return the current value plus a recursive call with the starting point increased by one. The base case occurs when we reach the end of the series. For the base case, we just return the max value and stop the recursion.
public static int sho(int curr, int max) {
if (curr == max) {
return curr;
}
else {
return curr + sho(curr + 1, max);
}
}
public static void main(String args[]) {
System.out.println(sho(10, 15)); // 10 11 12 13 14 15
}
One problem I see with your code is your recursion logic:
sum = sho(m+1, n-1);
I don't think that decreasing the upper bound is the way to go here. Instead, keep that bound fixed and advance through the series by making another recursive call. Decreasing the upper bound sounds like mixing recursion with an iterative approach.
Demo
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input a value for n");
int n = input.nextInt();
System.out.println("Input a value for m");
int m = input.nextInt();
System.out.println(sho (m,n,0));
}
public static int sho (int m, int n,int sum){
if(n<=0){
return sum;
}
sum=sum+m;
sum = sho(m+1,n-1,sum);
return sum;
}
Try this

how to display the largest number in stack on java

I have that following code with class called stack, and a push method
can you help me please how to make a method that show the maximum ( the largest number ) number in stack? please help me with a very simple code I'm beginner I don't know in java just 5%
class stack1 {
int maxsize,top;
String arr[];
int maxsize1;
stack1 (int maxsize){
this.maxsize=maxsize;
arr=new String[maxsize];
top=0;
}
void push (String data) {
if (top<maxsize) {
arr[top]=data;
top++;
} else {
System.out.print("stack is overflow");
}
}
public static void main(String arg[]) {
stack1 s=new stack1(4);
s.push("1");
s.push("2");
s.push("3");
s.push("4");
}
}
Instead of using all the numbers in a String array as you're doing right now, you should use an integer array (int[]), a floating-point number array (float[]) or a different kind of numeric primitive data type (You can read more about them on the Oracle Java tutorial).
Assuming you name your int[] array arr, you can create a method which loops through all the numbers and will store the highest value which will be returned at the end of the function:
int maximumValue() {
int maximum = Integer.MIN_VALUE;
for (int value : arr) {
if (value > maximum) {
maximum = value;
}
}
return maximum;
}
It's not the most efficient way but sorting does the trick:
Arrays.sort(stack);
System.out.println(Arrays.asList(stack));
System.out.println(stack[stack.length - 1]); //stack[stack.length - 1] is the max
The ordering you get will be lexographic because you are using strings. To use numbers, you can change the stack to integers:
String arr[]; becomes int arr[];
void push (String data) becomes void push (int data)
s.push("4") becomes s.push(4)
To get the max, you can add this method to your class:
int getMax() {
Arrays.sort(arr);
return arr[arr.length - 1];
}
Then you call it like:
int max = s.getMax();

Java Average Program

Write a class called Average that can be used to calculate average of several integers. It should contain the following methods:
A method that accepts two integer parameters and returns their average.
A method that accepts three integer parameters and returns their average.
A method that accepts two integer parameters that represent a range.
Issue an error message and return zero if the second parameter is less than the first one. Otherwise, the method should return the average of the integers in that range (inclusive).
Implement the class and write a program to test its methods and submit your source code (.java files).
I am stuck on part three, I don't even really understand the stipulation. Will I be using a floating point / double? Here is the program I have thus far:
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
int numb1, numb2, numb3, userInput;
System.out.println("Enter '2' if you wish to average two numbers enter '3' if you wish to average 3.");
Scanner keyboard = new Scanner(System.in);
userInput = keyboard.nextInt();
if (userInput == 2){
System.out.println("Enter two numbers you'd like to be averaged.");
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
Average ave = new Average();
System.out.println("The average is: " + ave.average(numb1, numb2));
System.exit(1);
}
if(userInput == 3){
System.out.println("Enter three numbers you'd like to be averaged.");
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
numb3 = keyboard.nextInt();
Average ave = new Average();
System.out.println("The average is: " + ave.average(numb1, numb2, numb3));
System.exit(1);
}
}
public static int average (int num1, int num2) {
return (num1 + num2) / 2;
}
public static int average (int numb1, int numb2, int numb3){
return (numb1 + numb2 + numb3) / 3;
}
}
Please don't re-ask the same question as you just asked here: http://stackoverflow.com/questions/19507108/java-averaging-program
Rather update your other post to reflect your new code / questions.
Now onto your question:
A method that accepts two integer parameters that represent a range. Issue an error message and return zero if the second parameter is less than the first one. Otherwise, the method should return the average of the integers in that range (inclusive). Implement the class and write a program to test its methods and submit your source code (.java files).
Lets start by declaring our method and we'll declare it as static to conform to your program (since you're not creating your own objects). Then we want to check if the parameters follow the assignment instructions and return values accordingly.
public static int getRange(int firstValue, int secondValue)
{
int range;
if (firstValue > secondValue)
range = firstValue - secondValue;
else
{
range = 0;
System.out.println("Error!");
}
return range;
}
**To promote your understanding it's up to you to find the average of the integers in the range!
Not really here to do your homework, but since I'm already here, the range is the difference between the largest and smallest number.
public int returnRange(int first, int second) {
if(first > second)
return first-second;
else
return second-first;
}
To make things easier though...
public double returnAverage(int...numbers) {
for(int i = 0; i < numbers.length(); i++) {
total += numbers;
}
return total/numbers.length();
}
public int returnRange(int...numbers) {
int holder = 0;
int highest;
int lowest;
for(int i = 0; i < numbers.length(); i++) {
if(numbers[i] > holder) {
holder = numbers[i];
}
highest = holder;
for(int i = 0; i < numbers.length(); i++) {
if(numbers[i] < holder) {
holder = numbers[i];
}
}
lowest = holder;
return highest-lowest;
}
Last 2 methods are un-tested, but from experience, should work fine. These methods have arrays for the parameters, so you can do as many numbers as you'd like.
In your main method check for -1 and return error when first value is greater than second
public double avgRange(int a, int b){
if(a>b){
return -1;
}
else{
double total=0;
for(int x=a; x<=b; x++){
total = total + x;
}
return total/(b-a+1);
}
}
the method should return the average of the integers in that range (inclusive).
You're asked to return the average of all integers in the range bounded by the two parameters.
For example, if parameters were 5 and 10, the method should return the average of 5, 6, 7, 8, 9, and 10, which is 7.5. (5 and 10 are included because the question says the range should be "inclusive".)
To find the average, use a for loop to sum each integer in the range, then divide by the number of integers.
Will I be using a floating point / double?
The return value should be a float or double, since the average isn't always a whole number.

array/data set constructor questions

I'm creating a program which takes a user's info and outputs the min, max, average, sum, and counts how many values were in it. I'm really struggling to figure out how to create default constructor of 100 items and the array size which the user is supposed to define.
Create a new DataSet object. The client creating the object specifies the maximum number
of items that can be added to the set. (Write a constructor with one int parameter.)
Also write a default constructor which creates a DataSet capable of handling 100 items.
Add an integer data item to a DataSet. If the maximum number of items have already been added to the set, the item is simply ignored.
Here is my code
import javax.swing.*;
import java.util.*;
public class DataSet {
private int count; // Number of numbers that have been entered.
private double sum; // The sum of all the items that have been entered.
private double min;
private double max;
//Adds numbers to dataset.
public void addDatum(double num) {
count++;
sum += num;
if (count == 1){
min = num;
max = num;
} else if (num < min){
min = num;
} else if (num > max){
max = num;
}
}
public boolean isEmpty()
{
if(count == 0)
{
return true;
}
else
{
return false;
}
}
//Return number of items entered into the dataset.
public int getCount() {
return count;
}
//Return the sum of all the numbers that have been entered.
public double getSum() {
return sum;
}
//Return the average of all the numbers that have been entered.
public double getAvg() {
return sum / count;
}
//return Maximum value of data entered.
public double getMax(){
return max;
}
//return Minimum value of data entered.
public double getMin(){
return min;
}
public static void main (String[] args){
Scanner scanner = new Scanner(System.in);
DataSet calc = new DataSet();
double nextnumber = 0;
while (true){
System.out.print("Enter the next number(0 to exit): ");
nextnumber = scanner.nextDouble();
if (nextnumber == 0)
break;
calc.addDatum(nextnumber);
}
System.out.println("Min = "+calc.getMin());
System.out.println("Max = "+calc.getMax());
System.out.println("Mean = "+calc.getAvg());
System.out.println("Count = "+calc.getCount());
System.out.println("Sum = "+calc.getSum());
}
} //end class DataSet
The syntax for declaring an array is type[] name; (there are variants, but this is the most common)
So an int array is declared as thus:
int[] someIntegers;
Creating a new array can be done several ways. The normal way is to create an empty array with all elements initialised to their default value (zero or false for primitive datatypes, and null for object arrays). The syntax is:
someIntegers = new int[4]; // ie. [0, 0, 0, 0]
// or
int n = ...; // intitalise n some how
someIntegers = new int[n];
// this way we can get different length arrays at runtime
You have to add a variable to hold the max amount of numbers.
int max = 0;
Then you would need the two constructors:
Dataset() {
max = 100;
}
Dataset(int max) {
this.max = max;
}
Then when you get the input, you have to check if you have reached the number limit before you do anything.
System.out.print("Enter the next number(0 to exit): ");
nextnumber = scanner.nextDouble();
if (count < max) {
if (nextnumber == 0) {
break;
}
calc.addDatum(nextnumber);
}
Your code above does not contain any constructors, so only the default DataSet() constructor is available. In your DataSet class, you need to define both constructors to meet your requirements. In addition you will need to create a collection type (ie an array of ints) for storing the numbers added to the dataset (this seems to be part of your requirements). With the code below, when you create an instance of the DataSet class in your main method, you can create it with the default 100 elements by saying
DataSet myDataSet = new DataSet();
or you can create it with a user specified number of elements like
DataSet myDataSet = new DataSet(30); //for thirty elements in the array
public class DataSet {
int[] myArray;
public DataSet() //Zero parameters constructor
{
//initialize your array to 100 elements here
myArray = new int[100]; //the array can hold 100 elements
}
public DataSet(int max) //One parameter constructor
{
//initialize your array to 'max' elements here
myArray = new int[max]; //the array can hold max number of elements
}
public void AddNum(int num)
{
//logic to add number to the array here :P
}
}

Categories

Resources