Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to figure how to find the largest number in an array of random numbers.
So far I cant manage to get it right.
Its an array[50] and the random, numbers are between 0-100.
Thanks!
Loop through the array and keep track of the largest number found already in an int variable.
public int findMax(int[] numbers)
{
int max = 0;
for (int i = 0; i < numbers.length; ++i)
if (numbers[i] > max) max = numbers[i];
return max;
}
(You can also initialize max to int.MIN_VALUE or something if it helps behave more suitably in the case where an empty array is passed in.)
Use:
java.utils.Arrays.sort(yours_array);
int largest = yours_array[yours_array.length - 1] ;
Collections.max and you can use it as follows with a raw array:
List<Integer> triedArray = new ArrayList<Integer>();
ArrayUtils.addAll(intArray);
This does add a dependency on commons-lang, though.
Assuming the int[] is named array
Try to use a loop like the following:
int biggest = array[0]
for(int a = 1; a < array.length; a++){
if(array[a] > biggest){
biggest = array[a]
}
}
At the end, your variable biggest will hold the largest value in the array.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
static void miniMaxSum(int[] arr) {
int summin=0;
int summax=0;
for (int i=0; i< 5; i++) {
for (int j=4; j>i; j--) {
if(arr[i]>arr[j]){
int c=arr[i];
arr[i]=arr[j];
arr[j]=c;
}
}
}
for (int i=0; i<4; i++) {
summin=summin+arr[i];
}
for (int i=1; i<5; i++) {
summax=summax+arr[i];
}
System.out.print(summin+" "+summax);
}
My code only works correctly enter image description here with 5/15 testcases. I want to sort the array and then calculate the result. The "min" result is correct, but the "max" result is a negative integer so it's wrong. I found the problem is caused by the last element after sorted. Using Netbeans, I calculated the sum of all element in the array. After 4 first elements, the sum still was a positive int, but when 5th element added, the sum changed into a negative int. I don't know why, can someone help me please?
You are exceeding the range of integer and the value is overflowing to the negative side. If you want to test with big numbers use long datatype.
Int Datatype Rang:
-2,147,483,648 to 2,147,483,647 The int data type is a 32-bit signed Java primitive data type. A variable of the int data type takes 32
bits of memory. Its valid range is -2,147,483,648 to 2,147,483,647
(-231 to 231โ 1).
I guess you should use long as summin and summax, that would solve your problem (you have negative values because you sum max is more than max integer value)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I wrote the following code to sort the elements in the array values using a BubbleSort. Is this correct or is there anything missing? My test cases are good, but maybe it's the test cases that are also missing something.
public void sort(ValuePair[] values) {
ValuePair value = null;
for (int i = 0; i < values.length; i++) {
for (int j = 1 + i; j < values.length; j++) {
if (values[i].getValue() > values[j].getValue()) {
value = values[j];
values[j] = values[i];
values[i] = value;
}
}
}
}
Your code is correct in that it will sort the array. However it will always require N*(N-1) passes over the array. This is not
the typical algorithm used to implement
a bubble sort. The typical algorithm uses repeat loop with a test for sorted. This is somewhat more efficient because it
terminates as soon as the array is sorted (consider the case where you start with a sorted array).
Read the Wikepedia article on bubble sort it demonstrates this very well.
A somewhat improved version pseudocode version of Bubble Sort goes something like this:
procedure bubbleSort( A : list of sortable items )
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
if A[i-1] > A[i] then
swap(A[i-1], A[i])
swapped = true
end if
end for
n = n - 1
until not swapped
end procedure
The lesson here is that while your algorithm and the Wikepedia algorithm both have the same big O characteristics, a small change
in the way they have been implemented can make a significant difference in their actual performance characteristics.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
list of integers with duplicates and integer N. Remove the duplicates from the list and find the N-th largest element in the modified list.
Implement at least two different solutions to find N-th largest element with O(N*log(N)) average time complexity in Big-O notation, where N is the number of elements in the list
The below is the solution i thought of is there any better way of implementing? Also, how do I implement two different solutions ?
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] list= {5,3,8,2,5,7,6,7,3,7};
int n = 3;
System.out.println("Printing list before removing duplicates");
for (int i : list) {
System.out.println(i+" ");
}
for (int i = 0; i < list.length; i++) {
for (int j = i+1; j < list.length; j++) {
if (list[i] < list[j]) {
int swap = list[i];
list[i] = list[j];
list[j]=swap;
}
if (list[i] == list[j]) {
list[j] = 0;
}
}
}
System.out.println("Printing list after removing duplicates");
for (int i : list) {
System.out.println(i+" ");
}
System.out.println("the N-th largest element in the modified list is"+ list[n-1]);
}
For this sort of problem really you need to look at what language tools are provided to you and how to make use of them to do the hard work for you.
To remove duplicates just place them into a Set. To have them sorted use a TreeSet.
So you get:
Set<Integer> values = new TreeSet<Integer>();
That will sort them from smallest to largest, to reverse the order specify your own comparator for the TreeSet that just reverses the natural ordering.
Then iterate over the Set and the nth value returned from the iterator is your value.
Your current code looks mostly valid, it doesn't actually remove duplicates though - you need to actually remove things from the Array for that, which Arrays do not support without recreating them as they cannot be resized. Additionally it will get confused if you include 0s or negative numbers. For example the biggest number in (-3, -5, -6, -6) will come back as 0.
One line for each task if you start with a collection.
List<Integer> list = new ArrayList<Integer>(Arrays.asList(5,3,8,2,5,7,6,7,3,7));
To remove duplicates:
List<Integer> nodups = new ArrayList<Integer>(new HashSet<Integer>(list));
To find largest:
Integer largest = Collections.max(list);
Unless for some reason you're bound to using only primitives, Tim's answer solves the sorting problem. To implement multiple "solutions", just create two different functions which take the list of numbers and the value n as parameters:
public void firstSolution(int[] numbers, int n) {
// one implementation
}
public void secondSolution(int[] numbers, int n) {
// another implementation
}
Then simply make the appropriate function calls in main.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem โ and include valid code to reproduce it โ in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Why it doesn't work?
P.S. I am beginner in Java.
int userInfo[];
userInfo = new int[2];
userInfo[0] = 11;
userInfo[1] = 20;
userInfo["result"] = userInfo[0] + userInfo[1];
System.out.println(userInfo["result"]);
Only an int can be an index into an array. A String won't work. If you need 3 slots, declare your array to be length 3 and then you can use userInfo[2].
The JLS, Section 10.4 makes it pretty clear:
Arrays must be indexed by int values; short, byte, or char values may also be used as index values because they are subjected to unary numeric promotion (ยง5.6.1) and become int values.
int userInfo[];
userInfo = new int[2];
userInfo[0] = 11;
userInfo[1] = 20;
int result = userInfo[0] + userInfo[1];
System.out.println(result);
The string can not be the index in array.
Your array has 2 slots, and you used them to store the numbers. To get the sum, do this:
int sum = userInfo[0] + userInfo[1];
Also, even if your array had a third slot, you can only access individual elements by their numerical index (0, 1, or 2 in this case). Not by a String like result.
In java, arrays only have zero and positive integer indexes. This means that an array can only be accessed with 0 to size of the array minus 1.
If you want to do something like:
userInfo["result"] = userInfo[0] + userInfo[1];
You can try the following:
int result = userInfo[0] + userInfo[1];
System.out.println(result);
or:
Map<String,Intgeer> example = new HashMap<String,Intgeer>();
example.put("result", new Integer(userInfo[0] + userInfo[1]));
System.out.println(example.get("result"));
There are several problems here as I mentioned in comments. You declare an array of int here:
int userInfo[];
Then try to pass a string into it here (that won't work):
userInfo["result"]; // This is bad news
Your cleaned-up code should look like this:
int userInfo[];
userInfo = new int[2];
userInfo[0] = 11;
userInfo[1] = 20;
int sumArrayValues = userInfo[0] + userInfo[1];
System.out.println(sumArrayValues);
Happy coding!
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have two arrays a[] and b[].
int a[]={3,1,1,1,7,4,6,6,3,1};
int b[]=new int[a.length];
Array length in actual problem can change.
The values in the array must be less then value of array length as seen.
The output must be:
b = 3 1 0 0 7 4 6 0 3 1
So basically if there is a sequence of same value in a[] then only 1st of its value must be placed at same index in b[] rest should be zero till the sequence exists.
Answer in java syntax will be helpful.
Thank you in advance
int a[]={3,1,1,1,7,4,6,6,3,1};
int b[]=new int[a.length];
int temp = a[0];
b[0] = temp;
for(int i = 1; i < a.length; i++) {
if(a[i] == temp)
b[i] = 0;
else
b[i] = a[i];
temp = a[i];
}
hint:
1) create hashmap to store processed values
2) iterate over the first array: if current value is stored in map, then fill 0, otherwise store this value in HashMap and copy the value to new array