Sorting an Array of Objects by their Int - arrays

So I tried implementing my Quicksort for sorting an array of Edges by their weight which is in int for my Kruskal's algorithm implementation. Is there a built function in javascript for sorting an array of objects by their properties? In this case by their weight. From smallest weight to the largest.
Here is my edge class.
class Edge
{
private int u;
private int v;
private int weight;
public Edge(int i, int i2, int w)
{
u = i;
v = i2;
weight = w;
}
public int getU() {
return u;
}
public int getV() {
return v;
}
public int getWeight() {
return weight;
}
}
Kruskal's code
class MSTKruskal
{
Edge[] mst(int[][] G)
{
Edge A[] = new Edge[G.length - 1];
Forest aForest = new Forest(G.length);
Edge E[] = new Edge[(G.length * G.length - G.length)/2];
int i3 = 0;
for (int i = 0; i < G.length; i++)
{
for(int i2 = i+1; i2 < G.length; i2++)
{
Edge anEdge = new Edge(i, i2, G[i][i2]);
E[i3] = anEdge;
i3++;
}
}
print(E);
//QuickSort(E, 0, E.length);
print(E);
int index = 0;
for (int i = 0; i < E.length; i++)
{
if (aForest.findSet(E[i].getU()) != aForest.findSet(E[i].getV()))
{
A[index] = E[i];
index++;
aForest.union(E[i].getU(), E[i].getV());
}
}
aForest.printA();
return A;
}

In javascript you can pass function as parameter to sort method, this function should take 2 parameters (a and b), and return:
0, if a == b
<0, if a < b
>0, if a > b
In your case it should be something like:
var a=[15,7,100,50];
a.sort(function(a,b){return a.weight-b.weight;});
So you can easily sort by any arrays contents' properties or even more complex criteria.

Related

number of subarray with average greater than average of the rest of the elements of array

We are given a array of size < 2000
and A[i]< 10^6.I know the bruteforce approach.Can we do better i.e in linear time ?
I am checking each subarray and comparing its average with the other elements.
public class FindingSubArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
ArrayList<Integer> a = new ArrayList<>();
ArrayList<Integer> b = new ArrayList<>();
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
double avg1 = getAverage(i,j,arr);
double avg2 = getAverageOfRest(i,j,arr);
//System.out.println(avg1+" "+avg2);
if(avg1 > avg2) {
a.add(i+1);
b.add(j+1);
}
}
}
System.out.println(a.size());
for(int i=0;i<a.size();i++){
System.out.println(a.get(i)+" "+b.get(i));
}
}
private static double getAverageOfRest(int i, int j, int[] arr) {
double result = 0;
int count = 0;
for(int k=0;k<i;k++) {
result += arr[k] ;
count ++;
}
for(int k=j+1;k<arr.length;k++) {
result += arr[k] ;
count ++;
}
if(count > 0)
return result/count;
else
return 0;
}
private static double getAverage(int i, int j, int[] arr) {
double result = 0;
int count = 0;
for (int k = i; k <= j; k++) {
result += arr[k] ;
count ++;
}
if(count > 0)
return result/count;
else
return 0;
}
}

I need to determine if a random number is unique

