I have written the selection sort method before for ints, but right now I am working with an array of doubles. I have tried changing the variables to doubles, but I am still getting a "Cannot convert from double to int". Any help is appreciated, thanks!
//Original selection sort for ints
public static void selectionSort (int... arr)
{
int i = 0, j = 0, smallest = 0;
int temp = 0;
for (i = 0;i<arr.length - 1;i++)
{
smallest = i;
for (j = 1; j<arr.length - 1; j++)
{
if (arr[j]<arr[smallest])
smallest = j;
}
temp = arr[smallest];
arr[smallest] = arr[i];
arr[i] = temp;
}
}
//Attempted selection sort with doubles
public static void selectionSort (double...arr )
{
double i = 0.0, j = 0.0, smallest = 0.0;
double temp = 0.0;
for (i = 0.0;i<arr.length - 1.0;i++)
{
smallest = i;
for (j = 1.0; j<arr.length - 1.0; j++)
{
if (arr[j]<arr[smallest]) //error here with smallest and j
smallest = j;
}
temp = arr[smallest]; //error here with smallest
arr[smallest] = arr[i]; //error here with smallest and i
arr[i] = temp; //error here with i
}
}
The problem is that you've also used double for indexing the arrays. So try this instead:
public static void selectionSort (double...arr)
{
int i = 0, j = 0, smallest = 0;
double temp = 0.0;
for (i = 0; i < arr.length - 1; i++)
{
smallest = i;
for (j = 1; j < arr.length - 1; j++)
{
if (arr[j] < arr[smallest])
smallest = j;
}
temp = arr[smallest];
arr[smallest] = arr[i];
arr[i] = temp;
}
}
As you can see you still have doubles as parameter, and the temp-value and arr-array are also still doubles, but the indexes that are used for the array are ints.
Indexes are always int. For example, when we have an array of Strings, we still use ints for the indexes:
String[] sArray = {
"word1",
"word2",
"word3"
}
int index = 1;
String result = sArray[index]; // As you can see we use an int as index, and the result is a String
// In your case, the index is still an int, but the result is a double
Why did you change the for loop to doubles?
for (i = 0.0;i<arr.length - 1.0;i++)
It does only work with int's for the indexes of the arrays.
You have to use subscript value as int check out with that. Use like this
int i = 0,j =0,smallest = 0;
access array values using these
Related
Here is the code for the classic rod cutting problem. As the code stands, the sizes are 1, 2, 3, and 4, the size of the price array arr[]. How would I modify the code so that the sizes are set to different values other than those given. For example, 1, 2, 3 and 5 instead.
static double cutRod(double price[],int n)
{
double val[] = new double[n+1];
val[0] = 0;
for (int i = 1; i<=n; i++)
{
double max_val = Integer.MIN_VALUE;
for (int j = 0; j < i; j++)
max_val = Math.max(max_val,
price[j] + val[i-j-1]);
val[i] = max_val;
}
return val[n];
}
public static void main(String args[])
{
double arr[] = new double[] {1.2, 3, 5.8, 10.1};
int size = arr.length;
System.out.println("Maximum Obtainable Value is " +
cutRod(arr, size));
}
}
In the classical problem, j+1 in your inner loop represents the cut sizes possible. If you have custom cut sizes, store those in an array and use them instead of j + 1.
In the above program, let custom_sizes be the array storing the cuts, eg. 1,2,3,5, etc.
Modifying the above program:
static double cutRod(double price[],int custom_sizes[], int n)
{
double val[] = new double[n+1];
val[0] = 0;
for (int i = 1; i<=n; i++)
{
double max_val = Integer.MIN_VALUE;
for (int j = 0; j < custom_sizes.length; j++) {
if (i - custom_sizes[j] >= 0)
max_val = Math.max(max_val,
price[j] + val[i-custom_sizes[j]]);
}
val[i] = max_val;
}
return val[n];
}
Please note that it is assumed that input is valid and that price and custom_sizes are of equal length = n.
Recently I've been assigned a task which asks to me to "calculate the maximum difference between two adjacent numbers in the array that is passed to it". I'm fairly new to Java (I have only done VB in the past) and since this topic was not well explained to me, I'm not quite sure how to go about it.
Here is some additional information about the task itself:
The function has to pass the following test. The function maxDiff should calculate the maximum difference between two adjacent numbers in the array that is passed to it.
#Test
public void assessmentTest() {
int [] numbers = {12, 8, 34, 10, 59};
assertEquals(49, maxDiff(numbers));
int [] numbers2 = {-50, 100, 20, -40};
assertEquals(150, maxDiff(numbers2));
}
You must assure to take the absolute difference, don't forget it. That's why I used the Math.abs() function.
public static int maxDiff(int[] numbers) {
int diff = Math.abs(numbers[1] - numbers[0]);
for(int i = 1; i < numbers.length-1; i++)
if(Math.abs(numbers[i+1]-numbers[i]) > diff)
diff = Math.abs(numbers[i+1] - numbers[i]);
return diff;
}
Something like this should do the trick:
public static int maxDiff(int[] numbers) {
if (numbers.length < 2) {
return 0;
}
if (numbers.length == 2) {
return Math.abs(numbers[1] - numbers[0]);
}
int max = Math.abs(numbers[1] - numbers[0]);
for (int i = 2; i < numbers.length; i++) {
int diff = Math.abs(numbers[i-1] - numbers[i]);
if (diff > max) {
max = diff;
}
}
return max;
}
For the specific question you asked:
public static int maxDiff(int[] arr) {
if(arr.length < 2)
return -1; // error condition: throw exception?
int maxdiff = Integer.MIN_VALUE;
for(int i = 1; i < arr.length; ++i) {
int diff = Math.abs(arr[i] - arr[i-1]);
if(diff > maxdiff)
maxdiff = diff;
}
return maxdiff;
}
If you want the max difference across all numbers in the array (not just adjacent ones) the most efficient way to do it would be to iterate the array just once to find the minimum and maximum, then return the absolute value of the two values subtracted from each other.
public static int maxDiff(int[] arr) {
if(arr.length < 2)
return -1; // error condition: throw exception?
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(int i = 0; i < arr.length; ++i) {
if(arr[i] < min)
min = arr[i];
if(arr[i] > max)
max = arr[i];
}
return Math.abs(max - min);
}
This piece of code can help you:
int[] numbers = {12, 8, 34, 10, 59};
int diff = 0;
int previous = 0;
for (int n : numbers) {
diff = Math.max(diff, Math.abs(n - previous));
previous = n;
}
Variable "diff" will contain the value you look for.
You can use this for Java;
int arrayMaximalAdjacentDifference(int[] inputArray) {
int max=0;
for( int i = 1 ; i < inputArray.length ; i++ ){
max = Math.max(max,Math.abs(inputArray[i] - inputArray[i-1]));
}
return max;
}
I have figured out how to create an array of integers and create a method to find the most frequent value in the array. Creating this method by creating another array used as a counter for each value. but how would I go about creating a method used to find the most frequent double in an array of DOUBLES.. without using hashmaps or sorting?
-this is my code for the method using integers, but will not work with double values/double array
public static int findMostFrequentValue(int[] array) {
int i;
int[] numberCount = new int[100];
for (i = 0; i < array.length; i++)
++numberCount[array[i]];
int max = 0;
int j;
for (j = 0; j < numberCount.length; j++) {
if (numberCount[j] > max) max = j;
}
return max;
}
Here's a quick blurb, sticking to your requirement of no hashmaps or sorting. Note, as coded, if there's a tie it returns the last match. Also note this is exponential O(n^2) time with the inner loop, so poor for large arrays.
public class Frequency {
public static void main(String args[]) {
double[] array = {3.4, 6.8, 1.1, 2.4, 3.8, 6.8, 7.0, 5.0};
double result = findMostFrequentValue(array);
System.out.println("Most frequent value: " + result);
}
public static double findMostFrequentValue(double[] array) {
int[] count = new int[array.length];
for (int i = 0; i < array.length; i++) {
count[i] = 0;
for (int j = 0; j < array.length; j++) {
if (approxEquals(array[i], array[j], .0001)) {
count[i]++;
}
}
}
int index = 0;
int max = 0;
for (int i = 0; i < count.length; i++) {
if (count[i] > max) {
max = count[i];
index = i;
}
}
return array[index];
}
private static boolean approxEquals(double val1, double val2, double tolerance) {
return Math.abs(val1 - val2) < tolerance;
}
}
I how can I find the positions of the three lowest integers in an array?
I've tried to reverse it, but when I add a third number, it all goes to hell :p
Does anybody manage to pull this one off and help me? :)
EDIT: It would be nice to do it without changing or sorting the original array a.
public static int[] lowerThree(int[] a) {
int n = a.length;
if (n < 2) throw
new java.util.NoSuchElementException("a.length(" + n + ") < 2!");
int m = 0; // position for biggest
int nm = 1; // position for second biggest
if (a[1] > a[0]) { m = 1; nm = 0; }
int biggest = a[m]; // biggest value
int secondbiggest = a[nm]; // second biggest
for (int i = 2; i < n; i++) {
if (a[i] > secondbiggest) {
if (a[i] > biggest) {
nm = m;
secondbiggest = biggest;
m = i;
biggest = a[m];
}
else {
nm = i;
secondbiggest = a[nm];
}
}
} // for
return new int[] {m,nm};
}
EDIT: I've tried something here but it still doesn't work. I get wrong output + duplicates...
public static int[] lowerthree(int[] a) {
int n= a.length;
if(n < 3)
throw new IllegalArgumentException("wrong");
int m = 0;
int nm = 1;
int nnm= 2;
int smallest = a[m]; //
int secondsmallest = a[nm]; /
int thirdsmallest= a[nnm];
for(int i= 0; i< lengde; i++) {
if(a[i]< smallest) {
if(smalles< secondsmallest) {
if(secondsmallest< thirdsmallest) {
nnm= nm;
thirdsmallest= secondsmallest;
}
nm= m;
secondsmallest= smallest;
}
m= i;
smallest= a[m];
}
else if(a[i] < secondsmallest) {
if(secondsmallest< thirdsmallest) {
nnm= nm;
thirdsmallest= secondsmallest;
}
nm= i;
secondsmallest= a[nm];
}
else if(a[i]< thirdsmallest) {
nnm= i;
thirdsmallest= a[nnm];
}
}
return new int[] {m, nm, nnm};
}
Getting the top or bottom k is usually done with a partial sort. There are versions that change the original array and those that dont.
If you only want the bottom (exactly) 3 and want to get their positions, not the values, your solution might be the best fit. This is how I would change it to support the bottom three. (I have not tried to compile and run, there may be little mistakes but the genereal idea should fit)
public static int[] lowerThree(int[] a) {
if (a.length < 3) throw
new java.util.NoSuchElementException("...");
int indexSmallest = 0;
int index2ndSmallest = 0;
int index3rdSmallest = 0;
int smallest = Integer.MAX_VALUE;
int sndSmallest = Integer.MAX_VALUE;
int trdSmallest = Integer.MAX_VALUE;
for (size_t i = 0; i < a.length; ++i) {
if (a[i] < trdSmallest) {
if (a[i] < sndSmallest) {
if (a[i] < smallest) {
trdSmallest = sndSmallest;
index3rdSmallest = index2ndSmallest;
sndSmallest = smallest;
index2ndSmallest = indexSmallest;
smallest = a[i];
indexSmallest = i;
continue;
}
trdSmallest = sndSmallest;
index3rdSmallest = index2ndSmallest;
sndSmallest = a[i];
index2ndSmallest = i;
continue;
}
trdSmallest = a[i];
index3rdSmallest = i;
}
}
return new int[] {indexSmallest, index2ndSmallest, index3rdSmallest};
}
This will have the three lowest numbers, need to add some test cases..but here is the idea
int[] arr = new int[3];
arr[0] = list.get(0);
if(list.get(1) <= arr[0]){
int temp = arr[0];
arr[0] = list.get(1);
arr[1] = temp;
}
else{
arr[1] = list.get(1);
}
if(list.get(2) < arr[1]){
if(list.get(2) < arr[0]){
arr[2] = arr[1];
arr[1] = arr[0];
arr[0] = list.get(2);
}
else{
arr[2] = arr[1];
arr[1] = list.get(2);
}
}else{
arr[2] = list.get(2);
}
for(int integer = 3 ; integer < list.size() ; integer++){
if(list.get(integer) < arr[0]){
int temp = arr[0];
arr[0] = list.get(integer);
arr[2] = arr[1];
arr[1] = temp;
}
else if(list.get(integer) < arr[1]){
int temp = arr[1];
arr[1] = list.get(integer);
arr[2] = temp;
}
else if(list.get(integer) <= arr[2]){
arr[2] = list.get(integer);
}
}
I'd store the lowest elements in a LinkedList, so it is not fixed on the lowest 3 elements. What do you think?
public static int[] lowest(int[] arr, int n) {
LinkedList<Integer> res = new LinkedList();
for(int i = 0; i < arr.length; i++) {
boolean added = false;
//iterate over all elements in the which are of interest (n first)
for(int j = 0; !added && j < n && j < res.size(); j++) {
if(arr[i] < res.get(j)) {
res.add(j, i); //the element is less than the element currently considered
//one of the lowest n, so insert it
added = true; //help me get out of the loop
}
}
//Still room in the list, so let's append it
if(!added && res.size() < n) {
res.add(i);
}
}
//copy first n indices to result array
int[] r = new int[n];
for(int i = 0; i < n && i < res.size(); i++) {
r[i] = res.get(i);
}
return r;
}
In simple words, you need to compare every new element with the maximum of the three you have at hand, and swap them if needed (and if you swap, max of the three has to be recalculated).
I would use 2 arrays of size 3 each:
arrValues = [aV1 aV2 aV3] (reals)
arrPointers = [aP1 aP2 aP3] (integers)
and a 64 bit integer type, call it maxPointer.
I will outline the algorithm logic, since I am not familiar with Java:
Set arrValues = array[0] array[1] array[2] (three first elements of your array)
Set arrPointers = [0 1 2] (or [1 2 3] if your array starts from 1)
Iterate over the remaining elements. In each loop:
Compare the Element scanned in this iteration with arrValues[maxPointer]
If Element <= arrValues[maxPointer],
remove the maxPointer element,
find the new max element and reset the maxPointer
Else
scan next element
End If
Loop
At termination, arrPointers should have the positions of the three smallest elements.
I hope this helps?
There is an easy way to find the positions of three lowest number in an Array
Example :
int[] arr={3,5,1,2,9,7};
int[] position=new int[arr.length];
for(int i=0;i<arr.length;i++)
{
position[i]=i;
}
for(int i=0;i<arr.length;i++)
{
for(int j=i+1;j<arr.length;j++)
{
if(arr[i]>arr[j]){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
int tem=position[i];
position[i]=position[j];
position[j]=tem;
}
}
}
System.out.println("Lowest numbers in ascending order");
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
System.out.println("And their previous positions ");
for(int i=0;i<arr.length;i++)
{
System.out.println(position[i]);
}
Output
you can do it in 3 iterations.
You need two extra memory, one for location and one for value.
First iteration, you will keep the smallest value in one extra memory and its location in the second. As you are iterating, you compare every value in the slot with the value slot you keep in the memory, if the item you are visiting is smaller than what you have in your extra value slot, you replace the value as well as the location.
At the end of your first iteration, you will find the smallest element and its corresponding location.
You do the same for second and third smallest.
hello guys i need to sort some elements of integer in an integer array and need to store the index of the sorted list
assume if the elements in array are
x[]= {10,20,40,70,80,50,30};
i need to get the index of the sorted order say in this case i need to get 4,3,5,2,6,0 (ascending) (array x starting from 0)
A simple way (not algorithmically clever) would be to make a new list (or array) of objects from the existing list that contains the value and the index:
class ValueAndIndex implements Comparable<ValueAndIndex> {
final int value;
final int index;
ValueAndIndex(int value, int index) {
this.value = value;
this.index = index;
}
#Override public int compareTo(ValueAndIndex other) {
// compare on value;
if (this.value < other.value) {
return -1;
} else if (this.value > other.value) {
return 1;
} else {
return 0;
}
}
}
Now, create instances of this class in a list:
List<ValueAndIndex> secondaryList = new ArrayList<ValueAndIndex>(x.length);
for (int i = 0; i < x.length; ++i) {
secondaryList.add(new ValueAndIndex(x[i], i));
}
Sort this list:
Collections.sort(secondaryList);
Now, the indices are still in this list:
int [] indexesInSortedOrder = new int[x.length];
for (int i = 0; i < secondaryList.size(); ++i) {
indexesInSortedOrder[i] = secondaryList.get(i).index;
}
System.out.println(Arrays.toString(indexesInSortedOrder));
Possible solution
//sort the array intio a new array
y[] = x;
Arrays.sort(y); //sort ascending
//final array of indexes
int index_array[] = new int[7];
//iteretate on x arrat
for(int i=0; i<7; i++)
//search the position of a value of the original x array into the sorted y array, store the position in the index array
index_array[i] = arrays.binarySearch(x,y[i]);
you can create an array
y[] = {0,1,2,3,4,5,6};
And ith any sorting algorithm, when you switching moving two elements in array x, do the same in array y
One way to do (what I understand) you need:
Determine the size n of the original array.
Create result array R and initialize its elements with 0 . . n-1
Finally implement one sort algorithm in the way that it sorts a copy(!) of your original array whilst also switching the elements in R
Example run:
Copied Result
Array
------------------
1. 2-3-1 0-1-2
2. 2-1-3 0-2-1
3. 1-2-3 2-0-1
public Map sortDecendingDFSGlobal() {
Map<String, Object> multiValues = new HashMap<String, Object>();
double[] dfs = this.global_dfs;
int[] index = new int[dfs.length];
for (int i = 0; i < dfs.length; i++) {
index[i] = i;//for required indexing
}
for (int i = 0; i < dfs.length; i++) {
//sorting dfsglobal in decending order
double temp = dfs[i];
double swap = dfs[i];
int swapIndex = i;
//keeping track of changing indexing during sorting of dfsglobal
int indStart = index[i];
int indSwap = index[i];
int number = i;
for (int j = i; j < dfs.length; j++) {
if (temp < dfs[j]) {
temp = dfs[j];
swapIndex = j;
indSwap = index[j];
number = j;
}
}
dfs[i] = temp;
dfs[swapIndex] = swap;
index[i] = indSwap;
index[number] = indStart;
}
//again sorting the index matrix for exact indexing
for (int i = 0; i < index.length - 1; i++) {
for(int j = i; j < index.length - 1; j++ )
{
if(dfs[j] == dfs[j + 1] && index[j] > index[j + 1])
{
int temp = index[j];
index[j] = index[j+1];
index[j + 1] = temp;
}
}
}
this.sortedDFS = dfs;
this.arrIndex = index;
multiValues.put("sorted", dfs);
multiValues.put("index", index);
return multiValues;
} //SortedDecendingDFSGlobal()