https://kotlinlang.org logo
Title
a

Alex

12/09/2021, 5:59 PM
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

Joffrey

12/09/2021, 6:11 PM
Take a look at the stdlib function called
zipWithNext
:)
a

Alex

12/09/2021, 6:22 PM
@Joffrey thanks I used the following function
zipWithNext
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

Joffrey

12/09/2021, 6:28 PM
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

Paul Griffith

12/09/2021, 6:40 PM
the stdlib also has a
contentToString()
extension function for arrays to print the contents
👍 1
j

Joffrey

12/09/2021, 6:47 PM
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

Alex

12/10/2021, 3:17 PM
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

Joffrey

12/10/2021, 4:04 PM
Arrays are weird beasts that bring some legacy from Java, there is unfortunately little that Kotlin could do about it 😕
a

Alex

12/11/2021, 7:08 PM
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

Paul Griffith

12/14/2021, 3:10 PM
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)