Creating array from range of numbers - java

I need to create an array of doubles given a max and min and interval. So array will look something like {2.9, 4.9, 6.9,... etc}
I am getting an array of zeros.
public class FoolinAround {
public static void main(String[] args) {
double min = 2.9;
double max = 20.6;
double gap = 2.0;
double count = (max - min) / gap + 2; // as will need first and last
// element also
double array[] = new double[(int) count];
for (int j = 0; j < array.length; j++) {
double i = array[j];
min = min + gap;
}
for (double k : array) {
System.out.print(array[(int) k] + ",");
}
}
}

It appears you are missing the assignment to your array (array[j] = something;). It appears from your explantation that array is supposed to contain the results. If I understand the problem you are trying to solve, this looks like a solution.
public class FoolinAround {
public static void main(String[] args) {
double min = 2.9;
double max = 20.6;
double gap = 2.5;
double count = (max - min) / gap + 2; // as will need first and last
// element also
double array[] = new double[(int) count];
for (int j = 0; j < array.length; j++) {
array[j] = min + (j*gap);
}
for (double k : array) {
System.out.print(array[(int) k] + ",");
}
}
}
I didn't verify that this calculation will give you the correct size for your array: double count = (max - min) / gap + 2;. I suggest that you verify this calculation. Since you are relying on truncation, rather than rounding, you may have an off-by-one error.

Here is how
double[] array = DoubleStream.iterate(min, prev -> prev + gap)
.limit(count)
.toArray();
Link to DoubleStream

The problem that I found was with the assignment and the for-each loop. Here is how you can do it:
double min = 2.9;
double max = 20.6;
double gap = 2.0;
double count = (max - min) / gap + 2.0;
System.out.println(count);
double array[] = new double[(int) count];
for (int j = 0; j < array.length; j++) {
// double i = array[j]; /*Not sure why this assignment is used
// here?*/
array[j] = min;
min += gap;
}
for (double k : array) {
System.out.print(k + "\n"); // Here k is the double value from the
// array. array[(int)k] will give you
// element of array indexed at the
// element of array.
}

Related

JAVA: Sorting an array in descending order

