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 25, 2018♻ May 21, 2018reading 9 min reading

Warm-up Challenges ⚡ Counting Valleys

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!

Counting Valleys is one of the initial challenges with 'EASY' difficulty.


What's the challenge?

Gary is an avid climber. It tracks your walks meticulously, paying close attention to small details like topography. During his last walk he took exactly n steps. For each step he took, he noted whether it was an up, U, or a down, D step. Gary's hikes start and end at sea level and each step up or down represents a 1 unit change in altitude. We define the following terms:

  • A mountain is a sequence of consecutive steps above sea level, starting with a rise from sea level and ending with a step to sea level.
  • A valley is a sequence of consecutive steps below sea level, starting with a step below sea level and ending with a step to sea level.

Given Gary's sequence of going up and down the steps during his last walk, find and print the number of valleys he walked. For example, if Gary's path is s = [DDUUUUDD], he will first enter a valley that is 2 units deep. Then he climbs a mountain 2 units high. Finally, he returns to sea level and finishes his walk.

What do we have to do?

A function that should return an integer with the number of valleys traveled by Gary.

Parameters
  • n = the number of steps Gary walked
  • s = a string describing your path

Sample Input

8
UDDDUDUU

Sample Output

1

Solution

function countingValleys(n, s) {

	let level = 0,
		valleys = 0,
		i = 0;
				
	for (i in s) {
		s.charAt(i) === 'U' ? level++ : level--;
		level === 0 && s.charAt(i) === 'U' ? valleys++ : 0;
	}

	return valleys;
}

Logic

let level = 0,
		valleys = 0,
		i = 0;

First I created three variables; level to track altitude; valleys to keep count of the number of valleys Gary has traversed; i to iterate the forloop;

for in

I've created a for loop that will go through the sequence of steps that Gary went through. for (i in s) {

The ternary condition if checks if Gary's step was up U: s.charAt(i) === 'U' ? if was, increment the count: level++ If not, decrement the count. level--

I then check that Gary is at sea level level === 0 and that the step was up && s.charAt(i) === 'U', in this case representing that he has just climbed a valley. valleys++

As at the beginning of the challenge we are informed that Gary starts and ends his walks at sea level, we can ignore knowing if he climbed a mountain and focus only on the valley 😎.

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


🕵Extra Solutions

Other languages that I speak


💎 Ruby

def countingValleys(n, s)
	level = 0
	valleys = 0

	s.each { | i | 
		i == 'U' ? level += 1 : level -= 1
		level == 0 && i == 'U' ? valleys += 1 : 0
	}

	valleys  
end

🐍 PYTHON 2 & 3

def countingValleys(n, s):
	level = 0
	valleys = 0
	
	for i in range(n):
		if (s[i] == 'U'):
			level += 1
		else:
			level -= 1

		if (level == 0 and s[i] == 'U'):
			valleys += 1
		
	return valleys

golang GOLANG

func countingValleys(n int32, s string) int32 {
	var level, valleys int32
	for _, i := range s {
		if i == 'U' {
			level++
		} else {
			level--
		}
		if level == 0 && i == 'U' {
			valleys++
		}
	}
	return valleys
}

scala SCALA

def countingValleys(n: Int, s: String): Int = {
	var level = 0
	var valleys = 0
					
	s.foreach (el =>  {
		if (el == 'U') {
			level += 1
		} else {
			level -= 1
		}
		if (level == 0 && el == 'U') {
			valleys += 1
		}
	})

	return valleys;
}

javaJAVA 7 & 8

static int countingValleys(int n, String s) {
	int level = 0,
			valleys = 0;
					
	for (int i = 0; i < n; i++) {
		if (s.charAt(i) == 'U')
			level++;
		else 
			level--;
		
		if (level == 0 && s.charAt(i) == 'U')
			valleys++;
	}

	return valleys;
}

php PHP

function countingValleys($n, $s) {
	$level = 0;
	$count = 0;

	for ($i = 0; $i < $n; $i++) {
		$s[$i] == 'U' ? $level++ : $level--;
		$level == 0 && $s[$i] == 'U' ? $valleys++ : 0;
	}
	return $valleys;
}

Thought: Nurture your mind with great thoughts, for you will never go any higher than you think.
Benjamin Disraeli

💡 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...