#how to solve/optimise this CodeWar

1 messages · Page 1 of 1 (latest)

viral ermine
#
local function jump_to_zero(arr)
  local count={}
  local steps={}
  for i=1,#arr do
    local number=arr[i]
    count[i]=number
    steps[i]=0
    local temp=number
    local digits_sum=0
    while temp>0 do
  for j=1,#tostring(temp) do
      digits_sum=digits_sum+tonumber(string.sub(tostring(temp),j,j)) 
      end
      temp=temp-digits_sum
      steps[i]=steps[i]+1
    end
  end
  return steps
end

return jump_to_zero``` 

link: https://www.codewars.com/kata/64cfc5f033adb608e2aaedef/train/lua/6897a8d5bcb22fb5b17820cf

Subtask 2: n ≤ 10 ^ 5
Subtask 3: n ≤ 10 ^ 6
Subtask 4: n ≤ 7 * 10 ^ 6

also tried using a while loop instead of the 2nd for loop but that would be even slower
Codewars

Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.

broken carbon
#

Hey so I have tried to recreate it on my own, heres what I did:

local function jump_to_zero(arr)
    local result = {}
    
    for _, num in ipairs(arr) do
        local steps = 0
        local temp = 0
        local digits = {}
        
        while #digits > 1 or #digits == 0 do -- while the num is > 9 or the digits are not set
            digits = {}
            temp = 0
            for digit in         
tostring(num):gmatch(".") do -- retrieve digits
                table.insert(digits, tonumber(digit))
            end
            
            for i, digit in ipairs(digits) do -- sum of digits
                temp += digit
            end
            
            num -= temp
            steps += 1
        end
        
        table.insert(result, steps)
    end
    
    return result
end
#

It seems to pass all subtasks with ease

#

However I dont know if you have figured it out yet but there seems to be a problem with your code

#
local digits_sum=0
while temp>0 do
    for j=1,#tostring(temp) do
        digits_sum=digits_sum+tonumber(string.sub(tostring(temp),j,j)) 
    end
    temp=temp-digits_sum
    steps[i]=steps[i]+1
end
#

In this part, you never reset the digits_sum

#

so it just keeps adding on and on, which results in the result being much smaller than the actual result

#

For example while jump_to_zero(200000) = 9350, your function returns 123

#

I have also forgot to reset that value in my function while I was writing it lol

#

Other than that your function seems fine

viral ermine
#

Did you try submitting it on CodeWars? I fixed the problem you found but its still very unoptimised

#

I tried making a cache but I'm not sure what I'm doing wrong for it to STILL be slow

wind gullBOT
#

studio** You are now Level 1! **studio