Translating Java to X10 - java

I'm translating a Java program into X10 and have run into a couple problems that I was wondering if anyone could help me translate.
Here's one Java segment that I'm trying to translate:
ArrayList<Posting>[] list = new ArrayList[this.V];
for (int k=0; k<this.V; ++k) {
list[k] = new ArrayList<Posting>();
}
And here's what I've done in X10:
var list:ArrayList[Posting]=new ArrayList[Posting](this.V);
for (var k:int=0; k<this.V; ++k) {
list(k)=new ArrayList[Posting]();
}
The line that's generating a mess of error statements is this:
list(k)=new ArrayList[Posting]();
Any suggestions and maybe an explanation on what I'm doing wrong?

Agreed with trutheality. You need to define list as something like Rail[ArrayList[Posting]] :
var list:Rail[ArrayList[Posting]]=new Rail[ArrayList[Posting]](this.V);
Also, as X10 supports type inference for immutable variables, it's often better to use val instead of var and omit the type declaration altogether:
val list = new Rail[ArrayList[Posting]](this.V);

Here is code that should work for you:
val list = new Rail[ArrayList[Posting]](this.V);
for (k in 1..(this.V)) {
list(k)=new ArrayList[Posting]();
}
And you can also do
val list = new Rail[ArrayList[Posting]](this.V, (Long)=>new ArrayList[Temp]());
i.e. use a single statement to create an initialized array.

Related

List of regex results instead of first result in Kotlin

Using the following code, I can set a couple variables to my matches. I want to do the same thing, but populate a map of all instances of these results. I'm struggling and could use help.
val (dice, level) = Regex("""([0-9]*d[0-9]*) at ([0-9]*)""").matchEntire(text)?.destructured!!
This code works for one instance, none of my attempts at matching multiple are working.
Your solution is short and readable. Here are a few options the one you use is largely a matter of preference. You can get a Map directly by using the associate method as follows.
val diceLevels = levelMatches.associate { matched ->
val (diceTwo,levelTwo) = matched.destructured
(levelTwo to diceTwo)
}
Note: This creates an immutable map. If you want a MutableMap, you can use associateTo.
If you want to be concise, you can simplify out the destructuring to local variables and index the groups directly.
val diceLevels = levelMatches.associate {
(it.groupValues[2] to it.groupValues[1])
}
Or, using let, you can also avoid needing to declare levelMatches as a local variable if it isn't used elsewhere --
val diceLevels = Regex("([0-9]+d[0-9]+) at ([0-9]+)")
.findAll(text)
.let { levelMatches ->
levelMatches.associate {
(it.groupValues[2] to it.groupValues[1])
}
}
I realized this was no where near as complicated as I was making it. Here was my solution. Is there something more elegant?
val levelMatches = Regex("([0-9]+d[0-9]+) at ([0-9]+)").findAll(text)
levelMatches.forEach { matched ->
val (diceTwo,levelTwo) = matched.destructured
diceLevels[levelTwo] = diceTwo
}

How can I create an array of objects in Kotlin without initialization and a specific number of elements?

I want to create an Array of objects with a specific number of elements in Kotlin, the problem is I don't now the current values for initialization of every object in the declaration, I tried:
var miArreglo = Array<Medico>(20, {null})
in Java, I have this and is exactly what I want, but i need it in Kotlin. :
Medico[] medicos = new Medico[20];
for(int i = 0 ; i < medicos.length; i++){
medicos[i] = new Medico();
}
What would be the Kotlink equivalent of the above Java code?
Also, I tried with:
var misDoctores = arrayOfNulls<medic>(20)
for(i in misDoctores ){
i = medic()
}
But I Android Studio show me the message: "Val cannot be reassigned"
The Kotlin equivalent of that could would be this:
val miArreglo = Array(20) { Medico() }
But I would strongly advice you to using Lists in Kotlin because they are way more flexible. In your case the List would not need to be mutable and thus I would advice something like this:
val miArreglo = List(20) { Medico() }
The two snippets above can be easily explained. The first parameter is obviously the Array or List size as in Java and the second is a lambda function, which is the init { ... } function. The init { ... } function can consist of some kind of operation and the last value will always be the return type and the returned value, i.e. in this case a Medico object.
I also chose to use a val instead of a var because List's and Array's should not be reassigned. If you want to edit your List, please use a MutableList instead.
val miArreglo = MutableList(20) { Medico() }
You can edit this list then, e.g.:
miArreglo.add(Medico())
If you want list of nullable objects, we can do something like this
val fragment : Array<Fragment?> = Array(4) { null }


Generate a Weibull distributed value in Java

