mercredi 1 juillet 2015

Java Rotate an Array

I have the following problem to test:

Rotate an array of n elements to the right by k steps. For instance, with n = 5 and k = 2, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. How many different ways do you know to solve this problem?

My solution in intermediate array: With Space is O(n) and time is O(n), I can create a new array and then copy elements to the new array. Then change the original array by using System.arraycopy().

public void rotate(int[] nums, int k) {
    if(k > nums.length) 
        k=k%nums.length;

    int[] result = new int[nums.length];

    for(int i=0; i < k; i++){
        result[i] = nums[nums.length-k+i];
    }

    int j=0;
    for(int i=k; i<nums.length; i++){
        result[i] = nums[j];
        j++;
    }

    System.arraycopy( result, 0, nums, 0, nums.length );
}

But there is better way we can do it with bubble rotate(like bubble sort) in O(1) space ?

Android Media Player Stuttering with CountDownTimer

I'm trying to make an app to teach someone how to count music. The media player is initialize to a 30 second sound clip of a persistent A note. I am using a countdown timer to tell my media player when to pause and play. The code below causes the first and last second of audio to stutter.

MediaPlayer myMediaPlayer = MediaPlayer.create(MusicCounting.this, R.raw.a_note);
CountDownTimer time = new CountDownTimer(4000,500) {
    @Override
    public void onTick(long millisUntilFinished) {
        if(myMediaPlayer.isPlaying()) {
            myMediaPlayer.pause();
        } else {
            myMediaPlayer.start();
        }
    }

    @Override
    public void onFinish() {
        myMediaPlayer.pause();
        myMediaPlayer.seekTo(0);
    }
};

time.start();

This code is for quarter notes and my eighth notes code looks identical except the second parameter for the countdown timer is 250. Any suggestions would be greatly appreciated. Thanks :)

mvn jetty:run not reflecting changes when run inside docker

I have a simple Tic-tac-toe Java web app http://ift.tt/1CIOMRA It is a Maven project. It uses Jetty to run the web app by doing mvn jetty:run While it is running locally, I can easily modify a JavaScript file and see the changes immediately when I refresh the browser. But, when I run it via Docker where I am mounting the source directory, similar change doesn't get reflected.

Note: I am mounting the source directory in docker-compose.yml file. And I see the change reflected in the file but jetty doesn't pick up the change.

Please Note: It needs JDK 7

To test on localhost:

  mvn clean install
  mvn jetty:run
  Open localhost:8080 to see the app.
  Add an alert(1); in `doInit` function in this JavaScript http://ift.tt/1C8q2aX
  Refresh the browser and you'll see an alert dialog

To test on Docker (using Docker compose):

    docker-compose up
    Add an alert(1); in `doInit` function in [this JavaScript][3]    
    ...Refresh browser, but the change is not reflected

What am I missing?

JNI: Bitmap from unsigned char* always null

I would like to pass an image (via jni) from C++ to an android application. I am starting from an unsigned char* array. This array is not corrupted whatsoever; I am even able to save it into a ppm file and display it properly on my laptop.

Then, I convert it to a jByteArray by using this function:

jbyteArray imgByte=as_byte_array(env,imgRaw,img.getRawImageSize());
...
jbyteArray as_byte_array(JNIEnv *env, unsigned char* buf, int len) {
    jbyteArray array = env->NewByteArray (len);
    env->SetByteArrayRegion (array, 0, len, reinterpret_cast<jbyte*>(buf));
    return array;
}

Afterward, I send this jByteArray to the java side. This variable has been properly populated, as I can see by printing its hex values on LogCat:

07-01 18:02:45.941    7017-8238/com.myapp.myapp W/C++ side﹕  798a95798b9677889371838d6b7d8664757e5d6e7860717b5e...
07-01 18:02:46.941    7017-8238/com.myapp.myapp W/Java side﹕ 798a95798b9677889371838d6b7d8664757e5d6e7860717b5e...

The final step would be to show it on an ImageView. To this end, I do the following code (taken from another question on SO):

public void setImageViewWithByteArray(final ImageView view, byte[] data) {
    final Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (bitmap==null) {
                Log.e(TAG,"Bitmap is NULL!");
                view.setImageResource(R.drawable.abc_btn_radio_material);
            }
            else {
                view.setImageBitmap(bitmap);
            }
        }
    });
}

but the bitmap variable is always null. What am I doing wrong? Is there a way to debug decodeByteArray?

Decrypt with Rijndael from c# to Java

I have this source code in c# and I need to translate this to Java:

    private byte[] DecryptAES(byte[] encrypted, byte[] key, byte[] IV)
    {
        RijndaelManaged myRijndael = new RijndaelManaged();
        byte[] fromEncrypt;
        //byte[] encrypted = Encoding.Default.GetBytes(texto);

        //Get a decryptor that uses the same key and IV as the encryptor.
        ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);

        //Now decrypt the previously encrypted message using the decryptor
        // obtained in the above step.
        MemoryStream msDecrypt = new MemoryStream(encrypted);
        CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

        fromEncrypt = new byte[encrypted.Length];

        //Read the data out of the crypto stream.
        csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

        //Convert the byte array back into a string.
        //roundtrip = Encoding.Default.GetString(fromEncrypt);

        return fromEncrypt;
    }

Could somebody help me please?

How to convert from Matrix to double Java (Java)

I have an object Matrix, where I stored a double[][] array. I want to return the values of the method Matrix.inverse().

How can I pass values from a Matrix object to a double[][] array?

double K[][] = {{1,5,3,4} , {1,10,4,3} , {1,40,232,4} , {32,434,23,5}};
Matrix GetInverse = new Matrix(K);

double returnValues[][] = GetInverse; // ---?----

The sum of all the multiples of 3 or 5 below N. Project Euler

So I'm doing the Project Euler challenge and I'm stuck at the first one, I'm using Java as pl. for example if we have to list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. We have to find the sum of all the multiples of 3 or 5 below N.

My code works on Eclipse but I get "Nice try, but you did not pass this test case." with stdout : No Response and when I submit the code I get Wrong Answer on all test cases, here's the code:

public class Solution {
    public static void main(String[] args) {
        for (int j = 0; j < args.length; j++) {
            int N = Integer.parseInt(args[j]);
            if (Somme(N) != 0) {
                System.out.println(Somme(N));
            }
        }
    }

    public static int Somme(int Nn) {
        int s = 0;
        for (int i = 0; i < Nn; i++) {
            if (((i % 3) == 0) || ((i % 5) == 0)
                && !(((i % 3) == 0) && ((i % 5) == 0))) {
                s = s + i;
            }
        }
        return (s);
    }
}

UPDATE : So, I looked more and it turns out that this is how it's supposed to be done:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Solution{
public static void main(String[] args) throws IOException {


    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String line = br.readLine();
    int Nbr = Integer.parseInt(line);


        for(int j=0; j<Nbr;j++)
        {
            BufferedReader br2 = new BufferedReader(new   InputStreamReader(System.in));
            String line2 = br2.readLine();
            String[] numbers = new String[Nbr];
            numbers[j]= line2;
            System.out.println(Somme(Long.parseLong(numbers[j])));
        }

        }


public static long Somme(long Nn) {
    long s = 0;
    for (int i = 0; i < Nn; i++) {
        if (((i % 3) == 0) || ((i % 5) == 0)) {
            s = s + i;
        }
    }
    return (s);
}

}

Now the only problem left is that I want it to be able to read ALL the numbers THEN display the sum, for now it reads one number and display the sum right after it, any ideas?