I'm trying to write a formula where the shorter the distance, the more points you get, the farther the distance, the less points
fun raiting(distance: Float): Int {
var rating = 1000
var maxDistance = 11750F
rating = if (distance > maxDistance) {
0
} else{
..
}
return rating
}
The question is how to write such a formula? Or tell me which formula to use
You can simply calculate percentage of distance from max distance where 0 means 100% and maxDistance means 0%:
fun raiting(distance: Float): Int {
var maxDistance = 11750F
rating = 100 - (distance * 100 / maxDistance)
return toInt(rating)
}
Related
Can someone explain why the below code produces [2,3,5,6,7,8,9,10,11,12]?
I know it has something to do with filter function is deferred to the last element but I don't see the picture. It would even be better if you can visualise it. Thank you so much.
val primes: Sequence<Int> = sequence {
var numbers = generateSequence(2) { it + 1 }
var prime: Int
while (true) {
prime = numbers.first()
yield(prime)
numbers = numbers.drop(1).filter { it % prime != 0 }
}
}
print(primes.take(10).toList())
it's because you change prime variable in filter closure. For example, on the second step you have numbers as .filter { it % prime != 0 }.filter { it % prime != 0 } but the prime is one variable, and it is equal to 3
Correct version:
val primes: Sequence<Int> = sequence {
var numbers = generateSequence(2) { it + 1 }
while (true) {
val prime = numbers.first()
yield(prime)
numbers = numbers.drop(1).filter { it % prime != 0 }
}
}
print(primes.take(10).toList())
Hey guys, newbie here. One question, can't understand why this while loop doesn't work even when I entered a int bigger than 9 to the variable num, the while loop should repeat itself until the expression is false, and it doesn't, no output even. Am I missing something here? Thanks in advance.
fun main () {
while(true) {
println ("\nWrite a positive number: ")
var num = readLine()!!.toInt()
var sum = 0
if (num > 9) {
while (num > 9) {
var digit = num % 10
sum = sum + digit
num = num / 10
}
println("\nDigit Sum: $sum")
} else if (num in 1..9) {
println("\nDigit Sum for the number $num is $num")
} else {
println("\nInvalid input, try again.")
}
}
}
The issue is that you are not summing the last num when it gets less or equal to 9. You can even simplify your code a bit. Try the following:
fun main() {
while(true) {
println ("\nWrite a positive number: ")
val insertedNumber = readLine()!!.toInt()
var num = insertedNumber
var sum = 0
while (num > 9) {
val digit = num % 10
sum = sum + digit
num = num / 10
}
sum = sum + num
println("\nDigit Sum for the number $insertedNumber is $sum")
}
}
You don't need to redeclare the variables every time
var sum = sum + digit
var num = num / 10
So simply remove var
sum = sum + digit
num = num / 10
I'm attempting to compare different run-times for simple blocks of code, but continue to get 0 returned. What can I do to get a better approximation for the execution time?
private var trackConstantTime: Long? = null
this.trackConstantTime = measureTimeMillis {
/* determine if a given number is even or odd */
var n = (0..(Int.MAX_VALUE)).random()
if(n % 2 == 0) "Even" else "Odd"
}
println("O(1), Constant Time for fxConstantTime(...):${TimeUnit.MILLISECONDS.toSeconds(trackConstantTime!!)}")
Similarly if I'll attach another example that's returning 0 for the runtime.
private var trackLinearTime: Long? = null
private var uL: MutableList<Int> = mutableListOf()
for(i in 0..100){
this.uL.add( ((0)..(100)).random() )
}
this.trackLinearTime = measureTimeMillis {
/* determine the maximum value in an unsorted array */
var max: Int = 0
for(i in 0 until uL.size) {
if (uL[i] > max) max = uL[i]
println(max)
}
}
println("O(n), Linear Time for fxLinearTime(...):${TimeUnit.MILLISECONDS.toSeconds(trackLinearTime!!)}")
Maybe try to measure time in nanoseconds:
this.trackLinearTime = measureNanoTime {
...
}
It's kind of bucket sort algorithm, trying to get K nearest locations from point (0,0). This is being done by calculating distances of these locations and bucketing them based on distance. If two locations are at equal distance then priority given to location with closet x and then y(if x values are same)
What is time complexity of following solution?
O(NlogN) or O(KNlogN) or anything else
// java
Input: int k, List<Location>
Output: List<Location>
public class Location {
//constructor x and y
int x;
int y;
//get
//set
//hashcode and equals
}
public class Solution {
public List<Location> returnKNearestLocation(int k, List<Location> locations) {
Map<Float, Set<Location>> map = new TreeMap<>();
for(Location loc: locations) {
float dist = calculateDistance(new Location(0,0), loc);
List<Location> temp = map.getOrDefault(dist, new HashSet());
temp.add(loc);
map.put(temp);
}
List<Location> result = new ArrayList<>();
int size = k;
while(size > 0) {
for(Float key : map.keySet()) {
Set<Location> loc = map.get(key);
Collection.sort(loc, p1, p2 -> {
return p1.x.equals(p2.x)? p1.y.compare(p2.y) : p1.x.compare(p2.x);
});
for(Location currLoc : loc) {
result.add(currLoc);
if(result.size() == k) {
return result;
}
}
size = size - loc.size();
}
}
return result;
}
private float calculateDistance(Location p, Location q) {
// calculate distance Math.sqrt((P.x - Q.x)^2 + (P.y - Q.y)^2)
}
}
I'd say O(N*log(N)).
Assuming float dist = calculateDistance(new Location(0,0), loc) is O(1).
Implementations of put() and getOrDefault() in a TreeMap are O(log(N)). Other implementations offer O(1). I'd take a look at HashMap.
Implementation of add in a HashSet is O(1) (amortized).
Implementation of add in an ArrayList is O(1) (amortized)
BucketSort has a worst-case of O(N^2), in the case that all items are placed in the same bucket.
I'd take a look at HashMap instead of TreeMap.
So, assuming I'm not wrong:
The first loop (foreach loc) has a complexity of O(N*log(N)).
The second loop (while size > 0) is O(N*log(N)).
Assuming all locations are placed in the same bucket, we'll sort all the items (O(N*log(N))).
Then we'll iterate through the first K elements, and add to result -- this takes O(K) < O(N).
How do I add the digits in a particular number for example if the number is 3234 the result should be 3+2+3+4 = 12?
Something along the lines of this should do it:
int val = 3234;
int sum = 0;
while (val != 0) {
sum += (val % 10);
val = val / 10;
}
// Now use sum.
For continued adding until you get a single digit:
int val = 3234;
int sum = val;
while (sum > 9) {
val = sum;
sum = 0;
while (val != 0) {
sum += (val % 10);
val = val / 10;
}
}
// Now use sum.
Note that both of these are destructive to the original val value. If you want to preserve it, you should make a copy or do this in a function so the original is kept.
Hope it is not your homework !
int sum = 0;
while (value!=0) {
sum += value % 10;
value = value / 10;
}