0

Struggling to find a way to multiply the numbers in the below array

[120.98 7, 151.99 8, 141.39 4, 137.71 7, 121.27 6, 187.29 11] 

Trying to split them by space using split and multiply them however facing issues, any ideas ?

Ask is to multiply the two numbers before comma.

cfrick
  • 35,203
  • 6
  • 56
  • 68
Raj
  • 29
  • 1
  • 2
  • Hi, not sure you need a regex for this. You may parse your array, then for each element cast it to string, split it, then multiply both components (previousely cast as double). I didn't try it but I think it should work – A.Joly Dec 17 '18 at 07:05
  • Is the source, that passes you down this shape, intentionally doing it this way? This looks like someone wants to pass a list of tuples and something upstream `toString()`s it? So rather that battling against parsing you might be better off finding the source and convincing them, there are better ways to deal with that? – cfrick Dec 17 '18 at 08:35

1 Answers1

0

It's a problem if your array stands as you show it. But if you set it first in String format, here is a solution :

myArray = "[120.98 7, 151.99 8, 141.39 4, 137.71 7, 121.27 6, 187.29 11]"
myStr = myArray[2..-1]  // to get rid of brackets
myStr = myStr[0..-2]
myStr = myStr.tokenize('[,]') // for parsing
println myStr

myStr.each{
    //println it
    first = it.split()[0].toDouble()
    second = it.split()[1].toDouble()

    println "$first * $second = " + first*second
}

It's probably not the best or cleanest way, but it fits your requirements here's the result:

[20.98 7,  151.99 8,  141.39 4,  137.71 7,  121.27 6,  187.29 11]
20.98 * 7.0 = 146.86
151.99 * 8.0 = 1215.92
141.39 * 4.0 = 565.56
137.71 * 7.0 = 963.97
121.27 * 6.0 = 727.62
187.29 * 11.0 = 2060.19

Alex

A.Joly
  • 2,317
  • 2
  • 20
  • 25