I need to write a function that receives the number generated in fillArray and determine if it has already been generated. I need to return a true or false thus determining if the random number must be put into the array.
Here's what I am working on. Thanks for any help. I've searched for anything similar but unfortunately cannot find anything.
public class RandomGenerator {
int Arr[] = new int[6];
int size;
public void fillArray() {
int randNum = (int) (Math.random() * 49) + 1;
for (int i = 0; i < size; i++) {
Arr[i] = randNum;
alreadyThere(randNum);
}
size++;
}
public int alreadyThere(int randNum) {
int find = randNum;
boolean found = false;
int i = 0;
while (!found && i < size) {
if (Arr[i] == find) {
found = true;
}
i++;
}
if (!found) {
}
return randNum;
}

exception in thread main java.lang.arrayindexoutofboundsexception 1

well i have to make a java program which determinate if a given number is capicua(131,12121,13431) the same number from last to initial digit. but it gives me the error, in the line 23 (while(i>=0).....) the question is how can i call the array into thath while. pls help me im really sad :c. Here is the code:
public class Capi {
/**
*
**/
public static int num(int a) { // counting digits from the number
int n = 0;
while(a>=10) { a = a/10;
n = n+1;
}
return n;
}
public static boolean det(int a, int n) {
int z = a;
double y =0;
n = n-1;
int i = 0;
int x[] = new int[n];
for(i=0; i<x.length; i++) { // saving the digits into x[i]
x[i] = a%10;
a = a/10;
}
while(i>=0) { y = x[i]*Math.pow(10,n-1); // calling the digits x[i],x[i-1] untill it gets 0
i = i - 1;
n = n -1;
}
double num1= y + a*Math.pow(10,n);
if(num1 == z) { return true; }
else { return false; }
}
}
I feel the issue is that the value of i is set to x.length, before you attempt while(i>=0). I have hence added i-- before you run the loop.
See if the following does the trick.
public class Capi {
public static int num(int a) { // counting digits from the number
int n = 0;
while(a>=10) {
a = a/10;
n = n+1;
}
return n;
}
public static boolean det(int a, int n) {
int z = a;
double y = 0;
n = n-1;
int i = 0;
int x[] = new int[n];
for(i=0; i<x.length; i++) { // saving the digits into x[i]
x[i] = a%10;
a = a/10;
}
//i is now set to x.length, thus decrement it as index runs from 0 to x.length-1
i=i-1;
while(i>=0) {
y = x[i]*Math.pow(10,n-1); // calling the digits x[i],x[i-1] untill it gets 0
i = i - 1;
n = n -1;
}
double num1= y + a*Math.pow(10,n);
if(num1 == z) {
return true;
}
else {
return false;
}
}
}

Null Pointer Exception in array passed class

So I have a project that requires a generic class that extends Number and also finds the largest and smallest value in the array, the average of all the values, and the size of the array. This seems easy enough to implement, but I have a problem before even putting the generic part of this in place, I get a runtime error of Null Pointer Exception at x.length, regardless of which method I call, always in the same place.
import java.util.Comparator;
public class test
{
public int x[];
public test(int x[])
{
}
public void setx(int newx[])
{
x = newx;
}
public int[] getx()
{
return x;
}
public int findSmallest()
{
int i = 0;
int temp = x[i];
while (i < x.length)
{
i++;
if(x[i] < temp)
{
temp = x[i];
}
else
{
}
}
return temp;
}
public int findLargest()
{
int i = 0;
int temp = x[i];
while (i < x.length)
{
i++;
if(x[i] > temp)
{
temp = x[i];
}
else
{
}
}
return temp;
}
public double findMean()
{
int i = 0;
double sum = 0.0;
double avg = 0.0;
while (i < x.length)
{
sum += x[i];
i++;
}
avg = sum / x.length;
return avg;
}
public int findTotal()
{
int i = x.length;
return i;
}
public static void main (String args[])
{
int[] ia = {1, 2, 3, 4, 5, 6};
test intTest = new test(ia);
System.out.println(intTest.findTotal());
}
}
Any help on how to fix this would be amazing.
You forgot use the setx method in the constructor. You're passing the integer array to constructor but not actually initializing the integer array inside the class. You can do this by calling the setx method in your constructor and passing the integer array x to setx method.
Hope this helps.

How can I store the results of permutation in a 2D array?

I need help writing this code to get the permutation of numbers.
I need to store all the permutations in a 2D array.
After output of the permutation, I then need to process 30 percent of the permutations in one method an the the rest in another method.
My code:
public class Permutation {
* #param args the command line arguments
*/
void printArray(int []a) {
for (int i = 0; i< a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.println("");
}
void permute(int []a,int k ) {
if(k==a.length)
printArray(a);
else
for (int i = k; i< a.length; i++) {
int temp=a[k];
a[k]=a[i];
a[i]=temp;
permute(a,k+1);
temp=a[k];
a[k]=a[i];
a[i]=temp;
}
}
public static void main(String[] args) {
Permutation p=new Permutation();
int a[]={1,2,3,4,5,6};
p.permute(a, 2);
}
}
This is my solution instead of a 2d array use an ArrayList
import java.util.ArrayList;
import java.util.Arrays;
/**
*
* #author David
*/
public class Permutations {
public static int[] a;
public final int SIZE = 6;
public final int NUMPERM;
public final ArrayList<int[]> newlist;
public Permutations()
{
a = new int[SIZE];
for(int x = 0; x < SIZE; x++)
a[x] = x+1;
NUMPERM = Factorial(a.length);
newlist = new ArrayList<>(NUMPERM);
}
public void permute()
{
permutation(a,0,a.length);
}
private void permutation(int array[],int start, int end)
{
newlist.add(saveArray(array));
if (start<end)
{
int i,j;
for(i=end-2; i>=start; i--)
{
for(j=i+1; j<end; j++)
{
Swap(array,i,j);
permutation(array,i+1,end);
}
Rotate_Left(array,i,end);
}
}
}
private int[] saveArray(int[] array)
{
int[] newarray = new int[array.length];
System.arraycopy(array, 0, newarray, 0, array.length);
return newarray;
}
public void Print()
{ //just to prove the list works
System.out.println("the current size of newlist is : " + newlist.size());
int[] array = new int[a.length];
for(int x = 0; x < newlist.size(); x++)
{
array = newlist.get(x);
System.out.println(Arrays.toString(array));
}
}
private void Swap(int array[],int i,int j)
{
int t;
t = array[i];
array[i] = array[j];
array[j] = t;
}
private void Rotate_Left(int array[],int start,int end)
{
int tmp = array[start];
for (int i=start; i < end-1; i++)
{
array[i] = array[i+1];
}
array[end-1] = tmp;
}
private int Factorial(int a)
{
int fact = 1;
for(int x = a; x > 0; x++)
fact *= a;
return fact;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Permutations newperm = new Permutations();
newperm.permute();
newperm.Print();
}
}
then all you have to do is send the list to the other functions and only use what you need from it.

Resources