I'm confused as to what I should return from:
public static double min(double[] array) {
double[] tenDoubles = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + tenDoubles.length + " numbers: ");
for (int i = 0; i < tenDoubles.length; i++){
tenDoubles[i] = input.nextDouble();
}
for (int j = 0; j < tenDoubles.length; j++) {
double currentMin = tenDoubles[j];
double currentMinIndex = j;
for (int k = j; k < tenDoubles.length; k++) {
if (currentMin > tenDoubles[k]) {
currentMin = tenDoubles[k];
currentMinIndex = k;
}
}
}
}
How do I return a value from this method and print out the minimum double the user inputs?
By using java api you can find minimum number
To find minimun convert our array tenDoubles to List and then find the minimum using Collections.min() method.
In your code I have done modification to resolve issue
I have modified your code, you are taking input at two places from user.
1. In min() method you are taking input using scanner.
2. you are not using double[] array passed as parameter to min() method.
Pass your array as parameter to min() method It will find out minimum value ans pass result.
public class Main {
public static void main(String[] args) {
double[] tenDoubles = new double[10];
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + tenDoubles.length + " numbers: ");
for (int i = 0; i < tenDoubles.length; i++){
tenDoubles[i] = input.nextDouble();
}
System.out.println(min(tenDoubles));
}
public static double min(double[] tenDoubles) {
double currentMin=Integer.MAX_VALUE;
for (int j = 0; j < tenDoubles.length; j++) {
if (tenDoubles[j]< currentMin) {
currentMin = tenDoubles[j];
}
}
return currentMin;
}
}
Improved code:
public static double min() {
double[] tenDoubles = new double[10];// = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + tenDoubles.length + " numbers: ");
for (int i = 0; i < tenDoubles.length; i++){
tenDoubles[i] = input.nextDouble();
}
double currentMin = tenDoubles[0];
for (int j = 1; j < tenDoubles.length; j++) {
if (currentMin > tenDoubles[j]) {
currentMin = tenDoubles[j];
}
}
return currentMin;}
Your example needs restructuring. Read in your values into an array first and then pass this array as a parameter to your min function. To return the minimum, add
return currentMinIndex;
Finally use System.out.println to print the value returned.
Your min function will then look like
public static double min(double[] array) {
for (int j = 0; j < array.length; j++) {
double currentMin = array[j];
double currentMinIndex = j;
for (int k = j; k < array.length; k++) {
if (currentMin > array[k]) {
currentMin = array[k];
currentMinIndex = k;
}
}
}
return currentMinIndex;
}
though it is not necessary to go through the array twice.
You just need to keep track of the min value (which you are doing) and have it compared to each other element in the array. If the next element is less, then you change out the values.
// This will hold what the minimum value is
double currentMin = 0;
// The current value from the tenDoubles array
double currentValue;
// loop through each element of the array
for (int j = 0; j < tenDoubles.length; j++) {
// get the current value from the array
currentValue = tenDoubles[j];
// if this is the first element, then just set the minimum to this value
if (j ==0) {
// Set the value as the minimum
currentMin = currentValue;
}else {
// if the current value is less that what is already saved as the minimum,
// set it as the new minimum
if (currentValue < currentMin) {
currentMin = currentValue;
}
}
}
System.out.println("Minimum value: " + currentMin);
return currentMin;
UPDATE
If you don't have to use the for-loops, you can shorten this up a lot by just doing this:
public static double min(double[] array) {
Arrays.sort(array);
return array[0];
}
Related
I am trying to develop a program to delete all the median values from an array (the middle value if it has an odd number of elements, the two middle values if it has an even number of elements) until there are only two elements left, elements [0] and [1]. For example, if the user inputs 1, 2, 3, 4, 5, the program will return [1, 5]. I put down what I thought logically might help, but my array x isn't copying myArray in the for loops. I am not looking for someone to completely do the code for me, just to point out where I am wrong. Here is my code:
import java.util.*;
public class Deletion
{
public static void main(String[]args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the array length:");
int [] myArray = new int[kb.nextInt()];
int [] x = new int[myArray.length - 1];
int index1 = 0;
int index2 = 0;
int index3 = 0;
if(myArray.length < 3)
{
System.out.println("Please make sure array length is greater than two. Run again.");
System.exit(0);
}
else
{
for(int i = 0; i < myArray.length; i++)
{
System.out.println("Please enter a number for position " + i + ":");
myArray[i] = kb.nextInt();
}
for(int i = 0; i < myArray.length; i++)
{
while(myArray.length > 2)
{
if(myArray.length%2 != 0)
{
index1 = (myArray.length/2);
for(int j = 0, r = 0; j < myArray.length; j++)
{
if(j != index1)
{
x[r++] = myArray[j];
myArray = x;
}
}
x = new int[myArray.length - 1];
}
else
{
index2 = (myArray.length/2);
index3 = (myArray.length/2 - 1);
for(int j = 0, r = 0; j < myArray.length; j++)
{
if(j != index2 && j != index3)
{
x[r++] = myArray[j];
myArray = x;
}
}
x = new int[myArray.length - 1];
}
}
}
}
System.out.println(Arrays.toString(myArray));
}
}
You must create the array and populate it, else it's using the same memory address, hence won't work. Use the following:
myArray = ArrayUtils.clone(x);
When you are doing do “myArray = x”, your are actually merely assigning a reference to the array. Hence, if you make any change to one array, it would be reflected in other arrays as well because both myArray and x are referring to the same location in memory.
Thus, what you need is
myArray = x.clone();
I cleaned up your code a bit. According to what you described, what really matters is pulling in the minimum and maximum values in the array - everything else will be deleted, so you simply need a single traversal through the array to find those two values.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean isValid = false;
int validLength = 0;
System.out.println("Please enter the array length:");
while (!isValid) {
int length = scanner.nextInt();
if (length < 3) {
System.out.println("Please make sure array length is greater than two. Try again.");
}
else {
isValid = true;
validLength = length;
}
}
int minimumValue = Integer.MAX_VALUE, maximumValue = Integer.MIN_VALUE;
for (int i = 0; i < validLength; i++) {
System.out.println("Please enter a number for position " + i + ":");
int nextInt = scanner.nextInt();
if (nextInt < minimumValue) minimumValue = nextInt;
else if (nextInt > maximumValue) maximumValue = nextInt;
}
System.out.println(Arrays.toString(new int[] {minimumValue, maximumValue}));
}
Edit: made another revision as using an array is unnecessary. Just keep track of the minimum and maximum values as they are being entered.
Java Array List is overriding the data added and put the last items added only.
The output expected is 1.0, 1.0, -1.0,-1.0, -1.0, 1.0,-1.0, -1.0, -1.0,-1.0, -1.0, -1.0
But, the output I get is -1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0 .
The code override the list by last array elements which is a=[-1,-1,-1,-1]. That is why all 12 elements of the list value is overridden to -1.
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args){
double sum=0; int n=0,y=0,count=0,x=1;
double []a=new double []{1,0,1};
double []b=new double [a.length];
List<double[] >mylist= new ArrayList<>();
double [][]c=new double[][]{{0,0.66,0.66},{0.66,0,0.66},{0,0.66,0}};
mylist.add(0,a);
while(n>=0 && n<4){
for (int i = 0 ; i < 3 ; i++)
for (int j = 0 ; j < a.length; j++)
{
sum=sum+(c[i][j]*a[j]);
if(j==a.length-1)
{
if(sum>0)
sum=1;
else
sum=-1;
b[y]=sum;
y++;
count++;
sum=0;
}
if(count==a.length){
mylist.add(x,b);
x++;
y=0;
count=0;
for(int k=0;k<a.length;k++){
a[k]=b[k];
}
}
}n++;
}
for (int i = 0 ; i < mylist.size(); i++)
for (int j = 0 ; j < a.length ; j++)
{
System.out.print(mylist.get(i)[j]+",");
}
}
}
Arrays in Java are passed by reference to methods, you can check this link for detailed explanation "pass by referece and pass by value" for more about Java parameter passing.
In you code, you just have multiple references of array a and array b. So that is why when their values change all initial values also change. you can use a debugger and you will see it starts changing from the second insertion of b to the ArrayList.
To fix this create a copy of array a at the beginning (whose content will not change). for each new insertion, create a temporary array to hold the values and insert them to your ArrayList.
Below is a fix
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
double sum = 0;
int n = 0, y = 0, count = 0, x = 1;
double[] a = { 1, 0, 1 };
// Create a copy of a to insert at the beginning
double[] acpy = new double[] { 1, 0, 1 };
double[] b = new double[a.length];
List<double[]> mylist = new ArrayList<>();
double[][] c = new double[][] { { 0, 0.66, 0.66 }, { 0.66, 0, 0.66 }, { 0, 0.66, 0 } };
mylist.add(0, acpy);
double[] temp ;
while (n >= 0 && n < 4) {
// this will create a new reference whenever you are about to insert a new element
temp = new double[a.length];
for (int i = 0; i < 3; i++)
for (int j = 0; j < a.length; j++) {
sum = sum + (c[i][j] * a[j]);
if (j == a.length - 1) {
if (sum > 0)
sum = 1;
else
sum = -1;
b[y] = sum;
// copy values of b for insertion to ArrayList
temp[y] = sum;
y++;
count++;
sum = 0;
}
if (count == a.length) {
mylist.add(x, temp);
x++;
y = 0;
count = 0;
for (int k = 0; k < a.length; k++) {
a[k] = b[k];
}
}
}
n++;
}
for (int i = 0; i < mylist.size(); i++)
for (int j = 0; j < a.length; j++) {
System.out.print(mylist.get(i)[j] + ",");
}
}
}
I'm trying to sort an array by the number of digits in each element from largest to smallest. This technically works but it seems to sort the array by value as well. For example, instead of printing out 1234 700 234 80 52, it should print 1234 234 700 52 80 as 234 is before 700 in the original array.
public class Sort {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {52, 234, 80, 700, 1234};
int temp = 0;
//Displaying elements of original array
System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
//Sort the array in descending order
//Math function is used to find length of each element
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(Math.log10(arr[i]) + 1 < Math.log10(arr[j]) + 1) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println();
//Displaying elements of array after sorting
System.out.println("Elements of array sorted in descending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
The easiest way to find the length of the number is to convert it into a String and then call the method length on it.
int number = 123;
String numberAsString = String.valueOf(number);
int length = numberAsString.length(); // returns 3
But you also could do it by division. The following method takes a number and divides by multiples of 10.
divide by 1 (we have at least a length of 1)
division by 10 > 0 (we have at least a length of 2)
division by 100 > 0 (we have at least a length of 3)
...
the variable i is used as dividend and the variable j is used as counter. j counts the length of the number.
As soon as number / i equals zero we return the counter value.
public int lengthOfNumber(int number) {
if (number == 0) {
return 1;
}
for (int i = 1, j = 0; ; i *= 10, j++) {
if (number / i == 0) {
return j;
}
}
}
There are multiple ways to sort the array. Here are some examples (I used the string version for comparing the values).
Use nested for-loop
public void sortArray(int[] array) {
for (int i = 0; i < array.length; i++) {
int swapIndex = -1;
int maxLength = String.valueOf(array[i]).length();
for(int j = i + 1; j < array.length; j++) {
int length2 = String.valueOf(array[j]).length();
if (maxLength < length2) {
maxLength = length2;
swapIndex = j;
}
}
if (swapIndex > -1) {
int temp = array[i];
array[i] = array[swapIndex];
array[swapIndex] = temp;
}
}
}
I used a variable swapIndex which is initialized with -1. This way we can avoid unnecessary array operations.
We take the first element in the outer for-loop and go through the rest of the array in the inner for-loop. we only save a new swapIndex if there is a number in the rest of the array with a higher length. if there is no number with a higher length, swapIndex remains -1. We do a possible swap only in the outer for-loop if necessary (if swapIndex was set).
Using Arrays.sort()
If you want to use Arrays.sort you need to convert your array from primitive type int to Integer.
public void sortArray(Integer[] array) {
Arrays.sort(array, (o1, o2) -> {
Integer length1 = String.valueOf(o1).length();
Integer length2 = String.valueOf(o2).length();
return length2.compareTo(length1);
});
}
Using a recursive method
public void sortArray(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
String current = String.valueOf(array[i]);
String next = String.valueOf(array[i + 1]);
if (current.length() < next.length()) {
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
// here you do a recursive call
sortArray(array);
}
}
}
I'm trying to return the mode of a 2D array using a frequency array. I have an array, score, which is of length 10, and has 3 columns. Each column contains an int that is between 0 and 100.
I'm trying to find a way that will iterate through the array and return the modal value. What I have so far is:
int value = 0;
int[] freq = new int[100];
for (int row = 0; row < score.length; row++) {
for (int col = 0; col < score[row].length; col++) {
score[row][col] = value;
freq[value]++;
}
}
int largest = 0;
int mode = -1;
for (int i = 0; i < 100; i++) {
if (freq[i] > largest)
{
largest = freq[i];
mode = i;
}
}
System.out.println("modal score is: " +mode);
Problem is that this is just returning the modal score as 0, which it isn't.
You have a problem on generating the freq array. If I understand correctly, on the first double-for block you are trying to put the frequencies of the numbers inside the freq array.
But all you do is:
int value = 0;
.....
score[row][col] = value;
freq[value]++;`
firstly you are changing the score array,( which is a problem for you I guess...) and the you go to freq[0] and do ++. Obviously modal is 0, that number appears in all of the array.
SOLUTION: in the first double for block you should do:
value = score[row][col];
freq[value]++;
so I think you mixed up the order of the line, it should be the other way around.
private static void printMode(double[][] doubles) {
HashMap<Double , Double> map = new HashMap();
for (int i = 0; i < doubles.length; i++) {
for (int j = 0; j < doubles[i].length; j++) {
double temp = doubles[i][j];
if(map.get(temp)==null){
map.put(doubles[i][j],1.0);
}else {
double temp2 = (double) map.get(temp);
map.put(doubles[i][j],++temp2);
}
}
}
Object[] objects = map.values().stream().sorted().toArray();
Stream stream = map.entrySet().stream().filter(val-> val.getValue().equals(objects[objects.length-1]));
stream.forEach(System.out::println);
}
I think using Stream for finding mode is the best way.
use int instead of double doesn't cause any problems.
int value = 0;
int [] freq = new int [arr.length];
for (int i = 0; i < arr.length; i++){
for (int j = 0; j < arr[i].length; j++){
value = arr[i][j];
freq[value]++;
}
}
int largest = 0;
int mode = 0;
for (int i = 0; i < freq.length; i++) {
if (freq[i] > largest)
{
largest = freq[i];
mode = i;
}
}
System.out.println("modal score is: " +mode);
I'm not sure how to set the differences to store in the array differences. The numbers stored should be 5-(1+2+3), 7-(1,2,4), 8-(3,5,9) : the output should be differences[0]= 1, differences[1] = 0, differences[2] = 9
import java.util.Scanner;
public class Main {
public static int[][] Array = { { 5, 1, 2, 3 }, { 7, 1, 2, 4 }, { 8,3,5,9 } }; //My 2D array//
int [] differences = new int [3];
public static int[] Sum(int[][] array) {
int index = 0; //setting the index to 0//
int temp[] = new int[array[index].length]; //making a temperary variable//
for (int i = 0; i < array.length; i++) {
int sum = 0;
for (int j = 1; j < array[i].length; j++) {
sum += array[i][j]; //going to add the rows after the first column//
}
temp[index] = sum;
for(int a = 0; a<differences.length; a++){
if(sum != array[index][0])
sum -= array[i][j];
System.out.println("the first integer " + array[index][0] + " the answer is " + sum); //going to print out the first integer each row and print out the sum of each row after the first column//
index++; //index is going to increment//
}
return temp;
}
public static void main(String[] args) {
new Main().Sum(Array);
}
}
Output:
the first integer 5 the answer is 6
the first integer 7 the answer is 7
the first integer 8 the answer is 17
Why do you want to complicate the task of yours when it is this simple? :)
public int[] Sum(int[][] array)
{
int sum;
for(int i = 0; i < Array.length; i++)
{
sum = Array[i][0] * -1;
for(int j = 1; j < Array[i].length; j++)
{
sum += Array[i][j];
}
differences[i] = sum;
}
return differences;
}
If I understand your problem correctly, I think that you want to put a
differences[i] = Array[i][0] - sum
somewhere in your code