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
Related
I came across this problem in class and I'm stuck on it. I did plenty of research but I'm not being able to fix my code.
I need to create a matrix and find the smallest value in the row of the largest value (I believe this element is called minimax). I'm trying to do with a simple 3 x 3 matrix. What I have so far:
Scanner val = new Scanner(System.in);
int matrizVal[][] = new int[3][3];
for (int a = 0; a < matrizVal.length; a++) {
for (int b = 0; b < matrizVal.length; b++) {
System.out.print("(" + a + ", " + b + "): ");
matrizVal[a][b] = val.nextInt();
}
}
int largest = matrizVal[0][0];
int largestrow = 0;
int arr[] = new int[2];
for (int row = 0; row < matrizVal.length; row++){
for (int col = 0; col < matrizVal.length; col++){
if (largest < matrizVal[row][col]){
largest = matrizVal[row][col];
largestrow = row;
}
}
}
To find the so called minimax element I decided to create a for each loop and get all the values of largestrow except the largest one.
for (int i : matrizVal[largestrow]){
if (i != largest){
System.out.print(i);
}
}
Here's where I'm stuck! I'd simply like to 'sort' this integer and take the first value and that'd be the minimax. I'm thinking about creating an array of size [matrizVal.length - 1], but not sure if it's gonna work.
I did a lot of research on the subject but nothing seems to help. Any tips are welcome.
(I don't think it is but I apologize if it's a duplicate)
Given the code you have provided, matrizVal[largestrow] should be the row of the matrix that contains the highest valued element.
Given that your task is to extract the smallest value in this array, there are a number of options.
If you want to simply extract the minimum value, a naive approach would go similarly to how you determined the maximum value, just with one less dimension.
For example:
int min = matrizVal[largestrow][0];
for (int i = 0; i < matrizVal.length; i++) {
if (matrizVal[largestrow][i] < min) {
min = matrizVal[largestrow][i];
}
}
// min will be the target value
Alternatively, if you want to sort the array such that the first element of the array is always the smallest, first ensure that you're making a copy of the array so as to avoid mutating the original matrix. Then feel free to use any sorting algorithm of your choice. Arrays.sort() should probably suffice.
You can simplify your approach by scanning each row for the maximum and minimum values in that row and then deciding what to do with those values based on the maximum value found in previous rows. Something like this (untested) should work:
int largestValue = Integer.MIN_VALUE;
int smallestValue = 0; // anything, really
for (int[] row : matrizVal) {
// First find the largest and smallest value for this row
int largestRowValue = Integer.MIN_VALUE;
int smallestRowValue = Integer.MAX_VALUE;
for (int val : row) {
smallestRowValue = Math.min(smallestRowValue, val);
largestRowValue = Math.max(largestRowValue, val);
}
// now check whether we found a new highest value
if (largestRowValue > largestValue) {
largestValue = largestRowValue;
smallestValue = smallestRowValue;
}
}
This doesn't record the row index, since it didn't sound like you needed to find that. If you do, then replace the outer enhanced for loop with a loops that uses an explicit index (as with your current code) and record the index as well.
I wouldn't bother with any sorting, since that (1) destroys the order of the original data (or introduces the expense of making a copy) and (2) has higher complexity than a one-time scan through the data.
You may want to consider a different alternative using Java 8 Stream :
int[] maxRow = Arrays.stream(matrizVal).max(getCompertator()).get();
int minValue = Arrays.stream(maxRow).min().getAsInt();
where getCompertator() is defined by:
private static Comparator<? super int[]> getCompertator() {
return (a1, a2)->
Integer.compare(Arrays.stream(a1).max().getAsInt(),
Arrays.stream(a2).max().getAsInt()) ;
}
Note that it may not give you the (undefined) desired output if two rows include the same highest value .
I need to create a class ArrayMethods. With a
• public static double median(double[][] a)
method. I know that i need to create a list with all the values from the 2d arrays. Then sort it out and find the median. BUt I dont know how to create a list. Can anyone help me with this.
For the median, I have done this but it doesn't work on negative numbers or odd number of arrays:-
public static void main(String[] args) {
double[][] a = {
{1,2,3},
{4,5,6},
};
System.out.println(median(a));
}
public static double median(double[][] a2) {
double[] list = new double[a2.length*a2[0].length];
double listPos = 0;
for(double i = 0 ; i < a2.length; i++) {
for(double j = 0; j < a2[(int) i].length; j++) {
list[(int) listPos++] = a2[(int) i][(int) j];
Arrays.sort(a2[(int) i]);
}
}
double middle = list.length/2;
if ((list.length%2) == 1) {
return list[(int) middle];
}
return (list[(int) (middle-1)] + list[(int) middle]) / 2.0;
}
}
If we're talking about simply creating a list, then we will need a dynamic list able to store whatever number of values, since we only know the size of the array if we either hard-code it (never!) or at runtime. The best solution for this is a basic ArrayList.
First, we store all the values into the ArrayList, and once all values are stored, we can then sort it. As you know, it's all down hill from there. The median (using your implementation of the median) can be found now using:
public static double median(double[][] a2) {
// check for an empty array
if(a2.length == 0)
throw new IllegalStateException("The array is empty");
ArrayList<Double> list = new ArrayList<Double>();
// first, add all the elements into the linear list
for(int i = 0; i < a2.length; i++) {
for(int j = 0; j < a2[0].length; j++) {
list.add(a2[i][j]);
}
}
// second, sort them
Collections.sort(list);
// and finally, determine the median based on the number of items
int length = list.size();
// if there is an even number of values, take the average of the 2 middle values
if(length % 2 == 0)
return (list.get(length/2 - 1) + list.get(length/2)) / 2.0;
// else, return the middle value
return list.get(length / 2);
}
I also threw in the check for an empty array, but if you want to get rid of it you can. Hope this helps!
I would like to use list.negativeNumbers(); to call out the part of a code, which counts how many negative numbers are in a list.
public void negativeNumbers(){
int negative = 0;
for (int i = 0; i <= size; i++){
if (i < 0) {
negative = negative + 1;
}
System.out.println("There are "+ negative +" negative elements in the list!");
}
}
Can you help me in creating a method, that could count negative numbers in the list the correct way?
public void negativeNumbers(){
int negative = 0;
for (int i = 0; i <= size; i++){
if (i < 0) {
negative = negative + 1;
}
System.out.println("There are "+ negative +" negative elements in the list!");
}
}
You will learn better by working out the solution for yourself.
Your code as presented is a good start but lacks:
a defined list of values to test.
a definition of the size of the list (use list.size()).
proper indexing of the list to access values to test (use list.get(i) or list[i]).
a test of each element in the list to determine its negativity. Your code tests whether the list increment variable is < 0.
negative = negative + 1 is ok, but simpler to write ++negative.
Here's a simple example:
import java.util.ArrayList;
public class negnum {
public static void main(String [] args) {
ArrayList<Integer> nums = new ArrayList();
nums.add(0);
nums.add(10);
nums.add(-10);
nums.add(20);
nums.add(-20);
nums.add(30);
nums.add(-30);
nums.add(40);
nums.add(-40);
nums.add(50);
int negs = 0;
for (int i = 0; i < nums.size(); i++){
int n = nums.get(i);
if (n < 0) {
++negs;
System.out.println(n);
}
}
System.out.println(negs +" negatives");
}
}
c:\dev>java negnum
-10
-20
-30
-40
4 negatives
If it is a list of integers you should not be doing "i < 0" but rather the number at index of i. If you were to do that, you would also want to do "< size" rather than "<= size" or else you would run into an IndexArrayOutOfBounds.
It depends on how your double linked list is implemented, but if it extends the normal List<Integer> interface it would look like:
final Integer ZERO = Integer.valueOf(0);
int countNegativeElements() {
return stream().filter(MyList::isNegative).count();
}
static boolean isNegative(Integer i) {
return i.compareTo(ZERO) < 0;
}
with streams. More traditionally with an collection for-each (or an iterator for-each):
int countNegativeElements() {
int count = 0;
for(Integer i : this) { // or iterator()
if (isNegative(i)) count++;
}
return count;
}
This does not expect concurrent modifications and is optimized for collections where iterating is the fastest access. If you have a simple type list then you can replace isNegative with a simple < 0.
This article here talks about different ways to iterate a collection.
In my code I assumed you will add the method directly to your list implementation class. Replace this or this.iterator() or this.stream() with your actual list instance if it is external.
Update:
I just saw your link to the actual linked list you are using, this would look like this (hand made iteration):
int countNegativeElements() {
Node n = start;
int count = 0;
while(n != null) {
if (n.getData() < 0) count++;
n = n.getLinkNext();
}
return count;
}
Using null since there is no hasLinkNext() which would be typical for homework :)
I don't think it is a particular good idea to work with implementations which do not fit in the Collections framework, but maybe it is required to keep the lessons simple.
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();
I am given a problem in which I have to store a list of N numbers in an array and then sort it ,
and then I have to add the numbers at alternative positions and output the sum.
The problem is the constraint of N i.e 0 <= N <= 1011 so I have to declare the N as double type variable here is my code :
ArrayList<Double> myList = new ArrayList<Double>();
myList.add(number);
.....
Collections.sort(myList);
String tempNo = "";
for(double i = 0 ; i < myList.size() ; i=i+2){
tempNo = myStringWayToAdd(tempNo , myList(i)+""); // Since the sum will exceed the limit of double I have to add the numbers by help of Strings
}
But the problem is that the get(int) method takes an int not double. Is there any other way I can solve the problem? , and Is it even allowed to store number of elements that exceed int range?
Any help will be highly appreciated. Thank you in Advance.
Edit 1 :
I can use Strings instead of double in ArrayList and then add up the numbers but my problem is that i need to store N elements which can exceed the range of Integers
You could use LinkedList because it does not have a size limit (although odd things may begin to happen up there). You should also be able to use BigInteger for your numbers if the numbers themselves could get huge (you don't seem to state).
// LinkedList can hold more than Integer.MAX_VALUE elements,
List<BigInteger> myList = new LinkedList<>();
// Fill it with a few numbers.
Random r = new Random();
for (int i = 0; i < 1000; i++) {
myList.add(BigInteger.probablePrime(10, r));
}
// Sort it - not sure if Collections.sort can handle > Integer.MAX_VALUE elements but worth a try.
Collections.sort(myList);
// Start at 0.
BigInteger sum = BigInteger.ZERO;
// Add every other one.
boolean addIt = false;
for (BigInteger b : myList) {
if (addIt) {
sum = sum.add(b);
}
addIt = !addIt;
}
I am not sure if Collections.sort can handle a list of numbers that big, let alone whether it will succeed in sorting within the age of the universe.
You may prefer to consider a database but again you might even have probelms there with this many numbers.
Ah, I misunderstood the question. So we have to store something that is significantly larger than the capacity of int.
Well, we can do this by dividing and conquering the problem. Assuming this is theoretical and we have unlimited memory, we can create a SuperArrayList.
'Scuse my bad generics, no compiler.
public class SuperArrayList<E>() {
private ArrayList<ArrayList<E>> myList;
private int squareRoot;
private double capacity;
public SuperArrayList(double capacity) {
this.capacity = capacity;
squareRoot = Math.ceil(Math.sqrt(capacity)); //we create a 2d array that stores the capacity
myList = new ArrayList<ArrayList<E>>();
for(int i = 0; i < squareRoot; i++) {
myList.add(new ArrayList<E>());
}
}
public E get(double index) {
if(index >= capacity || index < 0) {
//throw an error
}
else {
return myList.get((int) capacity / squareRoot).get(capacity % squareRoot);
}
}
}
As an alternative to squareRoot, we can do maxValue and add additional arraylists of length maxvalue instead.
boolean add = true;
for (Double doubleNum : myList) {
if (add) {
tempNo = myStringWayToAdd(tempNo , doubleNum+"");
}
add = !add;
}
Using this way, you won't have to use index.