Running times for sorting methods over multple arrays - sorting

I have various sorting methods that are all sorting the same 100,000 random number array.
I'm using the following method to find the runtimes of each
long insertionStart = System.currentTimeMillis();
arr.Clone(iniArr);
arr.insertionSort();
long insertionFinal = System.currentTimeMillis() - insertionStart;
And the following for the random number arrary
int maxSize = 100000; // array size
Sortarr arr, iniArr; // reference to array
arr = new Sortarr(maxSize); // create the array
iniArr = new Sortarr(maxSize);
// insert random numbers
Random generator = new Random();
for (int i = 0; i < maxSize; i++) iniArr.insert(generator.nextInt());
How can I modify this so that I can have each of them sort 100 arrays rather than just one, and count the time of each array? Eg. Run1 - 23ms; Run2 - 25ms; ... Run100 - 22ms
EDIT:
I have one final thing to do.
So each iteration sorts the array a few ways, let's say insertion, merge, and quick sort.
So say insertion = 300ms, merge = 200ms, and quick = 100ms. I need to, for each iteration, find which method sorted the fastest.
I know this is a simple min/max type thing that you do a thousand times in lower programming classes.
Would it be easier to throw each value into an array and use an array.min call? (Whatever it actually is, new to java syntax..)

Currently, it looks like you are creating the array and then repeatedly sorting using different functions.
You simply need to put all of that in a loop.
int maxRuns = 100;
int maxSize = 100000; // array size
for (int run=0; run<maxRuns; run++) {
Sortarr arr, iniArr; // reference to array
arr = new Sortarr(maxSize); // create the array
iniArr = new Sortarr(maxSize);
// insert random numbers
Random generator = new Random();
for (int i = 0; i < maxSize; i++) iniArr.insert(generator.nextInt());
long insertionStart = System.currentTimeMillis();
arr.Clone(iniArr);
arr.insertionSort();
long insertionFinal = System.currentTimeMillis() - insertionStart;
/* <more code goes here> */
}
You can use the index run while printing out your results.

You probably would be doing something like:
for (int try = 0; try < 100; try++) {
iniArr = new Sortarr(maxSize);
// insert random numbers
Random generator = new Random();
for (int i = 0; i < maxSize; i++) iniArr.insert(generator.nextInt());
long insertionStart = System.currentTimeMillis();
arr.Clone(iniArr);
arr.insertionSort();
long insertionFinal = System.currentTimeMillis() - insertionStart;
// print out the time, and/or add up the total
}
you'd still need the initialization beforehand. I guess I don't know why the array is cloned before it is sorted. Can you directly sort that array?

Related

Separate stream of numbers into groups of closer integers

