I am having difficulty in making the logic for my scenario which i m considering an array of arrays more specifically said as 2D array.i want to find the maximum value in 2D arrays i do not want to call it in main method.i am making the array as annonymous and calling the function of max from it via static data members.the code is as follows.do let me know the logic to find the greatest no in 2D array as i m finding it difficult to which value to compare with the array.the code is as follows:-
class Max2DArray
{
static int i;
static int j;
static int large;//largest number
int max(int x[][])
{
for(int i=0;i<x.length;i++)
{
for(j=0;j<x[i].length;i++)
{
if(x[i][j]<=???)//what should be the comparison here.
{
??//what should be done here??
}
}
}
return large
}
public static void main(String... s)
{
Max2DArray m1 = new Max2DArray();
int t = m1.max(new int[][]{{20,10,5},
{5,7,6},
{23,31,16}});
System.out.println("the largest number is = "+t);
}
}
I am not going to solve it to you but here is an algorithm
Have a local variable max
assign max to the first value of the array
iterate through the array and change the value of max whenever you find a value greater that the current value of max.
return max
Try this:
int max(int x[][]){
// Initialize the value to the lowest value
int large = Integer.MIN_VALUE;
for(int i = 0; i < x.length; i++) {
for(j = 0; j < x[i].length; j++) {
// Check if the current value is greater than large
if(x[i][j] > large) {
// It is greater so we keep the new value
large = x[i][j];
}
}
}
return large;
}
Using java 8, it could simply be:
int max(int x[][]){
return Arrays.stream(x).flatMapToInt(IntStream::of).max().getAsInt();
}
A Java 8 one-liner, instead of your for loop:
Arrays.stream(x).flatMapToInt(arr2 -> Arrays.stream(arr2)).max().getAsInt();
Related
So this is a coding question from school I have, I don't want to say "hey guys do my homework for me!", I actually want to understand what's going on here. We just started on arrays and they kind of confuse me so I'm looking for some help.
Here's the complete question:
Write a program in which the main method creates an array with
10 slots of type int. Assign to each slot a randomly-generated
integer. Call a function, passing it the array. The called
function should RETURN the largest integer in the array to
your main method. Your main method should display the number
returned. Use a Random object to generate integers. Create it
with
Random r = new Random(7);
Generate a random integer with
x = r.nextInt();
So, here's what I have so far:
import java.util.Random;
public class Q1 {
public static void main(String[] args) {
Random r = new Random(7);
int[] count = new int[11];
int x = r.nextInt();
for (int i = 0; i < count.length; i++)
{
count[i] = x;
}
}
I created that array with 10 ints, then used a for loop to assign each slot that randomly generated integer.
I'm having a hard time for what to do next, though. I'm not sure what kind of method / function to create and then how to go from there to get the largest int and return it.
Any help is really appreciated because I really want to understand what's going on here. Thank you!
Here is how to generate Random ints
public static void main(String[] args) {
int []count = new int[10];
Random r = new Random(7);
int x=0;
for (int i = 0; i < count.length; i++)
{
x = r.nextInt();
count[i] = x;
}
System.out.println("Max Number :"+maxNumber(count));}//Getting Max Number
Here is how to make method and get max number from list.
static int maxNumber(int[] mArray){//Passing int array as parameter
int max=mArray[0];
for(int i=0;i<mArray.length;i++){
if(max<mArray[i]){//Calculating max Number
max=mArray[i];
}
}
return max;//Return Max Number.
}
Ask if anything is not clear.
This is how we make method which return int.
You can do it by using a simple for loop for the Array.
First you have to create a seperate int variable (eg: int a) and assign value zero (0) and at each of the iterations of your loop you have to compare the array item with the variable a. Just like this
a < count[i]
and if it's true you have to assign the count[i] value to the variable a . And this loop will continue until the Array's last index and you will have your largest number in the a variabe. so simply SYSOUT the a variable
Important: I didn't post the code here because I want you to understand the concept because If you understand it then you can solve any of these problems in future by your self .
Hope this helps
What you have got so far is almost correct, but you currently are using the same random number in each iteration of your for-loop. Even though you need to get a new random number for each iteration of your for-loop. This is due to how the Random object is defined. You can achieve this by changing your code the following way:
import java.util.Random;
public class Q1 {
public static void main(String[] args) {
Random r = new Random(7);
int[] count = new int[11];
for (int i = 0; i < count.length; i++)
{
int x = r.nextInt(); // You need to generate a new random variable each time
count[i] = x;
}
}
Note that this code is not optimal but it is the smallest change from the code you already have.
To get the largest number from the array, you will need to write another for-loop and then compare each value in the array to the largest value so far. You could do this the following way:
int largest = 0; // Assuming all values in the array are positive.
for (int i = 0; i < count.length; i++)
{
if(largest < count[i]) { // Compare whether the current value is larger than the largest value so far
largest = count[i]; // The current value is larger than any value we have seen so far,
// we therefore set our largest variable to the largest value in the array (that we currently know of)
}
}
Of course this is also not optimal and both things could be done in the same for-loop. But this should be easier to understand.
Your code should be something like this. read the comments to understand it
public class Assignment {
public static int findMax(int[] arr) { // Defiine a function to find the largest integer in the array
int max = arr[0]; // Assume first element is the largest element in the array
for (int counter = 1; counter < arr.length; counter++) // Iterate through the array
{
if (arr[counter] > max) // if element is larger than my previous found max
{
max = arr[counter]; // then save the element as max
}
}
return max; // return the maximum value at the end of the array
}
public static void main(String[] args) {
int numberofslots =10;
int[] myIntArray = new int[numberofslots]; // creates an array with 10 slots of type int
Random r = new Random(7);
for (int i = 0; i < myIntArray.length; i++) // Iterate through the array 10 times
{
int x = r.nextInt();
myIntArray[i] = x; // Generate random number and add it as the i th element of the array.
}
int result = findMax(myIntArray); // calling the function for finding the largest value
System.out.println(result); // display the largest value
}
}
Hope you could understand the code by reading comments..
This can be done in one simple for loop no need to have 2 loops
public static void main(String[] args) {
Integer[] randomArray = new Integer[10];
randomArray[0] = (int)(Math.random()*100);
int largestNum = randomArray[0];
for(int i=1; i<10 ;i++){
randomArray[i] = (int)(Math.random()*100);
if(randomArray[i]>largestNum){
largestNum = randomArray[i];
}
}
System.out.println(Arrays.asList(randomArray));
System.out.println("Largest Number :: "+largestNum);
}
Initialize max value as array's first value. Then iterate array using a for loop and check array current value with max value.
OR you can sort the array and return. Good luck!
Here's a basic method that does the same task you wish to accomplish. Left it out of the main method so there was still some challenge left :)
public int largestValue(){
int largestNum;
int[] nums = new int[10];
for (int n = 0; n < nums.length; n++){
int x = (int) (Math.random() * 7);
nums[n] = x;
largestNum = nums[0];
if (largestNum < nums[n]){
largestNum = nums[n];
}
}
return largestNum;
}
I need practice with my syntax. I have an array of numbers and with that are methods to find the average, report highest number, and report the lowest number. To report the highest/lowest numbers I will be sorting the array.
But first my problem is with reporting the average. I think that if I can understand that part, then the min/max will be no problem. I have tried changing it to say Driver.randomArray[].getAverage() as well.
Are there any suggestions? Thanks in advance.
~Crystal
error code:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
randomArray cannot be resolved to a type
Class cannot be resolved to a type
Syntax error, insert ". class" to complete Expression
at IntegerArray.main(IntegerArray.java:48)
and it refers to my attempt to call the average from this line,
System.out.println(randomArray[].getAverage());
First, Driver Class
import java.util.Arrays;
public class Driver {
private static final int MAX = 0;
public Driver(){
int[] randomArray = new int [MAX];
int sum;
final int MAX;
}
public int getAverage(){
for (int index = 0; index < MAX; index++){
int sum = 0;
int[] randomArray = null;
int average;
sum = sum + randomArray[index];
average = sum/MAX;
return average;}
}
public void sortArray(){
// sort the array from smallest to biggest
int[] randomArray;
Arrays.sort(randomArray);
System.out.println("The sorted array from smallest to biggest is:");
for (int number : randomArray) {
System.out.println( + number)}
}
public int getMin(){
int[] randomArray;
// find the lowest number
return randomArray[0];
}
public int getMax(){
int[] randomArray;
// find the highest number
return randomArray[MAX];
}
}
Then my main class:
import java.util.Random;
import java.lang.reflect.Array;
import java.util.Arrays;
public class IntegerArray {
public static void main (String[] args) {
// set up the constant for the size of the array
final int MAX = 10;
int sum = 0;
int average = 0;
int[] randomArray = new int [MAX];
for (int index = 0; index < MAX; index++)
// values of the array go from 0-10
randomArray[index] = (int) (Math.random() *10);
// prints the array
for (int value : randomArray)
System.out.println (value);
System.out.println("The length of the array is: " + randomArray.length);
System.out.println(randomArray[].getAverage());
}
}
The way you're creating your methods eg. getAverage() you can't call it on the array you created. On the other hand you can call them on the a Driver object you create. for example: Driver driver = new Driver(); System.out.println(driver.getAverage()); If you want to call them on the Array Object you should add them on the Array class (but that is something more advanced Java than this).
In Java Code you need to add a ; after a statement don't forget them ;). Your IDE should warn you about them.
When you create your getMax() method you should add the array as a parameter. So that the method knows for what Array object it should get the highest number. For example:
public int getMax(int[] randomArray) {
// find the highest number
return randomArray[MAX];
}
This counts for all your methods.
I hope this solves some of your answers if not please add a comment or something.
So here is your code after that:
Driver class:
import java.util.Arrays;
public class Driver {
private static final int MAX = 0;
public Driver() {
int[] randomArray = new int[MAX];
int sum;
final int MAX;
}
public int getAverage() {
int average = 0;
for (int index = 0; index < MAX; index++) {
int sum = 0;
int[] randomArray = null;
sum = sum + randomArray[index];
average = sum / MAX;
}
return average;
}
public void sortArray(int[] randomArray) {
// sort the array from smallest to biggest
Arrays.sort(randomArray);
System.out.println("The sorted array from smallest to biggest is:");
for (int number : randomArray) {
System.out.println(+number);
}
}
public int getMin(int[] randomArray) {
// find the lowest number
return randomArray[0];
}
public int getMax(int[] randomArray) {
// find the highest number
return randomArray[MAX];
}
}
IntegerArray class:
public class IntegerArray {
public static void main(String[] args) {
// set up the constant for the size of the array
final int MAX = 10;
int sum = 0;
int average = 0;
int[] randomArray = new int[MAX];
for (int index = 0; index < MAX; index++)
// values of the array go from 0-10
randomArray[index] = (int) (Math.random() * 10);
// prints the array
for (int value : randomArray)
System.out.println(value);
System.out.println("The length of the array is: " + randomArray.length);
Driver driver = new Driver();
System.out.println(driver.getAverage());
}
}
Reply to the question in the comments:
You should give the randomArray as the parameter with your getAverage method so that method knows on which array it should operate, example: driver.getAverage(randomArray);
Your getAverage method also has some flaws:
1. Your sum variable should be outside the loop because else you would set your sum to 0 every time you iterate inside the loop.
2. int[] randomArray = null; You shouldn't really do this line at all, this line will create a NEW int array and set its value to null while you should you use the int array you give as a parameter.
So your getAverage method becomes:
public int getAverage(int[] randomArray) {
int sum = 0;
for (int index = 0; index < randomArray.length; index++) {
sum = sum + randomArray[index];
}
int average = sum / randomArray.length;
return average;
}
Currently your main class doesn't reference Driver at all, so your code cannot be called.
System.out.println(randomArray[].getAverage());
On this line randomArray is still just an array of integers (int[] randomArray = ...).
You will need to create an instance of Driver, pass in whatever array you're wanting to use, and then do .getAverage() on that.
randomArray is null and you are trying to read from a null array.
you need to define randomArray as a class member, not a local variable in all functions.
Local variables inside functions cannot be used as soon as function ends, and using the same name in other functions cannot help that.
Also:
define sum and average before loop. calculate and return average after loop.
Among other things your main issue seems to be a fundamental misunderstanding of scope rules. For example:
void method () {
int someVariable;
}
void method2 () {
someVariable = 2; // <-- Error.
}
In that code someVariable is local to method and is not available outside of it. You could not access it in method2.
I suggest you have a read not only of the above scope rules link, but of the official tutorial on member variables as well, which also describes scope. The information there will help you come up with a final strategy.
In your specific case your two most reasonable options are:
You could make randomArray a member field of your class (see above links).
You could pass randomArray as a parameter to your various methods (e.g. as a parameter to getAverage, see also the official tutorial on passing information to a method).
You have a few other issues, some mentioned in the other answers here, but my take is that is your primary confusion here. Read through the official tutorials (the docs.oracle.com links above), they're concise and well-written, and will fill in the blanks of some of your missing concepts. After you do that, give it another shot.
By the way, as for your compiler error on:
System.out.println(randomArray[].getAverage());
Unfortunately randomArray[].getAverage() simply does not make enough sense to justify a full explanation of how the compiler is interpreting it, so suffice it to say: No, that's wrong. :)
You'll want to check out that "passing information to a method" tutorial mentioned above, because it looks like you're trying to express something like this (option 2 above):
int getAverage (int randomArray[]) {
...
}
System.out.println(getAverage(randomArray));
As an aside: Note that the average of a bunch of integers isn't necessarily an integer itself (the average of 1 and 2 is 1.5). You might consider computing and returning a float or a double instead.
This question already has answers here:
How to find max and min value [duplicate]
(3 answers)
Closed 6 years ago.
I am trying to print the highest and lowest integer number stored in an array. I am able to print the highest but for the lowest I am not getting the correct result.
Consider my two classes below :
class ArrayUtilityNew
{
public static int findMaxMin(int a[])
{
int n=a.length;
int n2=n-1;
int minNo=0;
int count=0;
int maxNo=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(a[i]<a[j])count++;
}
//This gives the highest no. if the count is 0
if(count==0)
{
maxNo=a[i];
}
//Lowest no. shall be gained here if the count is greater
// than the no of elements in the array
// if(count>n)
// {
// minNo=a[i];
// }
count=0;
}
return maxNo;
}
}
class ArrayInteractionsNew
{
public static void main(String arr[])
{
int one[]={3,20,1999,2,10,8,999};
int answer=ArrayUtilityNew.findMaxMin(one);
System.out.println("The highest no in the array is "+answer);
}
}
Is the logic behind the second if not correct or is there some other mistake?
How can it be corrected?
You could return an int[] of min and max. Start with an array of two elements, loop over the array1 like
public static int[] findMinMax(int[] a) {
int[] result = { Integer.MAX_VALUE, Integer.MIN_VALUE };
for (int i : a) {
result[0] = Math.min(result[0], i);
result[1] = Math.max(result[1], i);
}
return result;
}
The result will be an array with the first element being the minimum value2. Then to test it,
public static void main(String[] args) {
int[] arr = { 3, 20, 1999, 2, 10, 8, 999 };
int[] minMax = findMinMax(arr);
System.out.printf("%s: min=%d, max=%d%n",
Arrays.toString(arr), minMax[0], minMax[1]);
}
And I get (as I would expect)
[3, 20, 1999, 2, 10, 8, 999]: min=2, max=1999
1Here, with a for-each loop.
2And the second element being the maximum.
I think your solution is way too complex... A better and more efficient solution would be this:
int n=a.length;
int minNo=a[0];
int maxNo=a[0];
for(int i=1;i<n;i++)
{
if(a[i] > maxNo) {
maxNo = a[i];
} else if(a[i] < minNo) {
minNo = a[i];
}
}
// do whatever you want with maxNo and minNo
Also an even more efficient (in the code size way) way would be to use lists or streams because you can do one-liners with it.
EDIT: less ambiguous code and explanations about efficiency
Your answer is n^2. To find min and max it only needs to be order n.
In other words you only need to look linear.
Do a loop that looks through the list once. Keep track of min and max as you go. Initially set min = maxvalue and max=minvalue. When you find a value smaller than min, it becomes the new min.
Here is an example in pseudo code.
min = max_int
max = min_int
for (i=0; i < array.length; i++)
if array[i] < min
min = array[i]
if array[i] > max
max = array[i]
Your approach, if it even works, is needlessly complicated.
Create two variables: minNo and maxNo.
Set minNo = Integer.MAX_VALUE and maxNo = Integer.MIN_VALUE.
Loop through the array. If the element is >= maxNo, assign its value to maxNo. Also (not instead -- i.e., not else if!), if the element is <= minNo, then assign its value to minNo.
After the loop, minNo and maxNo will be correctly assigned.
public static void minMax(int []arr){
int min = arr[0];
int max = arr[0];
for(int i=1; i<arr.length; i++){
min = Math.min(min,arr[i]);
max = Math.max(max,arr[i]);
}
//do whatever you want with the max and min
}
Thanks to the Streaming API in java8, this is a two-liner:
int[] array = new int[] {5,7,2,9,10,24,3,23};
int min = IntStream.of(array).min().getAsInt();
int max = IntStream.of(array).max().getAsInt();
Or as a more efficient 3-liner:
Arrays.parallelSort(array);
int min = array[0];
int max = array[array.length -1];
I'm trying to write a class and create accessors in Eclipse that I will have to use later on, however I'm having trouble doing so. I have the directions listed below but keep getting stuck on the last two.
Directions:
Write a class StringSet. A StringSet object is given a series of String objects. It stores these Strings (or a reference to them, to be precise) and can perform limited calculations on the entire series. A StringSet class has the following specification:
a single instance variable of type ArrayList<String>
a single default constructor
mutator that adds a String newStr to the StringSet object
void add(String newStr)
accessor that returns the number of String objects that have been added to this StringSet object
int size()
accessor that returns the total number of characters in all of the Strings that have been added to this StringSet object
int numChars()
accessor that returns the number of Strings in the StringSet object that have exactly len characters
int countStrings(int len)
My code so far:
import java.util.ArrayList;
public class StringSet {
ArrayList<String> StringSet = new ArrayList<String>();
public StringSet() {
}
public void add(String newStr) {
StringSet.add(newStr);
}
public int getsize() {
return StringSet.size();
}
public int getnumChars() {
return StringSet.length();
}
public int countStrings(int len) {
if (StringSet.equals(len)) {
return StringSet.size();
}
}
}
Your string set is an array of string objects. Think of it as though you've added each of the following to stringSet (indexes are to the left of the value).
0[Hello]
1[My]
2[name]
3[is]
5[Keith]
For simplicity I'm going to use a primitive String[] rather than an ArrayList
Question 5
Create a variable that will increment its value by the size of each String. Then use a for loop to evaluate each individual String's length and add it to that variable:
int totalCharsInStringSet = 0;
for (int i = 0; i < stringSet.size(); i++) { // loop through each index
// add the length of the string at this index to your running tally
totalCharsInStringSet += stringSet[i].length;
}
// you've read through all of the array; return the result
return totalCharsInStringSet;
Question 6
Calling stringSet.size() is just going to count how many elements are in the array; i.e., 5. So you need to create a tally of how many individual strings match the target length. Craete a variable to keep that tally. And again, use a for loop to iterate through the array, and compare each string's length to the target value. If it matches, increment your tally:
int numberOfMatches = 0;
for (int i = 0; i < stringSet.size(); i++) {
if (string[i].length == len) { // "len" is your input target length
numberOfMatches ++;
}
}
return numMatches;
Number 5: You iterate through your ArrayList and add up the length of the strings stored there.
Number 6: You iterate through you ArrayList and check if the length of the String matches the desired length, and keep track of the number of matching strings.
Well ArrayLists don't have a length() method, so what you need to do to count total number of chars in the string set is iterate through the StringSet list and find the length of each string and add it to a running total.
int sum = 0;
for(int i = 0; i < StringSet.size(); i++){
sum = sum + StringSet.get(i).length();
}
return sum;
For the countStrings you need to place this if statement in a for loop and increment a sum each time the if statement is triggered and return the sum
int sum = 0;
for(int i = 0; i < StringSet.size(); i++){
if(StringSet.get(i).length() == len){
sum = sum + 1;
}
}
return sum;
For Question 5:
public int getnumChars()
{
int countChar = 0;
for(String strSet: StringSet){
countChar += strSet.length();
}
return countChar;
}
For Question 6:
public int countStrings(int len)
{
int count = 0;
for(String strSet: StringSet){
if(strSet.length() == len){
count++;
};
}
return count;
}
Hi im trying to show the index of the array not the element this is part of my code so far:
int randomInt2 = randomGenerator.nextInt(15)+1;
double [] distances = new double [randomInt2];
Arrays.sort(distances);// sorts array from highest to lowest
for (double val : distances) {
System.out.println("["+val+"],");
}
System.out.println("The Nearest to point 1 is point: ");
Each index holds an value between 1-1000 but i do not want to show the value i want to show the index so that I can show what indexes are closest to point 1 (which is 0)
Sorry if im not being clear and if you need me to explain more then I am happy to
Thanks to dasblinkenlight's comment I finally understood what you need.
The easiest way to do what you need to do would be to create an object like
class Value implements Comparable<Value> {
int index;
dobule value;
public int compareTo(Value val) {
return Double.compare(this.value, val.value);
}
}
And use it to store the values. Note the Comparable implementation - allows you to use Collections.sort() and Arrays.sort().
You could also not use sorting. Sorting an array is a much more complex operation than finding the minimum value. Just iterate over the array once and find the smallest value and return its index.
double minVal = Double.MAX_VALUE;
int minIndex = -1;
for (int i=0, max=distances.length; i<max;i++) {
if (values[i] < minVal) {
minVal = values[i];
minIndex = i;
}
}
System.out.println("The Nearest to point 1 is point: "+minIndex+" with value "+minVal);
As for indexes: you can't use standard foreach loop if you want to access the index of a given element. One of the reasons is that some collections you may iterate over do not support element ordering (like a Set).
You have to use standard for loop or track the index yourself.
for (int i=0, max=distances.length; i<max;i++) {
System.out.println("["+i+"] "+distances[i]);
}
or
int i = 0;
for (double val : distances) {
System.out.println("["+i+"] "+val);
i++;
}
try like this
for (int i=0;i< distances.length;i++) {
System.out.println("distances["+i+"]");
}
I assume you want to find out the index of the item with lowest distance in the original array. When you sort the array, this information is lost, as it will simply indexed from 0..length-1. Therefore, your answer will always be 0.
You can do 2 things:
1) Find the minimum value:
double[] distances = new double [randomInt2];
// Need copy to for sorting
double[] c = Arrays.copyOf(distances, distances.length);
// Find minimum value
Arrays.sort(c);
double min = c[0];
// Search that value in the original array:
for (int i = 0; i < distances.length; ++i) {
if (distances[i] == min) {
System.out.println("Minimum distance at: " + i);
break;
}
}
2) Store the index information with the distance information:
For this you need to:
write your own class, like public class Distance, with a distance and index member.
Implement a Comperator<Distance>, so that instances are compared by distance
Make a function like Distance[] convertToDistance(double[] array) that creates a Distance array from your pure double values (if needed)
Sort the array using Arrays.sort(T[], Comparator<? extends T>) method
Get the result from sortedDistances[0].index
You can just used an old fashioned for loop instead of an enhanced for loop:
Arrays.sort(distances);// sorts array from highest to lowest
for (int i = 0; i < distances.lengh; ++i) {
System.out.println("index: " + i + ":[" + val + "],");
}
you might every distance let be an object of
class Distance {
public Distance(double dist) {
this.dist = dist;
this.id = idcount++;
}
static int idcount = 0;
public int id;
public double dist;
}
and than call the id in every