Not sure if this exact question's been asked before, though a similar question has been asked here. Essentially, what I'm trying to is generate random integers of a minimum size that still sum up to a certain value (an invariant is that the sum / (number of randoms you want) is greater than the minimum value. Here's a sad attempt I coded up:
import java.util.Arrays;
import java.util.Random;
public class ScratchWork {
private static Random rand = new Random();
public static void main(String[] args) {
int[] randoms = genRandoms(1000, 10, 30);
for (int i = 0; i<randoms.length; i++) sop("Random Number "+ (i+1) + ": " + randoms[i]);
sop("Sum: " + sum(randoms));
}
public static int sum(int[] array) { int sum = 0; for (int i : array) sum+=i; return sum; }
public static int[] genRandoms(int n, int numberOfRandoms, int min) {
if (min > n/numberOfRandoms) throw new UnsupportedOperationException();
int[] intRandArray = {0};
while (sum(intRandArray) != n) {
////////////////////////
// See https://stackoverflow.com/questions/2640053/getting-n-random-numbers-that-the-sum-is-m
Double[] randArray = new Double[numberOfRandoms];
double workerSum = 0;
for (int i = 0; i<numberOfRandoms; i++) {
randArray[i] = ((double)rand.nextInt(n-1)+1);
workerSum += randArray[i];
}
for (int i = 0; i<randArray.length; i++) {
randArray[i] = n*(randArray[i]/(workerSum));
}
/////////////////////////
while (existsSmallerNumThanMin(randArray, min))
randArray = continueToFix(randArray, min);
//Convert doubles to ints
intRandArray = new int [randArray.length];
for (int i = 0; i < intRandArray.length; i++)
intRandArray[i] = (int)Math.round(randArray[i]);
}
return intRandArray;
}
public static boolean existsSmallerNumThanMin(Double[] randArray, int min) {
for (double i : randArray) if (i < (double)min) return true;
return false;
}
public static Double[] continueToFix(Double[]randArray, int min) {
Double[] tempArray = Arrays.copyOf(randArray, randArray.length);
Arrays.sort(tempArray);
int smallest = Arrays.asList(randArray).indexOf(tempArray[0]);
int largest = Arrays.asList(randArray).indexOf(tempArray[tempArray.length-1]);
double randomDelta = rand.nextInt(min);
randArray[smallest]+=randomDelta;
randArray[largest]-=randomDelta;
return randArray;
}
public static void sop(Object s) { System.out.println(s); }
}
This is neither an elegant nor high-performing way to do this... It also doesn't seem to work well (if at all) when passed in, say, (100,10,10), which only allows for the number 10 in the array. The distribution of the random numbers is also pretty bad.
Is there an elegant approach to this??
Also, my end goal is to implement this in Objective-C, though I'm still just learning the ropes of that language, so any tips for doing this in that language would be greatly appreciated.
I did some more testing, and my Java implementation is broken. I think my algorithm is bad.
How about something like getting N random numbers in [0,1] and normalize the results based on their sums (different than the desired sum). Then multiply these values against the desired number sum.
This assumes the minimum size is 0. Generalizing this to maintain a minimum for each result is simple. Just feed in sum - min * n for sum. Add min to all the results.
To avoid potential floating point issues, you can do something similar with using a range of integer values that are logically on the scale [0,M] (M arbitarily large) instead of [0,1]. The idea is the same in that you "normalize" your random results. So lets say you get a random sum of N (want N to have to be a multiple of sum+1... see REMARK). Divy N up by sum+1 parts. The first part is 0, second is 1, ..., last is sum. Each random value looks up its value by seeing what part of N it belongs to.
REMARK: If you are okay with an arbitrarily small amount of bias, make each die roll a magnitude larger than sum (might want BigInteger for this). Let N be the sum. Then N = k*sum + rem where rem < sum. If N is large, then rem / k -> 0, which is good. N is probabilistically large if M is large.
Algorithm psuedo code:
F(S, N):
let R[] = list of 0's of size N
if S = 0: return R[]
for 0 <= i < N
R[i] = random integer in [0, M] -- inclusive and (M >= S). M should be an order larger than S. A good pick might be M = 1000*S*N. Not sure though. M should probably be based on both S and N though or simply an outragously large number.
let Z = sum R[]
for 0 <= i < N
R[i] = (Z mod R[i]) mod (S+1)
return R[]
Java implementation:
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
public class Rand {
private final Random rand;
public Rand () {
this(new Random());
}
public Rand (Random rand) {
this.rand = rand;
}
public int[] randNums (int total, int minVal, int numRands) {
if (minVal * numRands > total) {
throw new IllegalArgumentException();
}
int[] results = randNums(total - minVal * numRands, numRands);
for (int i = 0; i < numRands; ++i) {
results[i] += minVal;
}
return results;
}
private int[] randNums (int total, int n) {
final int[] results = new int[n];
if (total == 0) {
Arrays.fill(results, 0);
return results;
}
final BigInteger[] rs = new BigInteger[n];
final BigInteger totalPlus1 = BigInteger.valueOf(total + 1L);
while (true) {
for (int i = 0; i < n; ++i) {
rs[i] = new BigInteger(256, rand);
}
BigInteger sum = BigInteger.ZERO;
for (BigInteger r : rs) {
sum = sum.add(r);
}
if (sum.compareTo(BigInteger.ZERO) == 0) {
continue;
}
for (int i = 0; i < n; ++i) {
results[i] = sum.mod(rs[i]).mod(totalPlus1).intValue();
}
return results;
}
}
public static void main (String[] args) {
Rand rand = new Rand();
Map<Integer, Integer> distribution = new TreeMap<Integer, Integer>();
final int total = 107;
final int minVal = 3;
final int n = 23;
for (int i = total - (n-1) * minVal; i >= minVal; --i) {
distribution.put(i, 0);
}
for (int i = 0; i < 100000; ++i) {
int[] rs = rand.randNums(total, minVal, n);
for (int r : rs) {
int count = distribution.get(r);
distribution.put(r, count + 1);
}
}
System.out.print(distribution);
}
}
Does this do what you need?
import java.util.Arrays;
import java.util.Random;
public class ScratchWork {
static Random rng = new Random();
public static int randomRange(int n) {
// Random integer between 0 and n-1
assert n > 0;
int r = rng.nextInt();
if(r >= 0 && r < Integer.MAX_VALUE / n * n) {
return r % n;
}
return randomRange(n);
}
public static int[] genRandoms(int n, int numberOfRandoms, int min) {
int randomArray[] = new int[numberOfRandoms];
for(int i = 0; i < numberOfRandoms; i++) {
randomArray[i] = min;
}
for(int i = min*numberOfRandoms; i < n; i++) {
randomArray[randomRange(numberOfRandoms)] += 1;
}
return randomArray;
}
public static void main(String[] args) {
int randoms[] = genRandoms(1000, 10, 30);
System.out.println(Arrays.toString(randoms));
}
}
Based on the revised requirements in the comments below.
public static int[] genRandoms(int total, int numberOfRandoms, int minimumValue) {
int[] ret = new int[numberOfRandoms];
Random rnd = new Random();
int totalLeft = total;
for (int i = 0; i < numberOfRandoms; i++) {
final int rollsLeft = numberOfRandoms - i;
int thisMax = totalLeft - (rollsLeft - 1) * minimumValue;
int thisMin = Math.max(minimumValue, totalLeft / rollsLeft);
int range = thisMax - thisMin;
if (range < 0)
throw new IllegalArgumentException("Cannot have " + minimumValue + " * " + numberOfRandoms + " < " + total);
int rndValue = range;
for (int j = 0; j * j < rollsLeft; j++)
rndValue = rnd.nextInt(rndValue + 1);
totalLeft -= ret[i] = rndValue + thisMin;
}
Collections.shuffle(Arrays.asList(ret), rnd);
return ret;
}
public static void main(String... args) throws IOException {
for (int i = 100; i <= 1000; i += 150)
System.out.println("genRandoms(" + i + ", 30, 10) = " + Arrays.toString(genRandoms(1000, 30, 10)));
}
prints
genRandoms(100, 30, 10) = [34, 13, 22, 20, 26, 12, 30, 45, 22, 35, 108, 20, 31, 53, 11, 35, 20, 11, 18, 32, 14, 30, 20, 19, 31, 31, 151, 45, 25, 36]
genRandoms(250, 30, 10) = [30, 27, 25, 34, 28, 33, 34, 82, 45, 30, 24, 26, 26, 45, 19, 18, 95, 28, 22, 30, 30, 25, 38, 11, 18, 27, 77, 26, 26, 21]
genRandoms(400, 30, 10) = [48, 25, 19, 22, 36, 65, 24, 29, 49, 24, 11, 30, 33, 41, 37, 33, 29, 36, 28, 24, 32, 12, 28, 29, 29, 34, 35, 28, 27, 103]
genRandoms(550, 30, 10) = [25, 44, 72, 36, 55, 41, 11, 33, 20, 21, 33, 19, 29, 30, 13, 39, 54, 26, 33, 30, 40, 32, 21, 31, 61, 13, 16, 51, 37, 34]
genRandoms(700, 30, 10) = [22, 13, 24, 26, 23, 61, 44, 79, 69, 25, 29, 83, 29, 35, 25, 13, 33, 32, 13, 12, 30, 26, 28, 26, 14, 21, 26, 13, 84, 42]
genRandoms(850, 30, 10) = [11, 119, 69, 14, 39, 62, 51, 52, 34, 16, 12, 17, 28, 25, 17, 31, 32, 30, 34, 12, 12, 38, 11, 32, 25, 16, 31, 82, 18, 30]
genRandoms(1000, 30, 10) = [25, 46, 59, 48, 36, 32, 29, 12, 27, 34, 33, 14, 12, 30, 29, 31, 25, 16, 34, 44, 25, 50, 60, 32, 42, 32, 13, 41, 51, 38]
IMHO, Shuffling the result improves the randomness of the distribution.
Maybe a recursive approach:
if numberOfRandoms is 1, return n
if numberOfRandoms is x+1
get a random integer (myNumber) between min and n-min*x (so that at least min is left for each of the remaining x numbers)
get the remaining x that add up to n-myNumber
This is a utility method for generating a fixed length random number.
public final static String createRandomNumber(long len) {
if (len > 18)
throw new IllegalStateException("To many digits");
long tLen = (long) Math.pow(10, len - 1) * 9;
long number = (long) (Math.random() * tLen) + (long) Math.pow(10, len - 1) * 1;
String tVal = number + "";
if (tVal.length() != len) {
throw new IllegalStateException("The random number '" + tVal + "' is not '" + len + "' digits");
}
return tVal;
}
Related
So I have this dummy 2D array:
int mat[][] = {
{10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89}};
I want to add up all the values by columns so it would add 10 + 15 + 27 + 32 and return 84 and so on. I have this so far:
public void sum(int[][] array) {
int count = 0;
for (int rows = 0; rows < array.length; rows++) {
for (int columns = 0; columns < array[rows].length; columns++) {
System.out.print(array[rows][columns] + "\t");
count += array[0][0];
}
System.out.println();
System.out.println("total = " + count);
}
}
Can anyone help with this? Also the System.out.print(array[rows][columns] + "\t" ); prints the array out by rows, is there a way to print it out by columns?
One possible Solution would be to first find maximum size of all sub arrays and iterate that many times to find sum of each column avoiding unavailable values.
public static void main(String[] args) {
int mat[][] = {{10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89},
};
// Find maximum possible length of sub array
int maxLength = 0;
for (int i = 0; i < mat.length; i++) {
if (maxLength < mat[i].length)
maxLength = mat[i].length;
}
for (int i = 0; i < maxLength; i++) {
int sum = 0;
for (int j = 0; j < mat.length; j++) {
// Avoid if no value available for
// ith column from this subarray
if (i < mat[j].length)
sum += mat[j][i];
}
System.out.println("Sum of Column " + i + " = " + sum);
}
}
Use an ArrayList to get the sum of all the columns.
public static void sum(int[][] array) {
ArrayList<Integer> sums = new ArrayList<>();
for (int row = 0; row < array.length; row++) {
for (int column = 0; column < array[row].length; column++) {
if (sums.size() <= column) {
sums.add(column, 0);
}
int curVal = sums.get(column);
sums.remove(column);
sums.add(column, curVal + array[row][column]);
}
}
for (int i = 0; i < sums.size(); i++) {
System.out.println("Sum of column " + i + " = " + sums.get(i));
}
}
Here is one alternative.
The supplied data.
int mat[][] = { { 10, 20, 30, 40, 50, 60, 70, 80, 90 },
{ 15, 25, 35, 45 }, { 27, 29, 37, 48 },
{ 32, 33, 39, 50, 51, 89 }, };
First, find the maximum length of the array in which to store the sum.
int max = Arrays.stream(mat).mapToInt(a -> a.length).max().orElse(0);
Allocate the new array to hold the sums.
int[] sums = new int[max];
Now just use the Arrays.setAll method to sum them, taking careto not exceed the current array's length.
for (int[] arr : mat) {
Arrays.setAll(sums, i-> i < arr.length ? sums[i] + arr[i] : sums[i]);
}
System.out.println(Arrays.toString(sums));
Prints
[84, 107, 141, 183, 101, 149, 70, 80, 90]
You can use Stream.reduce method to summarise the elements of the rows of the matrix by the columns:
int[][] matrix = {
{10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89}};
int[] arr = Arrays.stream(matrix)
// summarize in pairs
// the rows of the matrix
.reduce((row1, row2) -> IntStream
// iterate over the indices
// from 0 to maximum row length
.range(0, Math.max(row1.length, row2.length))
// summarize in pairs the elements of two rows
.map(i -> (i < row1.length ? row1[i] : 0) +
(i < row2.length ? row2[i] : 0))
// an array of sums
.toArray())
// the resulting array
.get();
System.out.println(Arrays.toString(arr));
// [84, 107, 141, 183, 101, 149, 70, 80, 90]
See also:
• Sum of 2 different 2d arrays
• How to calculate the average value of each column in 2D array?
…and the same with lambda:
int[] array = Arrays.stream(mat)
.reduce((a1, a2) -> IntStream.range(0, Math.max(a1.length, a2.length))
.map(i -> i < a1.length && i < a2.length ? a1[i] + a2[i]
: i < a1.length ? a1[i] : a2[i] ).toArray()).get();
gets the sums of each column in the int[] array:
[84, 107, 141, 183, 101, 149, 70, 80, 90]
ReadFile randomGenerate = new ReadFile();
Input userNum = new Input();
String classnum = userNum.fileToSelect();
int lineNumber = randomGenerate.lineCounter(classnum);
//number of students in classnum.txt
ArrayList<String> people = randomGenerate.readPeople();
//a string of names(first word on each row)
int userPut = userNum.numInput();
int maxNum = lineNumber/userPut;
Right not, I am reading off a txt file - the first word of each row which is the name of a person. I want to distribute this ArrayList of people into even groups, with the number of groups based on userinput.
int[] numbers = RandomNumbersWithoutRepetition(0, lineNumber, lineNumber);
//an array of numbers IN ORDER
int[] randomNumbers = RandomizeArray(numbers);
//shuffles the array
I generated a set of numbers in order, and then shuffled them, which works fine.
But, my method of grouping people has been based off ifelse conditions which don't work so well. So is there an efficient method to put this ArrayList of names into user-desired groups?
I have x number of students.
I have n number of groups.
I'm assuming there's no other criteria for dividing students into groups.
Basically, you divide the number of groups into the number of students. Yes, you have to deal with a remainder. But it's straightforward.
Here are the results of a test. I created 53 students and shuffled them. I then divided the students into 4 groups. I manually formatted the output to fit in the answer. Group 1 has 14 students, while the remaining groups have 13 students.
Students: 42, 27, 5, 26, 32, 30, 44, 10, 17, 29, 40, 52,
47, 38, 49, 18, 46, 24, 34, 12, 13, 53, 35, 20, 1,
2, 41, 23, 43, 28, 8, 11, 50, 37, 9, 7, 48, 3, 33,
25, 31, 15, 22, 21, 14, 45, 36, 16, 51, 19, 4, 6, 39
Group 1: 42, 27, 5, 26, 32, 30, 44, 10, 17, 29, 40, 52, 47, 38
Group 2: 49, 18, 46, 24, 34, 12, 13, 53, 35, 20, 1, 2, 41
Group 3: 23, 43, 28, 8, 11, 50, 37, 9, 7, 48, 3, 33, 25
Group 4: 31, 15, 22, 21, 14, 45, 36, 16, 51, 19, 4, 6, 39
And here's the code. The groupStudents and sortStudents methods are the methods that do the work.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class StudentGroups {
public static void main(String[] args) {
int numberOfGroups = 4;
int numberOfStudents = 53;
StudentGroups sg = new StudentGroups(numberOfStudents);
sg.printStudents();
List<List<Integer>> groups = sg.groupStudents(
numberOfGroups);
sg.printGroups(groups);
}
private List<Integer> students;
public StudentGroups(int numberOfStudents) {
students = new ArrayList<>(numberOfStudents);
for (int i = 0; i < numberOfStudents; i++) {
students.add(i + 1);
}
Collections.shuffle(students);
}
public void printStudents() {
System.out.print("Students: ");
for (int i = 0; i < students.size(); i++) {
System.out.print(students.get(i));
if (i < (students.size() - 1)) {
System.out.print(", ");
}
}
System.out.println();
}
public List<List<Integer>> groupStudents(int groups) {
List<List<Integer>> output = new ArrayList<>();
int size = students.size();
int group = size / groups;
int remainder = size % groups;
sortStudents(output, size, group, remainder);
return output;
}
private void sortStudents(List<List<Integer>> output,
int size, int group, int remainder) {
List<Integer> list = new ArrayList<>();
int count = 0;
for (int i = 0; i < size; i++) {
list.add(students.get(i));
if (count == 0 && remainder > 0) {
if (group > 0) {
list.add(students.get(++i));
}
remainder--;
}
if (++count >= group) {
addList(output, list);
list = new ArrayList<>();
count = 0;
}
}
addList(output, list);
}
private void addList(List<List<Integer>> output,
List<Integer> list) {
if (list.size() > 0) {
output.add(list);
}
}
public void printGroups(List<List<Integer>> groups) {
for (int j = 0; j < groups.size(); j++) {
System.out.print("Group ");
System.out.print(j + 1);
System.out.print(": ");
List<Integer> students = groups.get(j);
for (int i = 0; i < students.size(); i++) {
System.out.print(students.get(i));
if (i < (students.size() - 1)) {
System.out.print(", ");
}
}
System.out.println();
}
}
}
Hi I have got merge Sort class I want to plot histogram of sorting array and when try to retrieve data from sorting class on screen appearing only unsorted array and then sorted array. How I have to restructure my sorting class so the full array will be returned on every occurrence of sorting or how I can retrieve merge(array, left, right) (I think this is the part I have to use to create histogram)
package mergeSort;
import java.util.*;
public class MergeSort {
public static void main(String[] args) {
int[] list = {14, 32, 67, 76, 23, 41, 58, 85};
System.out.println("before: " + Arrays.toString(list));
mergeSort(list);
System.out.println("after: " + Arrays.toString(list));
}
public static void mergeSort(int[] array) {
if (array.length > 1) {
// split array into two halves
int[] left = leftHalf(array);
int[] right = rightHalf(array);
// recursively sort the two halves
mergeSort(left);
mergeSort(right);
// merge the sorted halves into a sorted whole
merge(array, left, right);
}
}
// Returns the first half of the given array.
public static int[] leftHalf(int[] array) {
int size1 = array.length / 2;
int[] left = new int[size1];
for (int i = 0; i < size1; i++) {
left[i] = array[i];
}
return left;
}
// Returns the second half of the given array.
public static int[] rightHalf(int[] array) {
int size1 = array.length / 2;
int size2 = array.length - size1;
int[] right = new int[size2];
for (int i = 0; i < size2; i++) {
right[i] = array[i + size1];
}
return right;
}
public static void merge(int[] result, int[] left, int[] right) {
int i1 = 0; // index into left array
int i2 = 0; // index into right array
for (int i = 0; i < result.length; i++) {
if (i2 >= right.length || (i1 < left.length &&
left[i1] <= right[i2])) {
result[i] = left[i1]; // take from left
i1++;
} else {
result[i] = right[i2]; // take from right
i2++;
}
}
}
}
Also when I call for example bubble sort everything working fine so I think I must restructure the mergeClass
Please share if you have an idea thank you
This is my printing method
int Value = 100;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int edge= 50;
for (int i = 0; i < array.length; i++) {
g.drawLine(i + offSet, Value + edge, i + edge,
Value + edge- array[i]);
}
}
Bubble sort
public void bubbleSort(int[] a) throws InterruptedException {
for (int i = 0; i < a.length; i++) {
for (int j = 1; j < (a.length - i); j++) {
if (a[j - 1] > a[j])
swap(a, j - 1, j);
}
}
}
Would keeping a record of each step (rather than returning it each step) suffice? If so the following would give you a List of int[] arrays, each storing the value at each step of the sorting process. You could then iterate over the list and display it at your leisure.
The following:
package mergeSort;
import java.util.*;
public class MergeSort {
public static void main(String[] args) {
int[] list = {14, 32, 67, 76, 23, 41, 58, 85};
List<int[]> listOfLists = new ArrayList<int[]>();
System.out.println("before: " + Arrays.toString(list));
mergeSort(list,listOfLists);
System.out.println("after: " + Arrays.toString(list));
System.out.println("Each step:");
for(int[] arrList : listOfLists)
System.out.println(Arrays.toString(arrList));
}
public static void mergeSort(int[] array, List<int[]> listOfLists) {
if (array.length > 1) {
// split array into two halves
int[] left = leftHalf(array);
int[] right = rightHalf(array);
// recursively sort the two halves
mergeSort(left,listOfLists);
mergeSort(right,listOfLists);
// merge the sorted halves into a sorted whole
merge(array, left, right);
listOfLists.add(array);
}
}
// Returns the first half of the given array.
public static int[] leftHalf(int[] array) {
int size1 = array.length / 2;
int[] left = new int[size1];
for (int i = 0; i < size1; i++) {
left[i] = array[i];
}
return left;
}
// Returns the second half of the given array.
public static int[] rightHalf(int[] array) {
int size1 = array.length / 2;
int size2 = array.length - size1;
int[] right = new int[size2];
for (int i = 0; i < size2; i++) {
right[i] = array[i + size1];
}
return right;
}
public static void merge(int[] result, int[] left, int[] right) {
int i1 = 0; // index into left array
int i2 = 0; // index into right array
for (int i = 0; i < result.length; i++) {
if (i2 >= right.length || (i1 < left.length &&
left[i1] <= right[i2])) {
result[i] = left[i1]; // take from left
i1++;
} else {
result[i] = right[i2]; // take from right
i2++;
}
}
}
}
Would return this:
before: [14, 32, 67, 76, 23, 41, 58, 85]
after: [14, 23, 32, 41, 58, 67, 76, 85]
Each step:
[14, 32]
[67, 76]
[14, 32, 67, 76]
[23, 41]
[58, 85]
[23, 41, 58, 85]
[14, 23, 32, 41, 58, 67, 76, 85]
Ok, I think I understand the problem you have. Does this work for you? Where I've put the println statement you can instead render the current array.
package mergeSort;
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int[] list = { 14, 32, 76, 67, 41, 23, 58, 85 };
System.out.println("before: " + Arrays.toString(list));
mergeSort(list, 0, list.length - 1);
System.out.println("after: " + Arrays.toString(list));
}
public static void mergeSort(int[] array, int left, int right) {
int mid = 0;
if (right > left) {
mid = (right + left) / 2;
// sort left
mergeSort(array, left, mid);
// sort right
mergeSort(array, mid + 1, right);
// merge them
merge(array, left, mid+1, right);
// PUT YOUR HOOK TO DRAW THE ARRAY HERE
System.out.println("during: " + Arrays.toString(array));
}
}
public static void merge(int[] numbers, int left, int mid, int right) {
int[] temp = new int[numbers.length];
int i, left_end, num_elements, tmp_pos;
left_end = (mid - 1);
tmp_pos = left;
num_elements = (right - left + 1);
while ((left <= left_end) && (mid <= right)) {
if (numbers[left] <= numbers[mid])
temp[tmp_pos++] = numbers[left++];
else
temp[tmp_pos++] = numbers[mid++];
}
while (left <= left_end)
temp[tmp_pos++] = numbers[left++];
while (mid <= right)
temp[tmp_pos++] = numbers[mid++];
for (i = 0; i < num_elements; i++){
numbers[right] = temp[right];
right--;
}
}
}
The output that is produced is this:
before: [14, 32, 76, 67, 41, 23, 58, 85]
during: [14, 32, 76, 67, 41, 23, 58, 85]
during: [14, 32, 67, 76, 41, 23, 58, 85]
during: [14, 32, 67, 76, 41, 23, 58, 85]
during: [14, 32, 67, 76, 23, 41, 58, 85]
during: [14, 32, 67, 76, 23, 41, 58, 85]
during: [14, 32, 67, 76, 23, 41, 58, 85]
during: [14, 23, 32, 41, 58, 67, 76, 85]
after: [14, 23, 32, 41, 58, 67, 76, 85]
I tried using Arrays.binarySearch to find the number of pairs of ints in an array.In the following array, a brute force algorithm will find 4 pairs..However the binarysearch version gives 3 which is the wrong answer.
brute force:
public static int brutePairCount(int[] a){
int paircount = 0;
int N = a.length;
for(int i=0;i<N;i++){
for(int j=i+1;j<N;j++){
if(a[i]==a[j] ){
paircount++;
}
}
}
return paircount;
}
public static void main(String[] args) {
int[] nums = new int[]{12, 12, 23, 23, 45, 67, 75, 75, 85, 92, 111, 113, 113, 134, 142, 156};
int cnt1 = brutePairCount(nums);
System.out.println("pairs="+cnt1);
}
binarysearch:
public static int bsPairCount(int[] a){
Arrays.sort(a);
int paircount = 0;
int N = a.length;
for(int i=0;i<N;i++){
int key = a[i];
int idx = Arrays.binarySearch(a, key);
if(idx > i){
paircount++;
}
}
return paircount;
}
public static void main(String[] args) {
int[] nums = new int[]{12, 12, 23, 23, 45, 67, 75, 75, 85, 92, 111, 113, 113, 134, 142, 156};
int cnt1 = bsPairCount(nums);
System.out.println("pairs="+cnt1);
}
I found that the logic
if(idx > i){
paircount++;
}
is the source of error.My debugger shows that ,at i=11, key =113 ,the binarysearch(key) returns 11 itself,and so count is not incremented.
From the javadocs of Arrays.binarySearch :
If the range contains multiple elements equal to the specified object,
there is no guarantee which one will be found.
I think I found the problem,but how do I solve this? my brain is a bit addled (lack of sleep:( )..Can someone shed some light?
i have a for loop that multiples 3 and 7 by all numbers between 1 and 100. It only shows the numbers that are less the 100 after the multiplication though. How would you sort it so that its in ascending order?
for(int i = 1; i<=100; i++){
int result1 = 3 * i;
int result2 = 7*i;
if (result1 <=100){
System.out.println(+result1);
}
if (result2 <= 100){
System.out.println(+result2);
}
}
would use another if statement to sort it?
How about:
for(int i = 1; i<=100; i++){
if(i % 3 == 0 || i % 7 == 0)
System.out.println(i);
}
This sounds like it'll do what you need:
[mike#mike ~]$ cat temp/SO.java
package temp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SO {
private static final int MAX_VAL = 100;
public static void main(String[] args) {
List<Integer> results = new ArrayList<Integer>();
for (int i = 1; i <= MAX_VAL; i++) {
int result1 = 3 * i;
int result2 = 7 * i;
if (result1 <= MAX_VAL) {
results.add(result1);
}
if (result2 <= MAX_VAL) {
results.add(result2);
}
}
Collections.sort(results);
System.out.println(results);
}
}
[mike#mike ~]$ javac temp/SO.java
[mike#mike ~]$ java temp.SO
[3, 6, 7, 9, 12, 14, 15, 18, 21, 21, 24, 27, 28, 30, 33, 35, 36, 39, 42, 42, 45, 48, 49, 51, 54, 56, 57, 60, 63, 63, 66, 69, 70, 72, 75, 77, 78, 81, 84, 84, 87, 90, 91, 93, 96, 98, 99]