ProstDev ProstDev
Challenges Jul 11, 2023 · 2 min read

DataWeave programming challenge #8: Sum all digits to get a 1-digit number

Create a DataWeave script to sum all the digits from the input payload until there's only one digit left.

By Alex Martinez
Thumbnail: DataWeave programming challenge #8: Sum all digits to get a 1-digit number Read & copy the full video transcript

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 Playground

Input

Consider the following input payload (can be of txt format):

2456
2
25235
2456
6
54
58795
3
456
76544
0

Explanation of the problem

Create a DataWeave script to sum all the digits from the input payload until there’s only one digit left.

For example,

  • 123 + 456 = 579
  • 579 is broken down into 5 + 7 + 9 = 21
  • 21 is broken down into 2 + 1 = 3
  • The final result is 3 because it’s a 1-digit number

Expected output

In this case, the expected output would be:

2

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

You can first sum each line from the input payload to end up with just one number.

Clue #2

Use sizeOf() to get the length of a String.

Clue #3

You can use reduce() to sum some of the digits.

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 some solutions we provide here so you can compare your result with us.

Solution #1

%dw 2.0
import lines from dw::core::Strings
output application/json
fun sumNums(num, result=0) = do {
    var new = (num reduce $+$$) as String
    ---
    if (sizeOf(new) > 1)
        sumNums(new, result+new)
    else new
}
---
sumNums(sum(lines(payload))) as Number

Solution #2

%dw 2.0
import lines from dw::core::Strings
output application/json
fun sumNums(num, result=0) = do {
    var new = (num reduce $+$$) as String
    ---
    if (sizeOf(new) > 1)
        sumNums(new, result+new)
    else new
}
---
payload replace "\n" with ""
then sumNums($) as Number

Subscribe to receive notifications as soon as new content is published ✨

Reader notes

Helpful comments preserved from the original post.

  • Nicky van Steensel van der Aa · Jul 18, 2023
    %dw 2.0
    output application/json
    fun solve(x) =
     if (sizeOf(x)==1) x
     else solve((x reduce ((item, accumulator ) -> accumulator + item)))
    ---
    solve(payload splitBy('\n'))
  • sai teja nallamallli · Jul 12, 2023
    %dw 2.0
    output application/json
    fun singleit(L:Array):Number=singleit(sum(L map singleit($ as Number default $)))
    fun singleit(X:Null):Number =0
    fun singleit(N: Number):Number = if (N==0) 0 else do{var res = (N mod 9)
    
    ---
    if(res==0) 9 else res}
    
    fun singleit(Str :Any) : Number =0
    ---
    singleit(payload splitBy "\n")
  • T. sc. · Jul 12, 2023
    %dw 2.0
    output application/json
    import lines from dw::core::Strings
    fun reduceToOneDigit(inputValue) = inputValue  match {
        case d if(d is Number and sizeOf(d) == 1) -> d
        else -> reduceToOneDigit($ reduce $$ + $)
    }
    ---
    reduceToOneDigit(lines(payload))
  • Diksha Dhanuka · Jul 12, 2023
    %dw 2.0
    output application/json
    
    
    ---
    payload splitBy ("\n") reduce ($+$$) reduce ($+$$) reduce($+$$)
  • armandomejiam · Jul 12, 2023

    https://gist.github.com/armandomejiam/f49ea694e09f91bf6f0530920876186b

  • Nirmala Vairaganthan · Jul 11, 2023
    %dw 2.0
    output application/json
    fun add(num) = if (sizeOf(num) > 1) add(sum(num splitBy "")) else num
    ---
    add(sum(payload splitBy "\n"))
  • Sudiptaa · Jul 11, 2023
    %dw 2.0
    output application/json
    import * from dw::core::Strings
    
    fun sumOfDigits(n) = if(sizeOf(n) == 1) n else sumOfDigits(n reduce($ + $$))
    ---
    
    sumOfDigits(sum(lines(payload) map ($))  splitBy  "")
  • Victor Manuel Rodriguez · Jul 11, 2023
    %dw 2.0
    fun sumDigits(val) = using(result = sumValue(val)) if(result / 10 >= 1)
    sumDigits("$(result)") else result
    
    fun sumValue(val) = val reduce((item, acc = 0) -> (item as Number) + acc)
    output application/json
    ---
    sumDigits(sumValue((read(payload, "text/plain") splitBy('\n'))))

FAQs

Frequently asked questions about this post.

  • What does this DataWeave challenge ask you to do?

    It asks you to create a DataWeave script that sums all the digits from the input payload until only one digit is left. For example, 123 + 456 = 579, then 579 breaks down into 5 + 7 + 9 = 21, then 21 breaks down into 2 + 1 = 3, and the final result is 3 because it is a 1-digit number.

  • What is the expected output for the sample input?

    For the sample input payload shown in the post (which can be in txt format), the expected output is the single digit 2.

  • What clues does the post give if I'm stuck?

    The post offers three clues: first, you can sum each line from the input payload to end up with just one number; then use sizeOf() to get the length of a String; and finally you can use reduce() to sum some of the digits.

  • What's the difference between the two provided solutions?

    Both solutions use the same recursive sumNums function, but Solution #1 starts from sum(lines(payload)) to total the lines first, while Solution #2 instead does payload replace "\n" with "" and then pipes that into sumNums($) as Number.

  • Where should I look for help while solving this challenge?

    The post recommends referring to the DataWeave documentation only, at https://docs.mulesoft.com/dataweave/latest/ , and trying to avoid using Google or asking others so you can learn on your own and become a DataWeave expert. You can also solve it on the DataWeave Playground.

More from this series

DataWeave Programming Challenges· Part 8 of 8
  1. 1.DataWeave programming challenge #1: Add numbers separated by paragraphs and get the max number
  2. 2.DataWeave programming challenge #2: Rock Paper Scissors game score system
  3. 3.DataWeave programming challenge #3: Count palindrome phrases using the Strings module
  4. 4.DataWeave programming challenge #4: Solve the Tower of Hanoi mathematical puzzle
  5. 5.DataWeave programming challenge #5: Reverse a phrase's words, but keep the punctuation
  6. 6.DataWeave programming challenge #6: Using tail-recursion to get the factorial of a number
  7. 7.DataWeave programming challenge #7: Modify certain values from a JSON structure
  8. 8.DataWeave programming challenge #8: Sum all digits to get a 1-digit number
Search

Loading search…