I have an array filled with double values. I want to get the index of the 2nd and the 3rd and 4th lowest values in the array. This is what I have tried but I haven't been getting what I want.
double[] wantedVals = new double [3];
for(double n :allValues){
if(n < wantedVals[2] && n > wantedVals[1]) {
wantedVals[2] = n;
}
}
System.out.println("All Values: "+ Arrays.toString(allValues));
System.out.println("2nd, 3rd, 4th lowest values index: " + Arrays.toString(wantedVals));
}
Here is the output.
All Values: [314.8490027477457, 558.1219589782775, 0.0, 538.3207360335937, 519.5707513178547, 271.85862019623363, 452.44377672120766, 448.3506884613316, 365.0024775172766, 380.61611237571117, 225.73376879634114, 310.28009020077326, 121.53621181051349, 95.45317487517113, 280.453364828718, 57.11775118122211, 343.1257001358977, 365.58868943629807, 530.7625668260243, 227.4473840254049, 319.9578951791938, 291.8377585984206, 494.999842171692, 464.97103404405743]
2nd, 3rd, 4th lowest values: [0.0, 0.0, 0.0]
What I want to do is get the indexes of the 2nd, 3rd and 4th lowest values in All Values array.
Do an index sort, and then output the indexes. Like this:
final int MAX_ARRAY_SIZE = (the biggest that your all values array will be)
int index[] = new int[MAX_ARRAY_SIZE];
for(int i = 0; i < allValues.length(); i++)
{
index[ i ] = i;
}
//Simple Bubble Sort
for(int i = 0; i < allValues.length() - 1; i++)
{
for(int j = i + 1; j < allValues.length(); j++)
{
if(allValues[ index[ i ] ] > allValues[ index[ j ] ])
{
int temp = index[ i ];
index[ i ] = index[ j ];
index[ j ] = temp;
}
}
}
System.out.println("Indexes of 2nd to 4th lowest numbers are the following: ");
for(int i = 1; i < 4; i++)
{
System.out.println(index[ i ]);
}
Mark this as the answer if it answers your question.
Hope this helps!
I can think of two ways to accomplish this: sort the array, and search it repetitively. Neither of these is likely to be the most efficient, but they should be good enough for most use cases (with the latter being slightly more efficient).
If you want to sort the array, simple use Arrays.paralellSort() and get whatever values you need from the resulting array.
If you want to search it repetitively, then simply go through the array and find the lowest value. Make note of this value in a variable, and repeat the original code -- unless the current value is the lowest. It would be best to use a HashSet to contain the list of already selected values, since a HashSet can efficiently be checked for a value and have a value added to it.
Related
I'm tasked with a perplexing problem. I'm attempting to turn an unsorted array with duplicates into a sorted array without duplicates. I used the selection sort to accomplish the first part:
public static void SelectionSort(int [] list) {
int i = 0;
int j = 0;
int indexSmallest = 0;
int temp = 0;
for (i = 0; i < list.length - 1; i++) {
indexSmallest = i;
for (j = i + 1; j < list.length; j++) {
if (list[j] < list[indexSmallest]) {
indexSmallest = j;
}
}
temp = list[i];
list[i] = list[indexSmallest];
list[indexSmallest] = temp;
}
}
The sorting isn't the issue - I'm having a hard time removing the duplicates from the array. The solution that I have in my head is to create a secondary array, and iterate through the input to check if that element exists in the second array, if not, add it to the array. I'm stuck because I'm not able to create another array. So, what gives? How do I solve this problem if I can't create an array to cross-reference and check if I have unique values? I'm not able to use any built-in Java functions.
There is no need of second array ... think about it this way ...
The easiest way is to convert it to set / hashset and then sort it in an array.
But if the sets are forbidden, the only possibility is to put the duplicates at the end, cut them out and then sort the rest.
[1,8,1,2,3,5,3] in this array, you need to remove elements that are duplicates ... okay ... so what if we did something like this ... we will "split" this array into "sorted", "unsorted and duplicates" and "duplicates". Now what we will do is that we will go through the array using 2 pointers. One at the first element (lets call it "i") and at the last element (lets call it "j") ... now we will go while i < j and we will swap everytime, when we will find a duplicate. This way, you will get everything not duplicate before "i" and everything that is dupicate after "i" ... now you will sort the array from index 0 do index i and you should have sorted array and you will just cut out the duplicates ...
ofc., this will require the time complexity, to be able to handle O(n*logn) / O(n^2) ...
There is a way how to do it in a O(n), and that can be done by that .. you will use 2 pointers ...
one will be pointing at current sorted array, where you have no duplicates and toher will be pointing to a place, where are yet unswapped integers ... (you need to remember the highest number found)
to be more specific:
[1,2,2,3,3,4,5]
i = 0, j = 1
- fine
i = 1, j = 2
- duplicate ... soo ..
jumping to duplicate position
i = 2, j = 3 (array[3] != 2, so we will swap)
current array -> [1,2,3,2,3,4,5]
^ ^
i j
i = 3, j = 4
- highest_number > 3 is not true (2 < 3), so skipping
i = 3, j = 5
- highest_number > 3 is not true (3 < 3), so skipping
i = 3, j = 6
- swapping
... etc
and you should end up with something like this
[1,2,3,4,5,2,3]
^ ^
i j
now you can cut the array at i, so you will get `[1,2,3,4,5,\0]` (in C syntax) ... so basically `[1,2,3,4,5]`
I want to take the maximum value obtained from result.length, but I have trouble in the way to call it, can you help me?
double[][] result = matrixMultiplexing(neighboursAdjSquare(matrixEgoNetwork), matrixDecrement(ones, matrixEgoNetwork));
double max = result[0][0];
ArrayList<Double> val= new ArrayList<>();
for (int i = 0; i < result.length; i++) {
for (int j = i+1; j < result.length; j++) {
Arrays.sort(result);
if(result[i][j]== "I wanna called here" ){
val.add(result[i][j]);
}
}
}
The error is cannot applied 'double',double[]'
can you help me fix that?
public class FindMaxOf2dArray {
public static void main(String[] argv) {
double[][] arr2d = new double[][]{
{1.0, 2.0, 3.0, 4.0},
{5.0, 6.0, 7.0, 8.0},
{99.0, 0.0, 0.0, -1.0}
};
double maxOfarr2d = findMaxOf2dArray(arr2d);
System.out.println("The maximum value contained in arr2d is " + maxOfarr2d);
}
static double findMaxOf2dArray(double[][] arr2d){
double maxValue = Double.MIN_VALUE;
for(int i = 0; i < arr2d.length; i++){ //iterate through the number of arrays
for(int j = 0; j < arr2d[i].length; j++){//iterate through each value in the given array
if(arr2d[i][j] > maxValue){
maxValue = arr2d[i][j];
}
}
}
return maxValue;
}
}
This would be the most straight-forward way to find the maximum value within a 2d-array. Not necessarily the best way, but it should be easy to follow the logic. In the method findMaxOf2dArray(double[][]) we set the maximum value to the smallest possible value that can be stored in a double. Then we enter a for-loop that loops through each array that contains doubles. For every iteration of this loop we enter a second for-loop that iterates through each value stored in the current array. Each value is then compared against the value stored in maxValue. If the value stored in the array is greater than the value stored in maxValue, then we change the value of maxValue to the value stored in the array. Finally after checking each value in each array of the 2d-array, we return the value stored in maxValue.
I believe the problem with your code is that you never iterate through the values stored in each array. You only iterate through the arrays themselves–twice. Each value stored in result[i] is itself an array which holds the double values that you want to compare. Additionally by starting j at i + 1 you skip i + 1 values to be iterated through. Lastly, a double cannot be compared to a String.
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Consider input [3,2,4] and target is 6. I added (3,0) and (2,1) to the map and when I come to 4 and calculate value as 6 - 4 as 2 and when I check if 2 is a key present in map or not, it does not go in if loop.
I should get output as [1,2] which are the indices for 2 and 4 respectively
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
int[] arr = new int[2];
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0;i < len; i++)
{
int value = nums[i] - target;
if(map.containsKey(value))
{
System.out.println("Hello");
arr[0] = value;
arr[1] = map.get(value);
return arr;
}
else
{
map.put(nums[i],i);
}
}
return null;
}
I don't get where the problem is, please help me out
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice. Consider input [3,2,4] and target is 6. I added (3,0) and (2,1) to the map and when I come to 4 and calculate value as 6 - 4 as 2 and when I check if 2 is a key present in map or not, it does not go in if loop.
Okay, let's take a step back for a second.
You have a list of values, [3,2,4]. You need to know which two will add up 6, well, by looking at it we know that the answer should be [1,2] (values 2 and 4)
The question now is, how do you do that programmatically
The solution is (to be honest), very simple, you need two loops, this allows you to compare each element in the list with every other element in the list
for (int outter = 0; outter < values.length; outter++) {
int outterValue = values[outter];
for (int inner = 0; inner < values.length; inner++) {
if (inner != outter) { // Don't want to compare the same index
int innerValue = values[inner];
if (innerValue + outterValue == targetValue) {
// The outter and inner indices now form the answer
}
}
}
}
While not highly efficient (yes, it would be easy to optimise the inner loop, but given the OP's current attempt, I forewent it), this is VERY simple example of how you might achieve what is actually a very common problem
int value = nums[i] - target;
Your subtraction is backwards, as nums[i] is probably smaller than target. So value is getting set to a negative number. The following would be better:
int value = target - nums[i];
(Fixing this won't fix your whole program, but it explains why you're getting the behavior that you are.)
This code for twoSum might help you. For the inputs of integer array, it will return the indices of the array if the sum of the values = target.
public static int[] twoSum(int[] nums, int target) {
int[] indices = new int[2];
outerloop:
for(int i = 0; i < nums.length; i++){
for(int j = 0; j < nums.length; j++){
if((nums[i]+nums[j]) == target){
indices[0] = i;
indices[1] = j;
break outerloop;
}
}
}
return indices;
}
You can call the function using
int[] num = {1,2,3};
int[] out = twoSum(num,4);
System.out.println(out[0]);
System.out.println(out[1]);
Output:
0
2
You should update the way you compute for the value as follows:
int value = target - nums[i];
You can also check this video if you want to better visualize it. It includes Brute force and Linear approach:
I have a string array
"Ben", "Jim", "Ken"
how can I print the above array 3 times to look like this:
"Ben", "Jim", "Ken"
"Jim", "Ben", "Ken"
"Ken", "Jim", "Ben"
I just want each item in the initial array to appear as the first element. The order the other items appear does not matter.
more examples
Input
"a","b","c","d"
output
"a","b","c","d"
"b","a","c","d"
"c","b","a","d"
"d","a","c","d"
Method signature
public void printArray(String[] s){
}
Rather than give you straight-up code, I'm going to try and explain the theory/mathematics for this problem.
The two easiest ways I can come up with to solve this problem is to either
Cycle through all the elements
Pick an element and list the rest
The first method would require you to iterate through the indices and then iterate through all the elements in the array and loop back to the beginning when necessary, terminating when you return to the original element.
The second method would require you to iterate through the indices, print original element, then proceed to iterate through the array from the beginning, skipping the original element.
As you can see, both these methods require two loops (as you are iterating through the array twice)
In pseudo code, the first method could be written as:
for (i = array_start; i < array_end; i++) {
print array_element[i]
for (j = i + 1; j != i; j++) {
if (j is_larger_than array_end) {
set j equal to array_start
}
print array_element[j]
}
}
In pseudo code, the second method could be written as:
for (i = array_start; i < array_end; i++) {
print array_element[i]
for (j = array_start; j < array_end; j++) {
if (j is_not_equal_to i) {
print array_element[j]
}
}
}
public void printArray(String[] s){
for (int i = 0; i < s.length; i++) {
System.out.print("\"" + s[i] + "\",");
for (int j = 0; j < s.length; j++) {
if (j != i) {
System.out.print("\"" + s[j] + "\",");
}
}
System.out.println();
}
}
This sounds like a homework question so while I feel I shouldn't answer it, I'll give a simple hint. You are looking for an algorithm which will give all permutations (combinations) of the "for loop index" of the elements not the elements themselves. so if you have three elements a,b,c them the index is 0,1,2 and all we need is a way to generate permutations of 0,1,2 so this leads to a common math problem with a very simple math formula.
See here: https://cbpowell.wordpress.com/2009/11/14/permutations-vs-combinations-how-to-calculate-arrangements/
for(int i=0;i<s.length;i++){
for(int j=i;j<s.length+i;j++) {
System.out.print(s[j%(s.length)]);
}
System.out.println();
}
Using mod is approppiate for this question. The indexes of the printed values for your first example are like this;
0 1 2
1 2 0
2 0 1
so if you write them like the following and take mod of length of the array (3 in this case) you will reach solution.
0 1 2
1 2 3
2 3 4
Im trying to add an element to an array at its last position in Java, but I am not able to...
Or rather, I don't know how to. This is the code at the moment:
String[] values = split(line, ",");
int[][] coordinates = new int[2][values/2];
for(int i = 0; i < values.length; i++) {
if(i % 2 == 0) { //THIS IS EVEN VALUES AND 0
coordinates[0][coordinates[0].length] = values[i];
} else { //THIS IS ODD VALUE
coordinates[1][coordinates[1].length] = values[i];
}
}
EDITED VERSION:
String[] values = split(line, ",");
int[][] coordinates = new int[2][values/2];
int x_pos = 0;
int y_post = 0;
for(int i = 0; i < values.length; i++) {
if(i % 2 == 0) { //THIS IS EVEN VALUES AND 0
coordinates[0][x_pos] = values[i];
x_pos++;
} else { //THIS IS ODD VALUE
coordinates[1][y_pos] = values[i];
y_pos++;
}
}
values is being read from a CSV file. My code is I believe wrong, since it will try to add the values always at the maximum array size for coordinates[] in both cases.
How would I go around adding them at the last set position?
Thanks!
/e: Would the EDITED VERSION be correct?
Your original code has two problems:
it addresses the array badly, the las element in a Java array is at position length-1, and this would result in an ArrayOutOfBoundsException
even if you'd correct it by subtracting 1, you would always overwrite the last element only, as the length of a Java array is not related to how many elements it contains, but how many elements it was initialised to contain.
Instead of:
coordinates[0][coordinates[0].length] = values[i];
You could use:
coordinates[0][(int)Math.round(i/2.0)] = values[i];
(and of course, same with coordinates[1]...)
EDIT
This is ugly of course:
(int)Math.round(i/2.0)
but the solution I'd use is far less easy to understand:
i>>1
This is a right shift operator, exactly the kind of thing needed here, and is quicker than every other approach...
Conclusion: this is to be used in a live scenario:
Use
coordinates[0][i>>1] = values[i];
EDIT2
One learns new things every day...
This is just as good, maybe a bit slower.
coordinates[0][i/2] = values[i];
If you know you'll definitely have an even number of values you can do
for(int i = 0; i < values.length / 2; i++) {
coordinates[0][i] = values[2*i];
coordinates[1][i] = values[2*i + 1];
}
You have to store the last position somewhere. .length gives you the size of the array.
The position in the array will always be the half of i (since you put half of the elements in one array and the other half in the other).
String[] values = split(line, ",");
int[][] coordinates = new int[2][values/2];
for(int i = 0; i < values.length; i++) {
if(i % 2 == 0) { //THIS IS EVEN VALUES AND 0
coordinates[0][ i / 2] = values[i];
} else { //THIS IS ODD VALUE
coordinates[1][ i / 2 + 1 ] = values[i];
}
}
The array index for java is from "0" to "array length - 1".
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.
why not:
String[] values = split(line, ",");
int[][] coordinates = new int[2][values/2];
for(int i = 0; i < values.length; i+=2) {
coordinates[0][i/2] = values[i];
coordinates[1][i/2] = values[i+1];
}