I'm trying to sort an array in descending order, I know there are many examples of sorting an array online, but I just wanted to try and do it my own way (just trying to test to see if algorithm could actually work). But some reason, I'm unable to output the array with the result stored, I've tried using System.out.println(Arrays.toString(myList)); and printing them one at time, it works for one the arrays i created, but when trying to modify the array through a loop, it refused to output anything, no error, nothing as though nothing is there. Your help would be appreciated. see code below. Thanks.
import java.util.Arrays;
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 9.2, 3.4, 4.2, 6.7, 3.5};
double[] sortedList = new double[7] ;
// Print all the array elements
for (double i: myList) {
System.out.println(i + " ");
}
// Summing all elements
double total = 0;
for (double x: myList) {
total += x;
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
int m, z = 0;
for (double k: myList) {
if (k > max) max = k;
}
do{
for (int i = m; i < myList.length; i++) {
if (myList[i] > max){
max = myList[i];
z = i;
}
}
sortedList[m] = max;
myList[z] =0;
m++;
} while(m < myList.length);
System.out.println("Max is " + max);
//System.out.println(Arrays.toString(myList));
for (double y: sortedList) {
System.out.println(y + " ");
}
}
}
you can simply use inbuilt function to sort your array in descending order as
Arrays.sort(myList , Collections.reverseOrder());
System.out.println("myList Array Elements in reverse order:");
for (int i = 0; i < myList .length; i++)
System.out.println(intArray[i]);
It will work for sure.
Your logic for sorting is not working as intended. I have made some changes to it, give it a try :
do {
max = 0;
for (int i = 0; i < myList.length; i++) {
if (myList[i] > max) {
max = myList[i];
z = i;
}
}
sortedList[m] = max;
myList[z] = 0;
m++;
} while (m < myList.length);
The following code works for me.
public class Main {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 9.2, 3.4, 4.2, 6.7, 3.5};
double[] sortedList = new double[7] ;
// Print all the array elements
for (double i: myList) {
System.out.println(i + " ");
}
// Summing all elements
double total = 0;
for (double x: myList) {
total += x;
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
int m = 0;
int z = 0;
do{
for (int i = 0; i < myList.length; i++) {
if (myList[i] > max){
max = myList[i];
z = i;
}
}
sortedList[m] = max;
myList[z] =0;
m++;
max = 0;
} while(m < myList.length);
System.out.println("Max is " + max);
//System.out.println(Arrays.toString(myList));
for (double y: sortedList) {
System.out.println(y + " ");
}
}
}
You're code contained three errors:
1.You failed to reset 'max' in every iteration, leading to 'sortedList'
containing just the value 9.2 in every entry.
for (double k: myList) {
if (k > max) max = k;
}
is unneccessary. Moreover, it doesn't even keep track where the max element is.
3.
for (int i = m; i < myList.length; i++)
should be changed to
for (int i = 0; i < myList.length; i++)
The position you're at in 'sortedList' has nothing to do with where you can
find the maximum element of 'myList'.
First you need to convert this line int m, z = 0; to int m = 0, z = 0;
because int m, z = 0; is equivalent to int m; int z = 0;. Hence when you try to use variable m - it is not initialized yet and that results to a compilation error.
After fixing the above statement, your program will compile and run but there is also a mistake in the program logic as well and your result sorted array will be output as:
{9.2, 9.2, 9.2, 9.2, 9.2, 9.2, 9.2}
as in the following block
for (double k: myList) {
if (k > max) max = k;
}
you initially find the max value which is 9.2 . That's why when you later execute do .. while and check the condition here
if (myList[i] > max){
max = myList[i];
z = i;
}
the statement myList[i] > max will never return true and hence your max will be always remain 9.2 and z will be always remain 0. That's why the line sortedList[m] = max; always inserts 9.2 to each index of your sorted array.
In such cases i recommend you to use an IDE of your choice(Intellij Idea, Eclipse, etc.) which will highlight compilation errors and help you to find your bugs using the integrated debugger.
So i just found your mistakes, i think now you can manage it. In case of additional help feel free to communicate.

How to double an array size using a for loop to compare selection sort performance with different array sizes?

My goal for this project was to measure the performance of selection sort using random numbers. I wanted to begin with an array size of n=100, and I wanted to double that array size up to 200,000 (n = 100 * 2, n = 200 * 2, n = 400 * 2....) I did a pretty good job of setting up my selectionSort method in a class, but I am having trouble writing a for loop that will double my array size of 100.
Here is my code:
public static void selectionSort(int[] data) {
int temp;
int j;
int i;
for (i = 0; i < data.length - 1; i++ ){
int min = i;
for(j = i + 1; j < data.length; j++){
if(data[j] < data[min])
min = j;
}
temp = data[min];
data[min] = data[i];
data[i] = temp;
}
}
public static void main(String[] args) {
int[] bigdata = new int[100];
randomFill(bigdata, 100000);
for(int i = 100; i < 200000; i *= 2){ // this is where I am having trouble
bigdata[i] = bigdata[i] * 2;}
display(bigdata);
System.out.println("Is sorted before selectionSort: " + isSorted(bigdata));
long start = System.currentTimeMillis();
selectionSort(bigdata);
display(bigdata);
long elapsed = System.currentTimeMillis() - start;
System.out.println("Is sorted after selectionSort: " + isSorted(bigdata));
System.out.println("Elapsed time in milliseconds " + elapsed);
}
}
My code in main has successfully displayed selectionSort performance for a random array with a size of 100, but I am unsure where to go next with writing a forloop to double my array "big data" up to 200000.
public static void selectionSort(int[] data) {
int temp;
int j;
int i;
for (i = 0; i < data.length - 1; i++ ){
int min = i;
for(j = i + 1; j < data.length; j++){
if(data[j] < data[min])
min = j;
}
temp = data[min];
data[min] = data[i];
data[i] = temp;
}
}
public static void main(String[] args) {
int[] bigdata;
for(int i = 100; i < 200000; i *= 2){
// Here you double the size of bigdata array
bigdata = new int[i];
// You fill the i sized array
randomFill(bigdata, 100000);
display(bigdata);
System.out.println("Is sorted before selectionSort: " + isSorted(bigdata));
long start = System.currentTimeMillis();
selectionSort(bigdata);
display(bigdata);
long elapsed = System.currentTimeMillis() - start;
System.out.println("Is sorted after selectionSort: " + isSorted(bigdata));
System.out.println("Elapsed time in milliseconds " + elapsed);
}
}
Consider using an implementation of java.util.List, ex: java.util.ArrayList. This will ensure that you do not have to bother about managing the size of the list. It will automatically expand as and when you keep adding more elements.
int[] bigdata = new int[100];
can be changed to:
List<Integer> bigdata = new ArrayList<>();
The randomFill(int[], int) method can be changed to randomFill(List<Integer>, int).
This should help you get started in the right direction.