I am new to Java and I would like to create a Weibull distributed random value.
I tried using the the WeibullGen class from the umontreal.iro.lecuyer.randvar package but got kind of stuck.
I tried something like the following but it obviously doesn't work.
for(int i=0;i<5;i++){
int result = WeibullGen.nextDouble(RandomStream s ,1.0,1.0,1.0);
if(result>0) System.out.println(result);
}
My problem is that I don't know how to create a stream. I'm pretty sure that it can't be that hard, but I'm really struggling to find my way.
It is not a good idea to create a new stream for each generated random number. It is better to use only 1 stream like this:
RandomStream stream = new MRG32k3a();
for(int i=0;i<5;i++) {
int result = WeibullGen.nextDouble(stream, alp, lam,1.0);
System.out.println(result);
}
To create a Stream inline, you would do this:
for(int i=0;i<5;i++){
int result = WeibullGen.nextDouble(new RandomStream(),1.0,1.0,1.0);
if(result>0) System.out.println(result);
}
In Java, you have to instantiate objects with the new keyword.

Java code translation of Python array-splitting code

Can someone please give the Java equivalent of the below python (which slices a given array into given parts) which was originally written by ChristopheD here:
def split_list(alist, wanted_parts=1):
length = len(alist)
return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts]
for i in range(wanted_parts) ]
I don't know any python but can really use the above code in my Java app. Thanks
Maybe something like this:
List<List<T>> splitList(List<T> alist, int wantedParts) {
ArrayList<List<T>> result = new ArrayList<List<T>>();
int length = alist.length;
for (int i = 0; i < wantedParts; i++) {
result.append(alist.subList(i*length/wantedParts,
(i+1)*length/wantedParts));
}
return result;
}
If your alist will be structurally modified later in any way, you will have to make a copy of the sublist created by the subList method within the code, otherwise the results will be unpredictable.
Don't reinvent the wheel, the google collections api has a function called partition which does precisely that

Java SWT interop with COM - putting a float[] into a Variant?

In my Java SWT application I'm hosting an 3rd party ActiveX control. I'm using OleClientSite to do this.
// Ah, this works. :-)
OleAutomation comObject = new OleAutomation(...);
There are 2 easy little functions I want to call from Java. Here are the COM function definitions:
[id(5)]
void easyFoo([in] int blah);
[id(20)]
void problemFoo([in] VARIANT floatArray);
Easy, right? Here's my pretend code:
// Ah, this works. :-)
OleAutomation comObject = new OleAutomation("Some3rdPartyControlHere");
// Call easyFoo(42). This works. :-)
int easyFooId = 5;
comObject.invoke(easyFooId, new Variant[] { new Variant(42) });
// Call problemFoo(new float[] { 4.2, 7.0 }). This doesn't work. :-(
int problemFooId = 20;
comObject.invoke(problemFooId, [ACK! What goes here?]);
The problem is on the last line: how do I pass a float array to the 3rd party COM object? HELP!
You need to pass a float array. In COM terms, that mean s a VARIANT with vt set to VT_R4|VT_ARRAY. An array of variants may not work as the document does not say it can accept an array of variants (VT_VARIANT |VT_ARRAY). In java you should be able to use float[] as the parameter type. If not you can always call the Windows API to construct a safe array of desired type.
I suspect there is no constructor that takes a float[] because VARIANTs don't have a float array member.
I think what you need to do to make this work is pack up your floats into a SAFEARRAY (ick; and I have no idea how to create one in Java).
Alternatively, you may try serializing your array to raw bits and use the BYTE* member of the VARIANT struct, and pass an int that has the count of bytes so you can accurately de-serialize on the other side (and I assume this is all in the same process and thread, otherwise it gets harder).
[id(20)]
void problemFoo([in] VARIANT bytes /* VT_BYREF|VT_UI1 */, [in] VARIANT byteCount /* VT_UI4 */);
What's wrong with creating an array of Variant and filling it with your float array values?
Variant[] problemFooArgs = new Variant[myFloats.length];
for( int i=0; i<myFloats.length; i++)
{
problemFooArgs[i] = new Variant(myFloats[i]);
}
If it really needs only one argument (an array of float), you could try one level of indirection:
Variant[] problemFooArgs = new Variant[1];
Variant[] myFooArgs = new Variant[1];
for( int i=0; i<myFloats.length; i++)
{
myFooArgs [i] = new Variant(myFloats[i]);
}
problemFooArgs[0] = myFooArgs;
If the simple approach does not work and you do need a SAFEARRAY, you could try and create one after the example "Reading and writing to a SAFEARRAY", using the constants of org.eclipse.swt.internal.win32.OS. But it seems for char[] only.
Other source of inspiration for creating the relevant SAFEARRAY:
class SafeArray of project com4j (and its associated class, like Variant)

Categories