I try to run this, but it is very slow. Takes ages till it processes and finishes the calculating. Is there anyways I could improve it or make it work faster and more efficiently?
int n = 25;
int len = (int) Math.pow(2, n);
String[][] BinaryNumbers = new String[len][];
int[] DummyArray = new int[n];
int[][] BinaryNumbersInt = new int[len][];
for (int count = 0; count < len; count++) {
BinaryNumbers[count] = String.format("%" + n + "s",
Integer.toBinaryString(count)).replace((" "), ("0"))
.split("");
for (int i = 0; i < n; i++) {
DummyArray[i] = Integer.parseInt(BinaryNumbers[count][i]);
}
BinaryNumbersInt[count] = Arrays.copyOf(DummyArray, DummyArray.length);
}
thanks!
You're doing a lot of useless string manipulation. Try something like this:
for (int count = 0; count < len; count++) {
int[] DummyArray = new int[n];
int x = count;
for (int i = 0; i < n; i++) {
DummyArray[n-i-1] = x & 1;
x >>= 1;
}
BinaryNumbersInt[count] = DummyArray;
}
Related
I'm trying to create a 2D int array of numbers that are the product of 2 via user input defining the length of the rows and columns, as the one below:
1 2 4 8
2 4 8 16
4 8 16 32
8 16 32 64
I've only got up to here, and cannot figure out how to make the matrix to start from 1 and to look like the one above. I'd appreciate your help on this one!
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
int[][] matrix = new int[n][n];
matrix[0][0] = 1;
int temp = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = temp * 2;
temp *= 2;
}
}
System.out.println(Arrays.deepToString(matrix));
I'd say that each element of the matrix would be:
matrix[i][j] = (int) Math.pow(2, i+j) ;
So, your loop would look like this:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = (int) Math.pow(2, i+j);
}
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
int[][] matrix = new int[n][n];
matrix[0][0] = 1;
int temp = 1;
for (int i = 0; i < n; i++) {
temp = (int)Math.pow(2, i);
for (int j = 0; j < n; j++) {
matrix[i][j] = temp;
temp *= 2;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j]+" ");
}
System.out.println();
}
}
public class Sort {
public static void main(String[] args) {
//fill the array with random numbers
int[] unsorted = new int[100];
for(int i = 0; i < 100; i++) {
unsorted[i] = (int) (Math.random() * 100);
}
System.out.println("Here are the unsorted numbers:");
for(int i = 0; i < 100; i++) {
System.out.print(unsorted[i] + " ");
}
System.out.println();
int[] sorted = new int[100];
for(int i = 0; i < 100; i++) {
int hi = -1;
int hiIndex = -1;
for(int j = 0; j < 100; j++) {
if(unsorted[j] > hi) {
hi = unsorted[j];
hiIndex = j;
}
}
sorted[i] = hi;
unsorted[hiIndex] = -1;
}
System.out.println("Here are the sorted numbers: ");
for(int i = 0; i < 100; i++) {
System.out.print(sorted[i] + " ");
}
System.out.println();
}
}
So this is in descending order but I want to reverse it.
I tried changing the if(unsorted[j] > hi) {
to a if(unsorted[j] < hi) {
[edit:changed greater than to less than, both were same]
Okay, you want the numbers to be in ascending order. So for descending, you assume that compared number would be -1 and all other number must be grater than this -1, now instead of -1 use the maximum value a number could be. Assign Integer.MAX_VALUE where you were assigning -1. So change your code like this:
int[] sorted = new int[100];
for(int i = 0; i < 100; i++) {
int hi = Integer.MAX_VALUE;
int hiIndex = i;
for(int j = 0; j < 100; j++) {
if(unsorted[j] < hi) {
hi = unsorted[j];
hiIndex = j;
}
}
sorted[i] = hi;
unsorted[hiIndex] = Integer.MAX_VALUE;
Creating a custom matrix class I implemented multiplication with ikj algorithm and now I'm trying to optimize it. The problem is that the version that should work better is about 5 times slower and I can't understand why.
This is the Matrix class with the "basic" algorithm:
class Matrix {
private double[][] m; // matrix
private int rows;
private int cols;
// other stuff...
// does some checks and returns requested matrix value
// I know this will slow down computation, but it's not the relevant part
public double get(int row, int col) {
if (row >= rows || col >= cols)
throw new IndexOutOfBoundsException(); // to catch block
else
return m[startRow + row][startCol + col];
}
public Matrix multiply(Matrix other) {
int n = rows;
int m = cols;
int p = other.cols;
double[][] prod = new double[n][p];
for (int i = 0; i < n; i++)
for (int k = 0; k < m; k++)
for (int j = 0; j < p; j++)
prod[i][j] += get(i,k) * other.get(k,j);
return new Matrix(prod);
}
}
And this is the modified algorithm:
public Matrix multiplyOpt(Matrix other) {
int n = rows;
int m = cols;
int p = other.cols;
double[][] prod = new double[n][p];
for (int i = 0; i < n; i++) {
for (int k = 0; k < m; k++) {
double aik = get(i,k);
for (int j = 0; j < p; j++) {
prod[i][j] += aik * other.get(k,j);
}
}
}
return new Matrix(prod);
}
My though was that moving that get call outside the loop it will be called n x m times instead of n x m x p.
These are the results of a random matrix multiplication (exception is never thrown):
multiply time = 0.599s
multiplyOpt time = 3.041s
Why this change makes it slower and not faster?
EDIT
Timings are obtained with:
double[][] m1 = new double[1000][750];
double[][] m2 = new double[750][1250];
for (int i = 0; i < m1.length; i++)
for (int j = 0; j < m1[0].length; j++)
m1[i][j] = new Double(Math.random());
for (int i = 0; i < m2.length; i++)
for (int j = 0; j < m2[0].length; j++)
m2[i][j] = new Double(Math.random());
Matrix a = new Matrix(m1);
Matrix b = new Matrix(m2);
long start = System.currentTimeMillis();
Matrix c = a.multiply(b);
long stop = System.currentTimeMillis();
double time = (stop - start) / 1000.0;
System.out.println("multiply time = "+time);
start = System.currentTimeMillis();
c = a.multiplyOpt(b);
stop = System.currentTimeMillis();
time = (stop - start) / 1000.0;
System.out.println("multiplyOpt time = "+time);
package msj;
import mpi.*;
public class HelloWorld2 {
public static final int N = 10;
public static void main(String[] args) {
MPI.Init(args);
long startTime = System.currentTimeMillis();
int rank = MPI.COMM_WORLD.Rank();
int size = MPI.COMM_WORLD.Size();
int tag = 10, peer = (rank==0) ? 1:0;
if(rank == 0) {
double [][] a = new double [N][N];
for(int i = 0; i < N; i++)
for(int j = 0; j < N; j++)
a[i][j] = 10.0;
Object[] sendObjectArray = new Object[1];
sendObjectArray[0] = (Object) a;
MPI.COMM_WORLD.Send(sendObjectArray, 0, 1, MPI.OBJECT, peer, tag);
} else if(rank == 1){
double [][] b = new double [N][N];
for(int i = 0; i < N; i++)
for(int j = 0; j < N; i++)
b[i][j] = 0;
Object[] recvObjectArray = new Object[1];
MPI.COMM_WORLD.Recv(recvObjectArray, 0, 1, MPI.OBJECT, peer, tag);
b = (double[][]) recvObjectArray[0];
for(int i = 0; i < 4; i++){
for(int j = 0; j < N; i++)
//long endTime = System.currentTimeMillis();
//long endTime = System.currentTimeMillis();
System.out.print(b[i][j]+"\t");
System.out.println("\n");
//System.out.println("Calculated in " +
// (endTime - startTime) + " milliseconds");
}
}
MPI.Finalize() ;
}
}
I couldn't run this program.
I get an error when I do not write an int before the variables in the for loop: for( int i = 0; i < N; i++).
Is the problem related to this ?
Do you have any idea, There is no problem in the code
You get "java.lang.ArrayIndexOutOfBoundsException: 10" if "rank ==1" becomes true. This is because in your nested for-loop you wrote
"for(int j = 0; j < N; i++)" instead of
"for(int j = 0; j < N; j++)".
You increment i twice. This Exceptions stops your method.
Mr.
Copy and Mr Paste send Greetings. ;o)
I am trying to solve question at Reverse Game
When I submit my code, in some of the testcases it is getting timeout.
I think problem may be in reverseSubArray() method but I am not sure how to improve performance here.
Following is my code:
public class ReverseGame
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int testCases = Integer.parseInt(scanner.nextLine());
int[] numberOFBalls = new int[testCases];
int[] ballNumberArray = new int[testCases];
for (int i = 0; i < testCases; i++)
{
numberOFBalls[i] = scanner.nextInt();
ballNumberArray[i] = scanner.nextInt();
}
for (int i = 0; i < testCases; i++)
{
process(numberOFBalls[i], ballNumberArray[i]);
}
scanner.close();
}
private static void process(int totalNumberOFBalls, int ballNumber)
{
int[] ballsArray = new int[totalNumberOFBalls];
int maximumNumberOnBall = totalNumberOFBalls - 1; // This is because
// balls are numbered
// from 0.
// As the first step is to reverse the Balls arrangement, So insert into
// ballsArray in descending order of index.
for (int i = 0; i < totalNumberOFBalls; i++)
ballsArray[i] = maximumNumberOnBall--;
for (int i = 1; i < totalNumberOFBalls; i++)
{
ballsArray = reverseSubArray(ballsArray, i);
}
int position = findPosition(ballsArray, ballNumber);
System.out.println(position);
}
private static int[] reverseSubArray(int[] a, int fromIndex)
{
int temp = 0, counter = 1;
int midIndex = (a.length - fromIndex) / 2;
for (int i = fromIndex; i < fromIndex + midIndex; i++)
{
temp = a[a.length - (counter)];
a[a.length - (counter)] = a[i];
a[i] = temp;
counter++;
}
/*
* System.out.println(); for (int i = 0; i < a.length; i++)
* System.out.print(a[i] + " ");
*/
return a;
}
private static int findPosition(int[] ballsArray, int ballNumber)
{
for (int i = 0; i < ballsArray.length; i++)
{
if (ballsArray[i] == ballNumber)
return i;
}
return 0;
}
}
The time complexity of your solution is O(n ^ 2). It is too slow for n = 10 ^ 5. So you need to use a better algorithm. Here is simple linear solution which uses the fact that we do not need to know the positions of all balls(we need only the k-th):
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int testsCount = in.nextInt();
for (int t = 0; t < testsCount; t++) {
int n = in.nextInt();
int k = in.nextInt();
// Simulates all rotations,
// but keeps track only of the k-th ball.
// It does not matter what happens to the others.
for (int i = 0; i < n; i++)
if (k >= i)
k = i + n - 1 - k;
out.println(k);
}
out.flush();
}
}
This solution has an O(n) time complexity and easily passes all test cases.
It is actually possible to find the positions of all balls in linear time, but it is not required here.