Get the minimum value and its index with a for loop

How can I get the minimum value in a for loop plus its index:?
Update: This is what I tried after using #Sakalya 's answer
LatLng myLatLang = new LatLng(myLocation.getLatitude(),myLocation.getLongitude());
double minval = -1.0;
int minIndex = 0;
for (int i = 0; i < stationsCoord.size(); i++) {
double distance = CalculationByDistance(myLatLang,stationsCoord.get(i));
if(distance < minval){
minval = distance;
minIndex = i;
}
Log.i("distance " , String.valueOf(distance));
System.out.println("min=" +minval+ "index="+minIndex);
}
//i'm looking for the min value of 'distance' + the index 'i'
I always get this: System.out: min=-1.0index=0
Thank you in advance.
First you can set a min variable to 1000000 and then iterate the list to find min value as below:
LatLng myLatLang = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
double minval = 1000000000000.0;
int minIndex = 0;
for (int i = 0; i < stationsCoord.size(); i++) {
double distance = CalculationByDistance(myLatLang,stationsCoord.get(i));
if (distance < minval) {
minval = distance;
minIndex = i;
}
Log.i("distance " , String.valueOf(distance));
System.out.println("min=" +minval+ "index="+minIndex);
}
In the following code
double minval = -1.0;
if (somepositivedistance < minval ) { // do something
}
nothing will ever return true if the distance is positive, therefore the statement will never execute.
You need to set minvalto something greater then the largest possible distance (for example Double.MAX_VALUE) before entering the for-loop.

Randomly split a given number M into N parts

