Hi Guys, i kind of hit a road block while doing pr...
# getting-started
a
Hi Guys, i kind of hit a road block while doing practice questions in code wars 1. I have a doubleArray which contains distances
val x:DoubleArray = doubleArrayOf(0.0, 0.19, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25)
the values are records every 1.5s distance travelled, in this case 0.0 is the starting point 0.19 is when the distance covered is recorded at 1.5 seconds mark after another 1.5 seconds the distance of 0.5 is recorded and so on. 2. I need to find the difference in distances as following
0.0-0.19, 0.19-0.5, 0.5-0.75, 0.75-1.0, 1.0-1.25, 1.25-1.50, 1.5-1.75, 1.75-2.0, 2.0-2.25
, i know how to use map(to double values or multiple then) but i don't know how to subtract from a preceded value with a previous value in an Array 3. you can refer to the full question if my explanation is not clear, i just need to find the difference in distances before i can proceed to do the next step, hope someone can help me on this 😅
j
Take a look at the stdlib function called
zipWithNext
:)
a
@Joffrey thanks I used the following function
zipWithNext
Copy code
val differenceInDistance=x.toList().zipWithNext{a,b->b-a}
when i add toDoubleArray though, nothing get printed out, without it values get printed out but as a list
j
It's usually more comfortable to stick to lists in Kotlin, but working with arrays should be fine too. My guess is that you're trying to print the array with
println(myArray)
which doesn't print the elements of the array but instead prints the array object reference (something like
[D@3343c8b3
). This is unfortunately how the JVM does things because arrays use the default
toString()
method. If you want to use an array anyway and print it, you can use
println(Arrays.toString(myArray))
p
the stdlib also has a
contentToString()
extension function for arrays to print the contents
👍 1
j
Ah I literally searched for this just now, but didn't find anything quickly. I knew there was something! Thanks for pointing it out
1
a
thanks @Joffrey @Paul Griffith, i find it strange that i can use println for a list but not on an array, the solution provided does the work,i use println on array to ensure the calculations are correct
j
Arrays are weird beasts that bring some legacy from Java, there is unfortunately little that Kotlin could do about it 😕
a
Well that's a shame
@Paul Griffith i tried the contentToString() method, but it's not recognized by the IDE, is there something i need to import to use it?
p
can you post your code? maybe it's not an array anymore (
zipWithNext
and lots of the other array extensions return Lists instead of arrays)