[Algorithms] – Problem regards repeated strings solved with go

Problem:

Screenshot 2019-04-11 at 11.50.12

Solution:

Following the code to solve the problem.

package algoTest

import "strings"

func RepeatedString(s string, n int64) int64 {
   size := len(s)
   qtFirst := int64(0)
   res := int64(0)

   // check the qt first letter in the string
   c := strings.Split(s,"")
   pos := -1

   for i := 0; i < len(c); i++ {
      if c[i] == "a" {
         if pos == -1 {
            pos = i;
         }
         qtFirst++
      }
   }

   if pos == -1 {
      return res
   }

   // calc how many times it will be repeated
   mod := n%int64(size)
   total := n/int64(size)
   if mod == 0 {
      res = total*qtFirst
   } else {
      res = total*qtFirst
      for i := int64(0);i < mod  ; i++ {
         if c[i] == "a" {
            res++
         }
      }
   }
   return int64(res);
}

Following a small code to check the solution.

package algoTest

import (
   "github.com/stretchr/testify/assert"
   "testing"
)

func TestRepeatedString(t *testing.T) {
   s:="aba"
   res:=RepeatedString(s,10)
   assert.Equal(t, int64(7),res)

   s2:="gfcaaaecbg"
   res2:=RepeatedString(s2,547602)
   assert.Equal(t, int64(164280),res2)
}

This problem is from : https://www.hackerrank.com

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s