So, the idea that I have, is to be able to divide $2.00 into 10 person, and each of them will receive $x.xx amount of money randomly. (N and M will always be limited to 2 decimals and > 0)
Ex: {0.12, 0.24, 1.03, 0.01, 0.2, 0.04, 0.11, 0.18, 0.05, 0.02}
Currently I have tried:
private static BigDecimal[] randSum(int n, double m)
{
Random rand = new Random();
BigDecimal randNums[] = new BigDecimal[n], sum = new BigDecimal(0).setScale(2);
for (int i = 0; i < randNums.length; i++)
{
randNums[i] = new BigDecimal(rand.nextDouble()).setScale(2, RoundingMode.HALF_EVEN);
sum = sum.add(randNums[i]);
}
for (int i = 0; i < randNums.length; i++)
{
BigDecimal temp1 = randNums[i].divide(sum, 2, RoundingMode.HALF_EVEN);
BigDecimal temp2 = temp1.multiply(new BigDecimal(m).setScale(2));
randNums[i] = temp2;
}
return randNums;
}
public static void main(String[] args)
{
BigDecimal d[] = randSum(5, 2);
double sum = 0;
for (BigDecimal n : d)
{
sum += n.doubleValue();
System.out.println(n);
}
System.out.println("total: " + sum);
}
But BigDecimals are too confusing and they don't add up. Sometimes the total is 1.98 or 2.01. Doubles doesn't work because of the Double-precision floating-point.
The code was taken from:
Getting N random numbers that the sum is M
Let's suppose you need a fixed precision (passed as prec argument):
static public BigDecimal[] split(BigDecimal sum, int prec, int count) {
int s = sum.scaleByPowerOfTen(prec).intValue();
Random r = new Random();
BigDecimal[] result = new BigDecimal[count];
int[] v = new int[count];
for (int i = 0; i < count - 1; i++)
v[i] = r.nextInt(s);
v[count - 1] = s;
Arrays.sort(v);
result[0] = BigDecimal.valueOf(v[0]).scaleByPowerOfTen(-prec);
for (int i = 1; i < count; i++)
result[i] = BigDecimal.valueOf(v[i] - v[i - 1]).scaleByPowerOfTen(-prec);
return result;
}
This approach uses property that Random.nextInt() is uniformly distributed. After sorting, values of v[] array are points by which the whole amount is split, so you generate result using differences between neighboring elements:
[ 2, 5, 10, 11, ..., 197, 200] // v[]
[0.02, 0.03, 0.05, 0.01, ..., ..., 0.03] // result[]
Here you operate with integer values, so rounding issues don't bother anymore.
I suggest to multiply all the numbers by 100 and rephrase your problem: generate the n random non-negative integer numbers which sum equals to the given m integer number. Later you can divide all the generated numbers by 100 to get what you want. Here's my implementation (similar to #SashaSalauyou version):
private static int[] randSum(int n, int min, int m) {
Random rand = new Random();
int[] nums = new int[n];
int max = m - min*n;
if(max <= 0)
throw new IllegalArgumentException();
for(int i=1; i<nums.length; i++) {
nums[i] = rand.nextInt(max);
}
Arrays.sort(nums, 1, nums.length);
for(int i=1; i<nums.length; i++) {
nums[i-1] = nums[i]-nums[i-1]+min;
}
nums[nums.length-1] = max-nums[nums.length-1]+min;
return nums;
}
I also added one more parameter, min which is the minimal wanted number. Set it to 0 if you accept zeros in the answer. Otherwise you may set it to 1 (then after division by 100 the lowest possible number will be 0.01).
You can treat this problem as integers, and instead of summing to M, make it sum to 100M.
Do the algorithm, and you will end up with non-integers number, such as 10.345, Now - basically what you would like to do is take the floor value of each number (10 in the above example), and to increase the number to 11 with probability proportional to 0.345.
That can be done by creating the reminder array: rem[i] = value[i] - ceil(value[i]), and choose M - sum{ceil(value[i])} values with replacements, according to the weighted probability of rem array.
Code:
public static BigDecimal[] createRandomSumsTo(BigDecimal M, int n) {
int m = M.multiply(BigDecimal.TEN).multiply(BigDecimal.TEN).intValue();
double[] rands = new double[n];
double sum = 0;
for (int i = 0; i < n; i++) {
rands[i] = rand.nextDouble();
sum += rands[i];
}
for (int i = 0; i < n; i++) rands[i] = (rands[i] / sum) * m;
int[] intVals = new int[n];
double[] rem = new double[n];
//create base and reminder array:
for (int i =0 ; i < n; i++) {
intVals[i] = (int) Math.floor(rands[i]);
rem[i] = rands[i] - intVals[i];
}
//for efficiently chosing a random value by weight
double[] aux = new double[n+1];
for (int i = 1 ; i < n+1; i++) {
aux[i] = aux[i-1] + rem[i-1];
}
//normalize to sum to one.
for (int i = 0 ; i < n+1; i++) {
aux[i] = aux[i] / aux[n];
}
int intsSum = 0;
for (int x : intVals) {
intsSum += x;
}
for (; intsSum < m; intsSum++) {
intVals[chooseWeighted(aux)]++;
}
//and create the BigDecimal array:
BigDecimal[] res = new BigDecimal[n];
for (int i = 0; i < n; i++) {
res[i] = new BigDecimal(intVals[i]).divide(BigDecimal.TEN).divide(BigDecimal.TEN);
}
return res;
}
private static int chooseWeighted(double[] probabilities) {
double r = rand.nextDouble();
int idx = Arrays.binarySearch(probabilities, r);
if (idx >= 0) return idx-1;
return (-1*idx) -2;
}