I have a stream of numbers such as
[2872, 2997, 3121, 13055, 14178, 14302, 23134, 23382, 23507, 32832, 33677, 34017, 43415, 44246, 44374, 52866, 54035, 54158, 62835, 64243, 64936, 73110, 73890, 74014, 82809, 83771, 83899, 93436, 94765, 94891].
I would like to split it as follows:
[[2872, 2997, 3121], [13055, 14178, 14302], [23134, 23382, 23507], [32832, 33677, 34017], [43415, 44246, 44374], [52866, 54035, 54158], [62835, 64243, 64936], [73110, 73890, 74014], [82809, 83771, 83899], [93436, 94765, 94891]].
It is to be noted that the distance between the groups could be closer to each other, also the digits within a group could be farther away.
This is not an answer, but a way to look at your data, which should be insightful.
Original values:
Deltas:
Can't you just create a list of list of integers (or array of array) with size N/3 (N being the total of your numbers), and then just loop on this length and put the minimal number in it?
Something like this (I don't know what language you are using so I use c# as exemple):
int len = numbersStream.count();
List<List<int>> BigList = new List<List<int>>();
List<int> smallList = new List<int>();
for (int i = 0; i < len; ++i)
{
smallList = new List<int>();
for (int j = 0; j < 3; ++i)
{
int value = Math.Min(numbersStream);
smallList.Add(value);
numbersStream.remove(value);
}
BigList.Add(smallList);
}
BigList will be : (2872, 2997, 3121), (13055, 14178, 14302) etc...
*Assuming you always have exactly %3 numbers, otherwise you just tune the algorithm to avoid exceptions
The solution is in java but basically what this does is find the average delta and groups everything in a subset if the difference between the two elements is smaller then that average. You can fine tune this process by changing how the averageDelta operates
ps. this solution assumes your input is at least 1 large and called temp
int[] diffrence = new int[temp.length-1];
for (int i=1; i < temp.length; i++) {
diffrence[i-1] = temp[i]-temp[i-1];
}
int averageDelta = (int) Math.round(Arrays.stream(diffrence).average().orElse(1.0));
List<List<Integer>> resultList = new ArrayList<>();
List<Integer> currentList = new ArrayList<>();
currentList.add(temp[0]);
for (int i=1; i < temp.length; i++) {
if (temp[i]-temp[i-1] > averageDelta) {
resultList.add(currentList);
currentList = new ArrayList<>();
}
currentList.add(temp[i]);
}
resultList.add(currentList);
System.out.println(resultList.toString());

Looping through an arraylist of object variables and inputing them into an array in Processing

This is a section of my code, I have an ArrayList of 10 objects called "bob" and I want to loop through them so that each of their names (a local integer defined in the bob class) to be put in the array named "names" in order.
for (bob b : bob) {
for (int i = 0; i < 10; i++){
names[i] = b.name;
}
}
I tried this approach:
for (bob b : bob) {
for (int i = 0; i < 10; i++){
names[i] = b[i].name; //I added the "[i]" after b attempting to loop through
//the arraylist but it does not work
}
}
the syntax does not seem to allow me to loop through the arraylist of the objects like that. I am a beginning programmer so please excuse my lack of programming knowledge. It would be very helpful if someone could at least give me an idea of where to go from here. Thank you in advance!
When dealing with ArrayList you need to use the set() and get() methods to access the contents of it. Here's a somewhat hamfisted attempt at recreating the scenario you describe. Hope it helps.
class Bob {
int name;
Bob() {
this.name = floor(random(10000));
}
}
void setup(){
ArrayList<Bob> alb = new ArrayList<Bob>();
for(int i = 0; i < 50; i++){ //populate ArrayList
alb.add(new Bob());
}
int[] names = new int[10];
for(int i = 0; i < names.length; i++){
names[i] = alb.get(i).name; // use get() method
}
for(int i = 0; i < names.length; i++){
print(names[i]);
print('\n');
}
}
Your question highlights two techniques for iterating over a collection: with or without, an index. Each is best suited for different data structures and scenarios. It takes some experience to decide when to use one or the other, and is also a matter of personal style.
It is common to write code like for( int x: myInts ) and then realize you want the index of the current item, which isn't available. Or conversely, to write code like for( int i=first; i<last; i++) and then become irritated because determining first and last is tedious, or prone to bugs.
Notice your code is a double-nested loop. It says "iterate over each item in the collection Bob, and then for each one, iterate over each item in the collection of names". So if Bob had ten items, this would iterate one hundred total times, probably not what you want. You need to rewrite as a single, non-nested for loop ...
If you decide to iterate without an index, then names should be some type of list, where you can add items using append(). Consider the StringList available in Processing. Otherwise if you decide to iterate with an index, then names could be an array, although it could still be a list if it was already populated with old values which you wish to overwrite. The following shows both techniques:
void setup()
{
ArrayList<String> baseList = new ArrayList<String>(10);
for( int i=0; i<10; i++ )
baseList.add( i, Integer.toString( i + (i*10) ) );
// Approach 1: Iterate without an index,
// build a list with no initial allocation and using append()
StringList namesList = new StringList();
for( String s : baseList )
{
namesList.append( s );
println( namesList.get( namesList.size()-1 ) );
}
// Approach 2: Iterate with an index,
// build a list using preallocation and array access
String[] namesArray = new String[10];
for( int i=0; i<10; i++ )
{
namesArray[i] = baseList.get(i);
println( namesArray[i] );
}
}

Nested For Loops Explanation Needed

Basically, in this program, I was instructed to create an array of random numbers and then sort them smallest to largest by bubble sorting with for loops. With a bunch of trial and error, my buddy and I were able to figure it out but I just took a look back at my code and honestly, it's very hard to comprehend.. I'm not too familiar with nested loops so if someone could explain how this method is working, that would be awesome. More specifically, what does the value j and i stand for.
public void sort() {
int val = 0;
for(int i = 0; i < myArray.length; i++) {
for(int j = 1; j < (myArray.length - i); j++) {
if(myArray[j-1] > myArray[j]) {
val = myArray[j-1];
myArray[j-1] = myArray[j];
myArray[j] = val;
}
}
}
}
Any answers are greatly appreciated, thanks guys/gals!
i and j are short with no inherent meaning other than to represent the index you are at in the array. The first for loop is so that the second loop and the sorting method are repeated for as many items are in the array. The second loop does the sorting.
if(myArray[j-1] > myArray[j]) { // Checks if the index `j` in the array is less than the one before it.
val = myArray[j-1]; // Temporarily stores the greater value.
myArray[j-1] = myArray[j]; // Swap the numbers.
myArray[j] = val; // Swap the numbers.
}

How to generate random numbers with out repetition in windows phone app

here is the code for generating random numbers,but I am getting duplicate numbers,how can I overcome this.
void getnumbers()
{
Random r = new Random();
int[] trubyte = new int[4];
for (var x = 0; x < 4; ++x)
{
trubyte[x] = r.Next(1, 5);
}
b1.Content = trubyte[0];
b2.Content = trubyte[1];
b3.Content = trubyte[2];
b4.Content = trubyte[3];
}
Just get another random number if the method returns one that you already have.
void getnumbers()
{
Random r = new Random();
int num;
var trubyte = new List<int>();
for (var x = 0; x < 4; ++x)
{
do
{
num = r.Next(1, 5);
} while(trubyte.Contains(num));
trubyte[x] = num;
}
b1.Content = trubyte[0];
b2.Content = trubyte[1];
b3.Content = trubyte[2];
b4.Content = trubyte[3];
}
I'm using List instead of an array just because it offers the Contains method right away, not any other special reason.
This is not efficient if you want to generate a big list of random, unrepeated numbers (it's O(n^2) in the worst case) but for 4 numbers it's more than enough ;)
A random number generator function can return duplicates, because the output is random.
If you are using an RNG to generate numbers which must be unique, you will need to verify that they have not already been generated before using them.
Can't you use something like this [0] on Windows Mobile? It seems more practical than writing your own RNG.
0: http://msdn.microsoft.com/en-us/library/system.security.cryptography.randomnumbergenerator(v=vs.90).aspx
You have to do it by yourself, that means checking if a number was already generated.
You can do it like gjulianm said, but it is a long list of numbers, say 1000 you would be wasting a lot of time. So if you want a randomized list of 1000 you could proceed the following way
Initialize an array trubyte of size 1000 with trubyte[0]=1,trubyte[1]=2 and so on...
Initialize a variable arraysize=1000
run a loop 1000 times in which first extract a random number k btw 0-(arraysize-1). Your random number is a[k] which you can separately in a list. Now swap trubyte[k] with trubyte[arraysize]. And finally decrease the arraysize by one.
Another way, if you don't want the numbers while in the loop is just to use the changed list after the execution of loop
void getnumbers(){
Random r = new Random();
int num;
int[] trubyte = new int[1000];
int finalList[] = new int[1000]
for (int x = 0; x < 1000; ++x)
{
trubyte[x]=x+1;
}
int arraysize=1000;
for (var x = 0; x < 1000; ++x)
{
int k=r.Next(0, arraysize);
finalList[x]=trubyte[k];
trubyte[k]=trubyte[arraysize-1];
arraysize--;
}
//use the finalList
}
we can use dictionary instead of hash-set in windows phone application.
below is the code for generating distinct random numbers.
static int[] GetRandomNumbersNonrepeat(int noOfRandomNumbers, int maxValue)
{
Dictionary<int, int> randomnumbers = new Dictionary<int, int>();
while (randomnumbers.Count < maxValue)
{
Random r = new Random();
int rnum = r.Next(1, maxValue+1);
if (!randomnumbers.ContainsValue(rnum))
{
randomnumbers.Add(randomnumbers.Count + 1, rnum);
}
}
int[] rnums = randomnumbers.Values.ToArray<int>();
return rnums;
}

Most efficient way to sort parallel arrays in a restricted-feature language

The environment: I am working in a proprietary scripting language where there is no such thing as a user-defined function. I have various loops and local variables of primitive types that I can create and use.
I have two related arrays, "times" and "values". They both contain floating point values. I want to numerically sort the "times" array but have to be sure that the same operations are applied on the "values" array. What's the most efficient way I can do this without the benefit of things like recursion?
You could maintain an index table and sort the index table instead.
This way you will not have to worry about times and values being consistent.
And whenever you need a sorted value, you can lookup on the sorted index.
And if in the future you decided there was going to be a third value, the sorting code will not need any changes.
Here's a sample in C#, but it shouldn't be hard to adapt to your scripting language:
static void Main() {
var r = new Random();
// initialize random data
var index = new int[10]; // the index table
var times = new double[10]; // times
var values = new double[10]; // values
for (int i = 0; i < 10; i++) {
index[i] = i;
times[i] = r.NextDouble();
values[i] = r.NextDouble();
}
// a naive bubble sort
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
// compare time value at current index
if (times[index[i]] < times[index[j]]) {
// swap index value (times and values remain unchanged)
var temp = index[i];
index[i] = index[j];
index[j] = temp;
}
// check if the result is correct
for (int i = 0; i < 10; i++)
Console.WriteLine(times[index[i]]);
Console.ReadKey();
}
Note: I used a naive bubble sort there, watchout. In your case, an insertion sort is probably a good candidate. Since you don't want complex recursions.
Just take your favourite sorting algorithm (e.g. Quicksort or Mergesort) and use it to sort the "values" array. Whenever two values are swapped in "values", also swap the values with the same indices in the "times" array.
So basically you can take any fast sorting algorithm and modify the swap() operation so that elements in both arrays are swapped.
Take a look at the Bottom-Up mergesort at Algorithmist. It's a non-recursive way of performing a mergesort. The version presented there uses function calls, but that can be inlined easily enough.
Like martinus said, every time you change a value in one array, do the exact same thing in the parallel array.
Here's a C-like version of a stable-non-recursive mergesort that makes no function calls, and uses no recursion.
const int arrayLength = 40;
float times_array[arrayLength];
float values_array[arrayLength];
// Fill the two arrays....
// Allocate two buffers
float times_buffer[arrayLength];
float values_buffer[arrayLength];
int blockSize = 1;
while (blockSize <= arrayLength)
{
int i = 0;
while (i < arrayLength-blockSize)
{
int begin1 = i;
int end1 = begin1 + blockSize;
int begin2 = end1;
int end2 = begin2 + blockSize;
int bufferIndex = begin1;
while (begin1 < end1 && begin2 < end2)
{
if ( values_array[begin1] > times_array[begin2] )
{
times_buffer[bufferIndex] = times_array[begin2];
values_buffer[bufferIndex++] = values_array[begin2++];
}
else
{
times_buffer[bufferIndex] = times_array[begin1];
values_buffer[bufferIndex++] = values_array[begin1++];
}
}
while ( begin1 < end1 )
{
times_buffer[bufferIndex] = times_array[begin1];
values_buffer[bufferIndex++] = values_array[begin1++];
}
while ( begin2 < end2 )
{
times_buffer[bufferIndex] = times_array[begin2];
values_buffer[bufferIndex++] = values_array[begin2++];
}
for (int k = i; k < i + 2 * blockSize; ++k)
{
times_array[k] = times_buffer[k];
values_array[k] = values_buffer[k];
}
i += 2 * blockSize;
}
blockSize *= 2;
}
I wouldn't suggest writing your own sorting routine, as the sorting routines provided as part of the Java language are well optimized.
The way I'd solve this is to copy the code in the java.util.Arrays class into your own class i.e. org.mydomain.util.Arrays. And add some comments telling yourself not to use the class except when you must have the additional functionality that you're going to add. The Arrays class is quite stable so this is less, less ideal than it would seem, but it's still less than ideal. However, the methods you need to change are private, so you've no real choice.
You then want to create an interface along the lines of:
public static interface SwapHook {
void swap(int a, int b);
}
You then need to add this to the sort method you're going to use, and to every subordinate method called in the sorting procedure, which swaps elements in your primary array. You arrange for the hook to get called by your modified sorting routine, and you can then implement the SortHook interface to achieve the behaviour you want in any secondary (e.g. parallel) arrays.
HTH.

Resources