How to generate a random double value in a specific range using Kotlin? - kotlin

How do I generate a random number in a specific float range (From 51.3257 to 52.4557 for example) using Kotlin?
var xCoord = randomValue()
var yCoord = randomValue()
Do I need to make a method or do I just import something?

Here is the documentation for that: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.random/-random/index.html
I believe that it would be something like
import kotlin.random.Random
var xCoord = Random.nextDouble(51.3257, 52.4557)
var xCoord = Random.nextDouble(51.3257, 52.4557)

try this
double random = ThreadLocalRandom.current().nextDouble(51.3257, 52.4557);

If you are using kotlin do this :
var max=51.3257
var min=52.4557
var outpot= (min + Random.nextDouble() * (max - min))

Random r = new Random();
double randomValue = rangeMin + (rangeMax - rangeMin) * r.nextDouble();
Please try this. Thanks

Related

Kotlin cannot cast to Integer

var num = pref?.getInt("something", 1)
This gives me "java.lang.Long cannot be cast to java.lang.Integer, null"
However I don’t see a long here. Am I missing something?
"pref" contains Long class may be
you should try
var num = pref?.getLong(“something”,1L)

Convert Long to String in Kotlin

What am I missing here?
var timestamp = (System.currentTimeMillis() - SystemClock.elapsedRealtime())
String time = Long.toString(time) // Error: Expecting an element
value.setText("" + time)
You could use Kotlin String templates:
val time = (System.currentTimeMillis() - SystemClock.elapsedRealtime()) / 1000*60*60
value.setText("$time")
Otherwise you'd use the time.toString() directly.

How to print double value in DecimalFormat

I have a code.
Double value = 6.589715E7;
DecimalFormatSymbols symbol = new DecimalFormatSymbols(Locale.GERMANY);
symbol.setGroupingSeparator(',');
final DecimalFormat doris = new DecimalFormat("#,###000",symbol );
System.out.println(changedValue);
which displays the value like this rite now.
65,897150
is there any way out this can be displayed as.
65,9 (also rounding off to one decimal place)
This example rounds up 2 but you get the point, try this
inputValue = Math.Round(inputValue, 2);
Here I put answer in string format. you can also convert into double format.
Double value = 6.589715E7;
DecimalFormatSymbols symbol = new DecimalFormatSymbols(Locale.GERMANY);
symbol.setGroupingSeparator(',');
final DecimalFormat doris = new DecimalFormat("##,###000",symbol );
String str = String.valueOf(doris.format(value));
String formated=str.replace(".", ",").substring(0,str.indexOf(",")+2);
Log.e("Log","d result="+formated);

Kotlin: how to swap character in String

I would like to swap a string from "abcde" to "bcdea". So I wrote my code as below in Kotlin
var prevResult = "abcde"
var tmp = prevResult[0]
for (i in 0..prevResult.length - 2) {
prevResult[i] = prevResult[i+1] // Error on preveResult[i]
}
prevResult[prevResult.length-1] = tmp // Error on preveResult[prevResult.lengt-1]
It errors out as stated above comment line. What did I do wrong? How could I fix this and get what I want?
Strings in Kotlin just like in Java are immutable, so there is no string.set(index, value) (which is what string[index] = value is equivalent to).
To build a string from pieces you could use a StringBuilder, construct a CharSequence and use joinToString, operate on a plain array (char[]) or do result = result + nextCharacter (creates a new String each time -- this is the most expensive way).
Here's how you could do this with StringBuilder:
var prevResult = "abcde"
var tmp = prevResult[0]
var builder = StringBuilder()
for (i in 0..prevResult.length - 2) {
builder.append(prevResult[i+1])
}
builder.append(tmp) // Don't really need tmp, use prevResult[0] instead.
var result = builder.toString()
However, a much simpler way to achieve your goal ("bcdea" from "abcde") is to just "move" one character:
var result = prevResult.substring(1) + prevResult[0]
or using the Sequence methods:
var result = prevResult.drop(1) + prevResult.take(1)
You can use drop(1) and first() (or take(1)) to do it in one line:
val str = "abcde"
val r1 = str.drop(1) + str.first()
val r2 = str.drop(1) + str.take(1)
As to your code, Kotlin String is immutable and you cannot modify its characters. To achieve what you want, you can convert a String to CharArray, modify it and then make a new String of it:
val r1 = str.toCharArray().let {
for (i in 0..it.lastIndex - 1)
it[i] = it[i+1]
it[it.lastIndex] = str[0] // str is unchanged
String(it)
}
(let is used for conciseness to avoid creating more variables)
Also, you can write a more general version of this operation as an extension function for String:
fun String.rotate(n: Int) = drop(n % length) + take(n % length)
Usage:
val str = "abcde"
val r1 = str.rotate(1)
Simpler solution: Just use toMutableList() to create a MutableList of Char and then join it all together with joinToString.
Example:
Given a String input, we want to exchange characters at positions posA and posB:
val chars = input.toMutableList()
val temp = chars[posA]
chars[posA] = chars[posB]
chars[posB] = temp
return chars.joinToString(separator = "")
Since Strings are immutable, you will have to copy the source string into an array, make changes to the array, then create a new string from the modified array. Look into:
getChars() to copy the string chars into an array.
Perform your algorithm on that array, making changes to it as needed.
Convert the modified array back into a String with String(char[]).

split function to change order

i used a methode to get treepath i get it like this
[dc=example,dc=com,ou=Usres] and i need to make it look like this
ou=Usres,dc=example,dc=com
so i tried this methode to change the order
public static String changeString(String old)
{
old = old.replace('[', ' ');
old = old.replace(']', ' ');
old.trim();
String array[] = old.split(",");
String result = "";
for (int i = 1; i <= array.length; i++) {
if(i != 1)
result +=","+ array[array.length-i];
else
result += array[array.length-i];
}
but i get the like this ou=Usres,dc=com,dc=example
how can i do to change only the position of ou=users
If you are using Java, I would suggest you use the UnboundID SDK. Using the DN class, you can break down the items with public RDN[] getRDNs(), which returns a RDN[]
Then you could simply reorder the RDN[] and then create the new DN with DN(RDN... rdns).