Minimum Of An Array

I'm confused as to what I should return from:
public static double min(double[] array) {
double[] tenDoubles = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + tenDoubles.length + " numbers: ");
for (int i = 0; i < tenDoubles.length; i++){
tenDoubles[i] = input.nextDouble();
}
for (int j = 0; j < tenDoubles.length; j++) {
double currentMin = tenDoubles[j];
double currentMinIndex = j;
for (int k = j; k < tenDoubles.length; k++) {
if (currentMin > tenDoubles[k]) {
currentMin = tenDoubles[k];
currentMinIndex = k;
}
}
}
}
How do I return a value from this method and print out the minimum double the user inputs?
By using java api you can find minimum number
To find minimun convert our array tenDoubles to List and then find the minimum using Collections.min() method.
In your code I have done modification to resolve issue
I have modified your code, you are taking input at two places from user.
1. In min() method you are taking input using scanner.
2. you are not using double[] array passed as parameter to min() method.
Pass your array as parameter to min() method It will find out minimum value ans pass result.
public class Main {
public static void main(String[] args) {
double[] tenDoubles = new double[10];
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + tenDoubles.length + " numbers: ");
for (int i = 0; i < tenDoubles.length; i++){
tenDoubles[i] = input.nextDouble();
}
System.out.println(min(tenDoubles));
}
public static double min(double[] tenDoubles) {
double currentMin=Integer.MAX_VALUE;
for (int j = 0; j < tenDoubles.length; j++) {
if (tenDoubles[j]< currentMin) {
currentMin = tenDoubles[j];
}
}
return currentMin;
}
}
Improved code:
public static double min() {
double[] tenDoubles = new double[10];// = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + tenDoubles.length + " numbers: ");
for (int i = 0; i < tenDoubles.length; i++){
tenDoubles[i] = input.nextDouble();
}
double currentMin = tenDoubles[0];
for (int j = 1; j < tenDoubles.length; j++) {
if (currentMin > tenDoubles[j]) {
currentMin = tenDoubles[j];
}
}
return currentMin;}
Your example needs restructuring. Read in your values into an array first and then pass this array as a parameter to your min function. To return the minimum, add
return currentMinIndex;
Finally use System.out.println to print the value returned.
Your min function will then look like
public static double min(double[] array) {
for (int j = 0; j < array.length; j++) {
double currentMin = array[j];
double currentMinIndex = j;
for (int k = j; k < array.length; k++) {
if (currentMin > array[k]) {
currentMin = array[k];
currentMinIndex = k;
}
}
}
return currentMinIndex;
}
though it is not necessary to go through the array twice.
You just need to keep track of the min value (which you are doing) and have it compared to each other element in the array. If the next element is less, then you change out the values.
// This will hold what the minimum value is
double currentMin = 0;
// The current value from the tenDoubles array
double currentValue;
// loop through each element of the array
for (int j = 0; j < tenDoubles.length; j++) {
// get the current value from the array
currentValue = tenDoubles[j];
// if this is the first element, then just set the minimum to this value
if (j ==0) {
// Set the value as the minimum
currentMin = currentValue;
}else {
// if the current value is less that what is already saved as the minimum,
// set it as the new minimum
if (currentValue < currentMin) {
currentMin = currentValue;
}
}
}
System.out.println("Minimum value: " + currentMin);
return currentMin;
UPDATE
If you don't have to use the for-loops, you can shorten this up a lot by just doing this:
public static double min(double[] array) {
Arrays.sort(array);
return array[0];
}

Categories

Resources