I have the code:
int[] values = { 1, 4, 9, 16 };
Stream<Integer> ints = Stream.of(values);
which gives me compilation error. But:
int[] values = { 1, 4, 9, 16 };
Stream<Integer> ints = Stream.of(new Integer[] {1, 4, 9, 16});
doesn't give so. Why?
In the first example, you are passing an array of primitives ints to Stream#of which can take either an object, or an array of object. Primitives are not objects.
In the second example, it compiles becauses you pass in an array of Integer.
You can use IntStream#of which accept int arrays.
Because int[] and Integer[] is different types. First one is array of primitives, second one is array of objects with type Integer.
You can use IntStream.of(int[]) or Stream.of(Integer[])
A bit un-related, but the more correct way to do it would be :
Arrays.stream(values).boxed();
Related
I am looking in Kotlin for a method who return me from a list a new list with a defined number of elements (for example 10).
Whatever the size of the list, the method would always return the same number of elements.
For example, suppose a list of 3000 elements, it would return me a list of 10 elements from indexes 0, 300, 600, 900, 1200,...
Is there an extension function for this?
That's kind of a specialised thing, so there's nothing (that I know of) in the standard library - but you could easily make your own extension function:
fun <T: Any> List<T>.sample2(count: Int): List<T> {
// this allows for a fractional step, so we get a more accurate distribution of indices
// with smaller lists (where count doesn't divide into the list size evenly)
val step = size / count.toFloat()
return List(count) { i -> elementAt((i * step).toInt()) }
}
You'll get repeats if your list is too small to provide count unique indices (e.g. your list has 9 items and you want 10), so you'd have to handle that if you want different behaviour, but I think this is the easiest way to do it
Here's an idea:
Take advantage of the method chunked(size: Int), which tries to depart a given collection into sub-collections of the given size.
That's not quite what you want, but you can use it in order to implement a custom extension function which does what you want, e.g. like this:
fun List<Int>.departInto(subListCount: Int) : List<List<Int>> {
// calculate the chunk size based on the desired amount of sublists
val chunkSize = this.size / subListCount
// then apply that value to the chunked method and return the result
return this.chunked(chunkSize)
}
Using this could look as follows:
fun main() {
// define some example list (of 30 elements in this case)
val someList: List<Int> = List(30, {it})
// use the extension function
val tenSubLists = someList.departInto(10)
// print the result(s)
println(tenSubLists)
}
The output of this code will be 10 sub-lists of 3 elements (your example of 3000 elements would then result in 10 sub-lists of 300 elements each):
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18, 19, 20], [21, 22, 23], [24, 25, 26], [27, 28, 29]]
I can sort a list like this in Dart:
final myList = [6, 3, 7, 1, 0, 2];
myList.sort();
However, this is a destructive sort since it mutates it in place. I'd like to do something like this:
final myList = [6, 3, 7, 1, 0, 2];
final newList = myList.sorted();
where my list stays the same but newList contains the sorted list. Dart apparently doesn't have this functionality, so how do I implement that myself?
In searching for the answer to this question my main struggle was knowing the proper way to copy a list, which wasn't as obvious as it seems like it should be. I found the answer to that, so I am also posting an answer to my original question below, Q&A style.
You can create a new sorted list without affecting the original list like so:
final myList = [6, 3, 7, 1, 0, 2];
final sorted = myList.toList()..sort();
Calling toList() copies the list. The .. is to get a reference to the list itself since sort() is a void function. This gives the same result:
final sorted = myList.toList();
sorted.sort();
Printing the values of both lists gives the following results:
print(myList); // [6, 3, 7, 1, 0, 2]
print(sorted); // [0, 1, 2, 3, 6, 7]
You can read more about copying lists here.
I'd suggest you to create a fixed-length list.
final myList = [6, 3, 7, 1, 0, 2];
final sortedList = myList.toList(growable: false)..sort();
It seems to me that this question is really "How can I copy a List?", and the sorting aspect is tangential.
There are multiple ways to copy an Iterable to a new List:
Using a method on the original Iterable: iterable.toList()
Using a List constructor: List.of(iterable)
Using the spread operator in a List literal: [...iterable]. Note that this always creates a growable List.
Note that List.from should not be used since that uses dynamic types and loses type information. Effective Dart prefers .toList().
Also note that the above applies to Sets too (iterable.toSet(), {...iterable}, Set.of(iterable)).
For example : [][]float64{{11, 5, 14, 1}, {11, 5, 14, 1}} has dimensions [2,4].
If this is passed to a function then what is the most efficient way to find the dimension here?
Thanks
The outer dimension is just len(x) where x is the slice of slices you pass to the function (your example [][]float64{{11, 5, 14, 1}, {11, 5, 14, 1}}).
However, the inner dimensions are not guaranteed to be equal so you will have to go through each element and check what len they have.
If you have the guarantee than each element of x has the same number of elements, just find len(x[0]) if len(x) > 0.
Go only provides 1-dimensional arrays and slices. N-dimensional arrays can be emulated by using arrays of arrays, which is close to what what you're doing--you have a 1-dimensional slice, which contains 2 1-dimensional slices.
This is problematic, because slices are not of a defined length. So you could end up with slices of wildly different lengths:
[][]float64{
{1, 2, 3, 4},
{5, 6, 7, 8, 9, 10},
}
If you use actual arrays, this is simpler, because arrays have a fixed length:
[2][4]float64
You can extend this to as many dimensions as you want:
[2][4][8]float64 provides three dimensions, with respective depths of 2, 4, and 8.
Then you can tell the capacity of each dimension by using the built-in len() function on any of the elements:
foo := [2][4][7]float64{}
x := len(foo) // x == 2
y := len(foo[0]) // y == 4
z := len(foo[0][0]) // z == 8
My Input Sequence is : [1,2,3,4,5]
Result should be : [1,12,3,14,5]
That is even numbers are incremented by 10, but odd values are left intact.
Here is what I tried:
public static List<Integer> incrementEvenNumbers(List<Integer> arrays){
List<Integer> temp =
arrays.stream()
.filter(x->x%2==0)
.map(i -> i+10)
.collect(Collectors.toList());
return temp;
}
when I call this method,
System.out.println(incrementEvenNumbers(Arrays.asList(1,2,3,4,5)));
I get [12, 14]. I am wondering how to include the values not filtered to seep in but the map should not be applied for it.
You can use a ternary operator with map, so that the function you apply is either the identity for odd values, or the one that increments the value by 10 for even values:
List<Integer> temp = arrays.stream()
.map(i -> i % 2 == 0 ? i+10 : i)
.collect(Collectors.toList());
The problem, as you saw, is that filter will remove the elements so when a terminal operation will be called, they will be filtered by the predicate.
Note that if you don't care modifying the list in place, you can use replaceAll directly, as you are doing a mapping from a type T to T.
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
list.replaceAll(i -> i % 2 == 0 ? i+10 : i); //[1, 12, 3, 14, 5]
I need to find duplicate latitude in an array and nudge it a bit to avoid marker display problem.
I searched and find a way to do it in ruby:
1.find duplicate element in ruby
(I consider sort array element and check adjacent element)
2.use array.indexof() to get its index(may have 3 or more duplicate element)
This works sure but I feel its not the best way. Is there a way to find duplicate and index of duplicate in one go?
Thanks in advance
EDIT:
I've find a way,check duplicate and change on spot.
But the problem is this function change all duplicate value to another duplicated value.
I think its because the main array is not updated during check and change procedure, attached is my code,anyway to improve it?
#ln=0
for #ln in 0..#checkLocation.length-1 do
if (!(#checkLocation.index(#existlat)==nil) && (#existlat!=nil))
#checkLocation[#ln]=#checkLocation[#ln]+0.00001
end
#existlat=#checkLocation[#ln]
end
a = [:a, :b, :c, :b, :d, :a, :e]
a.each_index.group_by{|i| a[i]}.values.select{|a| a.length > 1}.flatten
# => [0, 5, 1, 3]
Finding dupes is not very difficult if performance is not a real issue for you.
The most natural way would be to compare each element with all the other elements:
for (int i = 0; i < arraySize-1; ++i) {
for (int j = i+1; j < arraySize; ++j) {
if(array[i] == array[j]) changeDupe(array[j]);
}
}
The code above will allow you to change all the dupes.
Example in execution, changin dupes to 0:
Input: {1, 2, 3, 2, 1, 4, 5, 6, 8, 2}
Output: {1, 2, 3, 0, 0, 4, 5, 6, 8, 0}
Another way to achieve this is to use a second array. If you are using integer values, you can make it like this:
int input[10] = {1, 2, 3, 2, 1, 4, 5, 6, 8, 2};
bool output[10] = {false, false, false, false, false, false, false, false, false, false};
for (int i = 0; i < arraySize; ++i) {
if (output[input[i]] == false) changeDupe(input[i]));
else output[input[i]] = true;
}
However, if one of your elements is bigger than the size of your array you will have a boundary problem. Suppose you have the value 100, then you would be trying to access the 100th element of the boolean array.
If you want to use the second algorithm but you are not working with an integer array, you could use a map to map each value on your array to an int, and then use the map value to set the booleans.
A pseudocode would look like this:
Map<yourData, int> map;
map<someValue, 1>;
map[someValue] = 1; //work based on this return value;
Yeeeet another way is to sort the array before iterating over it, and stop once you hit a different number. This would diminish the number of times you iterate over the array, but you would be adding the sorting algorithm complexity (probably O(n log(n))).
The code would look something like this:
int i = 0;
while (i < arraySize-1) {
if(array[i] == array[i+1])
array[i] = 0;
i++;
}
Input: {1, 1, 2, 3, 3, 4, 5, 6, 7, 8};
Output: {0, 1, 2, 0, 3, 4, 5, 6, 7, 8}
Complexity:
for the first algorithm, you would have N*(N-1) which I would say is O(n²).
for the second is O(n), but restrictions apply.
for the third, it would be the sort + O(n) for the loop.