ALLAN AVELARTechnology Solutions
🍰Good Afternoon,<username class="jsx-1036735364">Guest</username>!Welcome to my website!Progressive Web App (PWA)Install in your deviceChromecast Controlsstatus: not playing or showingVolumeDown50%VolumeUpPlayPausestoppedStopResetFullscreenExpandRestricted accessLogin / RegisterEnter with your credentialsRestrict Access ManagerRequest your Access CodeAccount DetailsYour personal and access dataProjects / ServicesYour contract historyProducts / DownloadsYour purchase historyChromecast AppsYour streaming contractsCredits / PurchasesYour balance and credit historyAccess ManagerYour restricted content accessNotificationsNotifications enabled for youDisconnectDisconnect your userAvailable contentHomeAbout Me6Personal ResumeA little bit of how it all startedProfessional ResumeA little about my careerWork MethodologyHow I make it happenPersonal MemoriesRestricted ContentCurriculum VitaeRestricted ContentTrips & PhotosRestricted ContentAreas of Expertise10All my servicesSummary of all areasCTO as a ServiceGet a part-time basis C-LevelCorporate ArchitectureAgility and technology as a philosophySoftware & TechnologyComing soonFrontend DevelopmentComing soonBackend DevelopmentComing soonStrategy & ConsultingComing soonPlatform & DevSecOpsComing soonCustomer ExperienceComing soonAgile CultureComing soonInnovation Hub6Innovation CultureAdvantages and how to implementDistributed LT & BlockchainComing soonData Science & AnalyticsComing soonCybersecurity PlatformComing soonIntelligent AutomationComing soonAI & Machine LearningComing soonCourses & Training9Distributed LT & BlockchainComing soonCybersecurity PlatformComing soonIntelligent AutomationComing soonFrontend DevelopmentComing soonBackend DevelopmentComing soonPlatform & DevSecOpsComing soonAI & Machine LearningComing soonProgressive Web AppsComing soonAgile CultureComing soonContact MeDEVELOPED PROJECTSAll my projectsSummary of all areasFinancial Institutions3Santander Totta BankRestricted ContentSantander Brazil BankRestricted ContentSafra Bank S.ARestricted ContentWeb3 / Blockchain15Bitcoin (BTC)Restricted ContentEthereum VM (ETH)Restricted ContentRipple (XRP)Restricted ContentHyperledger.orgRestricted ContentInternet ComputerRestricted ContentStarknet (Cairo)Restricted ContentPolkadot (DOT)Restricted ContentDeFi DashboardsRestricted ContentToken MarketplacesRestricted ContentCrypto CheckoutsRestricted ContentCold / Hot WalletsRestricted ContentWallet ConnectorsRestricted ContentNon Fungible Tokens (NFT)Restricted ContentDescentralized Identities (DID)Restricted ContentDescentralized Organizations (DAO)Restricted ContentOld Projects29TIM | Interactive Voice ResponseAdobe Flex, Actionscript 3, Java, SpringACS | Follow EnergyAngularjs, HTML5, CSS3, C#, REST APIACS | Gateway CE50Angularjs, HTML5, CSS3, C, C#, LUASKY | Selinho de NatalActionscript 3, .NET, REST API, JSONIntel | Futuro de PresenteActionscript 3, .NET, REST API, JSONNestlé | Baú de DiversõesAS 3, .NET, REST, Facebook OpengraphMarlboro | Red RacingAdobe Flash, Actionscript 3, JSONHP | Cartucho PirataAdobe Flash, Actionscript 3, REST APIHP | Youtube StoreAdobe Flash, AS3, YouTube Data APICasas Bahia | BahianinhoActionscript 3, .NET, REST API, JSONAdria | TortinhasAdobe Flash, Actionscript 3, PHPUniverso Online | UOL FinanceActionscript 3, REST API, JSONUniverso Online | UOL MaisActionscript 3, REST API, JSONChevrolet | CaptivaActionscript 3, PHP, MYSQLGafisa | Edifício ColaborativoAdobe Flash, Actionscript 3Pão de Açucar | Sommeliers ClubAdobe Flash, Actionscript 3Pão de Açucar | Desafio ColeçõesAdobe Flash, Actionscript 3Antarctica | Circuito OriginalMacromedia Flash, Actionscript 2, XMLNestlé | Nescau 2.0Macromedia Flash, Actionscript 2, XMLSchin RefrigerantesActionscript 2, FMS 2, PHP, MYSQLMercedes-Benz | SLK 2005Actionscript 2, XMLMercedes-Benz | Classe CActionscript 2, XMLMercedes-Benz | Classe AActionscript 2, XMLMercedes Benz | SprinterActionscript 2, XMLMercedes Benz | Motores EletrônicosActionscript 2, XMLBanda NX ZeroMacromedia Flash, Actionscript 2Lew´lara TBWAActionscript 2, PHP, MYSQLMaison CriolaActionscript 2, PHP, MYSQLBondage MusicActionscript 2, PHP, MYSQLBlog PostsHackerRank5Sock MerchantWarm-Up ChallengesCounting ValleysWarm-Up ChallengesRepeated StringWarm-Up ChallengesJumping On CloudsWarm-Up ChallengesLeft RotationWarm-Up ChallengesLegal TermsTerms and ConditionsPrivacy PolicyDisclaimer
Username / PasswordBlockchainForgot your password?LoginDon't have an account? Look at a demonstration!
🚀 April 22, 2018 ♻ May 18, 2018reading 7 min reading

Warm-up Challenges ⚡ Repeated String

