The problem
The enter is a string str
of digits. Reduce the string into chunks (a bit here’s a substring of the preliminary string) of dimension sz
(ignore the final chunk if its dimension is lower than sz
).
If a bit represents an integer such because the sum of the cubes of its digits is divisible by 2, reverse that chunk; in any other case rotate it to the left by one place. Put collectively these modified chunks and return the outcome as a string.
If
sz
is<= 0
or ifstr
isempty
return “”sz
is larger(>)
than the size ofstr
it’s unimaginable to take a bit of dimensionsz
therefore return “”.
Examples:
revrot("123456987654", 6) --> "234561876549"
revrot("123456987653", 6) --> "234561356789"
revrot("66443875", 4) --> "44668753"
revrot("66443875", 8) --> "64438756"
revrot("664438769", 8) --> "67834466"
revrot("123456779", 8) --> "23456771"
revrot("", 8) --> ""
revrot("123456779", 0) --> ""
revrot("563000655734469485", 4) --> "0365065073456944"
Instance of a string rotated to the left by one place:
s = "123456" provides "234561".
The answer in Golang
package deal answer
func cubeSum(str []rune) int {
sum := 0
for _, dr := vary str {
d := int(dr) - 48
sum += d * d * d
}
return sum
}
func reverse(s []rune) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}
func shift(s []rune) {
first := s[0]
for i := vary s[1:] {
s[i] = s[i+1]
}
s[len(s)-1] = first
}
func Revrot(s string, n int) string {
if n <= 0 || n > len(s) {
return ""
}
sr := []rune(s)
i := 0
for ; i+n <= len(sr); i += n {
chunk := sr[i:i+n]
if cubeSum(chunk)%2 == 0 {
reverse(chunk)
} else {
shift(chunk)
}
}
return string(sr[:i])
}
Check instances to validate our answer
package deal our_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func dotest(s string, n int, exp string) {
var ans = Revrot(s, n)
Count on(ans).To(Equal(exp))
}
var _ = Describe("Assessments Revrot", func() {
It("ought to deal with primary instances", func() {
dotest("1234", 0, "")
dotest("", 0, "")
dotest("1234", 5, "")
var s = "733049910872815764"
dotest(s, 5, "330479108928157")
})
})