DataWeave programming challenge #1: Add numbers separated by paragraphs and get the max number
Create a DataWeave script to add all the numbers separated by a paragraph. Then, retrieve the highest number.
DataWeave Programming Challenges· Part 1 of 8
- 1.DataWeave programming challenge #1: Add numbers separated by paragraphs and get the max number
- 2.DataWeave programming challenge #2: Rock Paper Scissors game score system
- 3.DataWeave programming challenge #3: Count palindrome phrases using the Strings module
- 4.DataWeave programming challenge #4: Solve the Tower of Hanoi mathematical puzzle
- 5.DataWeave programming challenge #5: Reverse a phrase's words, but keep the punctuation
- 6.DataWeave programming challenge #6: Using tail-recursion to get the factorial of a number
- 7.DataWeave programming challenge #7: Modify certain values from a JSON structure
- 8.DataWeave programming challenge #8: Sum all digits to get a 1-digit number
Note
This challenge is based on Advent of Code 2022 day 1
Try to solve this challenge on your own to maximize learning. We recommend you refer to the DataWeave documentation only. Try to avoid using Google or asking others so you can learn on your own and become a DataWeave expert!
Solve on the PlaygroundInput
Consider the following input payload (can be of txt format):
1
2
3
4
5
0
15
20
5
1
3
25
6
4
4
Explanation of the problem
Create a DataWeave script to add all the numbers separated by a paragraph.
For example,
- the first number would be 3 (2 + 1),
- the second number would be 12 (3 + 4 + 5 + 0),
- the third number would be 15, and so on.
After that, retrieve the highest number.
(Using code, not manually 😉)
Expected output
In this case, the expected output would be:
29
Clues
If you’re stuck with your solution, feel free to check out some of these clues to give you ideas on how to solve it!
Clue #1
Use the splitBy() function
Clue #2
Instead of splitting by “\n” try splitting by “\n\n” at first - to separate by paragraph
Clue #3
Use map() to go through each paragraph
Clue #4
Use splitBy() again to separate each of the paragraph’s lines
Clue #5
Use sum() to add all the numbers in each paragraph
Clue #6
Use max() to return the highest number from the array
Clue #7
If some of the numbers are string instead of numbers, use as to coerce them to Numbers — this is a bug and will hopefully be fixed soon!
Answer
If you haven’t solved this challenge yet, we encourage you to keep trying! It’s ok if it’s taking longer than you thought. We all have to start somewhere ✨ Check out the clues and read the docs before giving up. You got this!! 💙
There are many ways to solve this challenge, but you can find here some solutions we are providing so you can compare your result with us.
Solution #1
%dw 2.0
output application/json
---
(payload splitBy "\n\n")
map (sum($ splitBy "\n") as Number)
then max($)
Solution #2
%dw 2.0
output application/json
---
(payload splitBy "\n\n")
map ((item) -> (
sum(item splitBy "\n") as Number
))
then max($)
Solution #3
%dw 2.0
output application/json
---
(payload splitBy "\n\n")
map ((item,index) -> do {
var newItem = item splitBy "\n"
---
sum(newItem) as Number
})
then max($)
Solution #4
%dw 2.0
output application/json
---
max((payload splitBy "\n\n")
map (sum($ splitBy "\n") as Number))
Did you like this challenge?? Let us know what you think!! 👇
Subscribe to receive notifications as soon as new content is published ✨
Reader notes
Helpful comments preserved from the original post.
- learningdazzler · Oct 24, 2024
%dw 2.0 output application/json --- (((((payload splitBy "\n\n") map ((item, index) -> item replace "\n" with ",")) map ((item, index) -> item splitBy ",") ) map ((item, index) -> item map ((item, index) -> item as Number))) map ((item, index) -> sum(item) ) orderBy ((item, index) -> item))[-1] - Kevin Medina · Feb 23, 2024
%dw 2.0 import * from dw::core::Arrays output application/json fun getMaxNumber(nums) = max(nums splitBy "\n\n" map ((values, index) -> values splitBy "\n" sumBy $)) --- getMaxNumber(payload) - sai teja nallamallli · Jul 13, 2023
%dw 2.0 output application/json fun returnmax(a : Number,b : Number) : Number=if(a>b)a else b fun findMax(Data: String) : Number = findMax(Segregate(Data)) fun findMax(L : Array<Number>) :Number = L reduce ($$ returnmax $) default 0 fun findMax(X:Any) : Number = 0 fun Segregate(Data : String) : Array<Number>= Segregate(Data splitBy "\n\n") fun Segregate(Data : Array) : Array<Number> = Data map sum($ splitBy "\n") --- findMax(payload) - Victor Manuel Rodriguez · Jul 11, 2023
%dw 2.0 var pay = (read(payload, "text/plain") splitBy('\n\n')) map ($ splitBy('\n')) output application/json --- max(pay map sum($)) - Disha Bhar · May 10, 2023
Hi, tried solving using random input.
%dw 2.0 output application/json --- max((payload splitBy "\n\n") map(sum($ splitBy "\n") as Number)) - Kalyani Chodavarapu · May 9, 2023
%dw 2.0 output application/json --- max(payload splitBy ("\n\n") map (($ splitBy "\n" reduce $ + $$) as Number)) - mysg147 · Apr 20, 2023
%dw 2.0 output application/json var x= payload splitBy('\n\n') var y = x map((val,in) -> sum(val splitBy('\n')) as Number ) --- max(y) - Felix Schnabel · Feb 22, 2023
%dw 2.0 output application/json import lines from dw::core::Strings --- max(payload splitBy "\n\n" map sum(lines($))) -
Reply to Felix Schnabel
Alex Martinez · Feb 22, 2023You and your fancy code :p Thanks, Felix! I'll use one of your solutions for the next challenge, I hope you don't mind (giving you full credit, of course).
-
Reply to Alex Martinez
Felix Schnabel · Feb 22, 2023Sure, no problem!
-
Reply to Felix Schnabel
Saravanan Devadass · Mar 6, 2023How do you handle if the line has a letter.
-
Reply to Saravanan Devadass
Alex Martinez · Mar 7, 2023It's a simple challenge. In this case, there's never gonna be a letter in the input.
- Elvedin Babic · Feb 22, 2023
max(payload splitBy "\n\n" map sum($ splitBy "\n")) - Faizan Arif · Feb 21, 2023
Here is my soln
%dw 2.0 output application/json var Numbers = payload splitBy (/\r?\n\r?\n/) var highestSum = Numbers map ((item)-> item splitBy("\n") reduce ((value, accumulator) -> accumulator + value as Number)) maxBy ((item) -> item ) --- highestSum - Shyam Raj Prasad · Feb 21, 2023
%dw 2.0 output application/json import lines from dw::core::Strings --- max(lines(payload) joinBy "," splitBy ",," map( sum($ splitBy ",") as Number ))
FAQs
Frequently asked questions about this post.
-
What is the goal of this DataWeave challenge?
Create a DataWeave script that adds all the numbers separated by a paragraph, then retrieves the highest of those sums. For the sample input the first group sums to 3, the second to 12, the third to 15, and so on, and the expected output is 29.
-
How do I separate the input into paragraphs in DataWeave?
Instead of splitting by
"\n", split by"\n\n"first with thesplitBy()function so the payload is separated by paragraph; then usemap()to go through each paragraph andsplitBy()again to separate each paragraph's individual lines. -
Which functions does this challenge suggest using?
The clues point you to
splitBy()to break the text into paragraphs and then lines,map()to iterate over each paragraph,sum()to add all the numbers in a paragraph, andmax()to return the highest number from the resulting array. -
Why do some solutions coerce values with `as Number`?
If some of the numbers come through as strings instead of numbers, you use
asto coerce them to Numbers; the post notes this is a bug that will hopefully be fixed soon. -
Where can I try solving this challenge?
You can solve it directly on the DataWeave Playground at https://dataweave.mulesoft.com/learn/playground?projectMethod=GHRepo&repo=alexandramartinez%2Fdataweave-challenges&path=challenges%2F1 , and the challenge itself is based on Advent of Code 2022 day 1 at https://adventofcode.com/2022/day/1 .
-
Is there only one correct solution?
No, there are many ways to solve this challenge. The post provides several sample solutions so you can compare your result, and it recommends referring only to the DataWeave documentation at https://docs.mulesoft.com/dataweave/latest/ while you work through it.
More from this series
DataWeave Programming Challenges· Part 1 of 8
- 1.DataWeave programming challenge #1: Add numbers separated by paragraphs and get the max number
- 2.DataWeave programming challenge #2: Rock Paper Scissors game score system
- 3.DataWeave programming challenge #3: Count palindrome phrases using the Strings module
- 4.DataWeave programming challenge #4: Solve the Tower of Hanoi mathematical puzzle
- 5.DataWeave programming challenge #5: Reverse a phrase's words, but keep the punctuation
- 6.DataWeave programming challenge #6: Using tail-recursion to get the factorial of a number
- 7.DataWeave programming challenge #7: Modify certain values from a JSON structure
- 8.DataWeave programming challenge #8: Sum all digits to get a 1-digit number