I'm posting about my solutions to the HackerRank challenges as a way to improve my learning, reinforce my knowledge, and establish an understanding of the concepts covered. If I help someone by sharing along the way, even better!

Repeated String is one of the initial challenges with 'EASY' difficulty.


What's the challenge?

Lilah has a string, s, of lowercase English letters that are repeated infinitely. Given an integer, n, find and return the number of letters a in the first n letters of Lilah's infinite string.

Example

If Lilah's string is s = 'abcac' and n = 10, the substring we are considering is abcacabcac, the first 10 characters of her infinite string. There are 4 occurrences of the letter a in the substring.

What do we have to do?

A function that returns an integer number of occurrences of the letter a in the prefix of length n in the infinitely repeating string.

Parameters
  • s = a string to repeat
  • n = the number of characters to consider

Sample Input

aba
10

Sample Output

7

Solution

function repeatedString(s, n) {
	let amount = parseInt(n / s.length),
		count = s.split('').filter(c => c === 'a').length,
		rest = s.slice(0, n % s.length).split('').filter(c => c === 'a').length;

	return amount * count + rest;
}

Logic

let amount = parseInt(n / s.length),
		count = s.split('').filter(c => c === 'a').length,
		rest = s.slice(0, n % s.length).split('').filter(c => c === 'a').length;

All logic is contained in these three variables:

amount is the amount of times the string s appears based on n of Lilah's infinite string;

count is the total amount of a contained in the string s

rest is the total amount of a contained in the string resulting from the remainder of dividing the given length n with the string s

Finally, I finalize the function by returning the final count. 🖖


🕵Extra Solutions

Other languages that I speak


💎 Ruby

def repeatedString(s, n)
	amount = n / s.size
	count = s.count('a')
	rest = s.slice(0, n % s.size).count('a')

	amount * count + rest
end

🐍 PYTHON 2 & 3

def repeatedString(s, n):
	amount = n // len(s)
	count = s.count('a')
	rest = s.count('a', 0, n % len(s))

	return amount * count + rest

golang GOLANG

func repeatedString(s string, n int64) int64 {
	var rest, amount, count int64
	rest = n % int64(len(s))
	amount = n / int64(len(s))
	count = int64(strings.Count(s, "a"))
	total := amount * count + int64(strings.Count(s[0:rest], "a"))

	return total
}

scala SCALA

def repeatedString(s: String, n: Long): Long = {
	val rest = n % s.length
	val amount = n / s.length
	val count = s.count(_ == 'a')
	val total = amount * count + s.substring(0, rest.toInt).count(_ == 'a')

	return total
}

javaJAVA 7 & 8

static int repeatedString(String s, long n) {
	long rest = n % s.length();
	long amount = n / s.length();
	long count = s.chars().filter(c -> c == 'a').count();
	long total = amount * count + s.substring(0, (int) rest).chars().filter(c -> c == 'a').count();

	return total;
}

php PHP

function repeatedString($s, $n) {
	$rest = substr_count(substr($s, 0, $n % strlen($s)), "a");
	$amount = intval($n / strlen($s));
	$count = substr_count($s, "a");

	return $amount * $count + $rest;
}

Thought: Life is a play that does not allow testing. So, sing, cry, dance, laugh and live intensely, before the curtain closes and the piece ends with no applause.
Charles Chaplin

💡 Latest Insights:

I don't claim that these answers are the best or most efficient, they are simply creations of my mind to solve the problem at that time. Probably today I would do different...
About MeProfessional ResumeWork MethodologyPersonal MemoriesCurriculum VitaePhotos & Travel
AREAS OF EXPERTISECTO as a ServiceCorporate ArchitectureSoftware & TechnologyFrontend DevelopmentBackend DevelopmentStrategy & ConsultingPlatform & DevSecOpsCustomer ExperienceAgile Culture
Innovation HubDistributed LT & BlockchainData Science & AnalyticsCybersecurity PlatformIntelligent AutomationAI & Machine Learning
COURSES & TRAININGBlockchain & Distributed LTCybersecurity PlatformIntelligent AutomationFrontend DevelopmentBackend DevelopmentPlatform & DevSecOpsAI & Machine LearningProgressive Web AppsAgile Culture
Hackathons & Prizes
DEVELOPED PROJECTSWEB3 / BLOCKCHAIN 2017 ~ 2024BitcoinEthereumRippleStarknetDIDInternet ComputerMarketplacesNFTHyperledgerWalletsDAODeFi DashboardsCrypto Checkoutsecurity tokensBANKS 2016 ~ 2021Santander TottaSafra S.A.Santander BrazilOld Projects 2000 ~ 2016SKYIntelACSNinho SoleilHP YouStoreHP Cartucho PirataMarlboro RacingMercedes BenzTortinhas AdriaChevrolet CaptivaGPA Sommeliers ClubUOL FinanceGafisaSprinterCasas BahiaJVCLew´laraPão de AçucarSchin RefrigerantesNescau 2.0PapaizTV CulturaSpacekidsBondage MusicMaison CriolaAntarctica OriginalNX ZeroSLK 2005Classe AClasse CPetrobrasBraskemNíveaJohnson & JohnsonAbyaraTIM (URA)NestléUOL
Blog PostsHACKERRANK 2017 ~ 2018#sockMerchant#countingValleys#repeatedstring#jumpingOnClouds#leftRotation
Contact Me
Terms and ConditionsPrivacy PolicyDisclaimer
This PWA was built with ❤ in my spare time 🤸‍♂️ through of the years...