ALLAN AVELARTechnology Solutions
🍰Good Afternoon,<username class="jsx-708122429">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 21, 2018 ♻ May 17, 2018reading 8 min reading

Warm-up Challenges ⚡ Sock Merchant

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!

Sock Merchant is one of the initial challenges with 'EASY' difficulty.


What's the challenge?

John works at a clothing store. He has a big pile of socks that he must sort by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with the corresponding colors exist.

For example, there are n = 7 socks with colors ar = 1, 2, 1, 2, 1, 3, 2. There is a pair of color 1 and a pair of color 2. There are three odd socks, one of each color. The number of pairs is 2.

What do we have to do?

A function that should return an integer representing the number of matching pairs of socks available.

Parameters
  • n = the number of socks in the pile
  • ar = the colors of each sock in an array

Sample Input

9
10 20 20 10 10 30 50 10 20

Sample Output

3

Solution

function sockMerchant(n, ar) {

	let socks = {},
		count = 0,
		i = 0;

	for (i = 0; i < n; i++) {
		if (ar[i] in socks) {
			socks[ar[i]] += 1;
		} else {
			socks[ar[i]] = 1;
		}
	}

	Object.keys(socks).map(el => {
		count += ~~(socks[el] / 2);
	})

	return count;
}

Logic

let socks = {},
	count = 0,
	i = 0;

First I created three variables; socks is an object that records the count of each type of sock; count to keep count of the number of pairs of socks; i to iterate the forloop;

for loop

I've created a for that will loop through the sock color array. It will iterate n times, which is the given amount of socks on the stack. for (var i = 0; i < n; i++)

The condition if checks if the color exists in our object socks: if (ar[i] in socks)
If it exists, increment the count for that color by one: socks[ar[i]] += 1;
If not, create a key with that color and set it to 1. socks[ar[i]] = 1;

After the socks have been counted, execute a map on the socks object, so an element will be separated for each key: Object.keys(socks).map(el => {

Then I calculate the number of pairs by dividing the number of "socks" of one color socks[el] / 2 and then apply the answer, two tildes (bitwise NOT).

I used the bitwise NOT as a substitute for the Math.floor(), as it performs the same operation much faster 😎, as you can check in https://jsperf.com/jsfvsbitnot

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


🕵Extra Solutions

Other languages that I speak


💎 Ruby

def sockMerchant(n, ar)
	socks = Hash.new { | hash, key | Hash[key] = 0 }
	count = 0

	ar.each { | color | socks[color] += 1 }
	socks.each_value { | el | count += (el / 2) }

	count
end

🐍 PYTHON 2 & 3

def sockMerchant(n, ar):
	socks = collections.Counter(ar)
	count = 0

	for el in socks:
		count += socks[el] // 2
			
	return count

golang GOLANG

func sockMerchant(n int32, ar []int32) int32 {
	var count, i int32

	socks := make(map[int32]int32)
	for i = 0; i < n; i++ {
		socks[ar[i]]++
	}
	for _, el := range socks {
		count += (el / 2)
	}
	return count
}

scala SCALA

def sockMerchant(n: Int, ar: Array[Int]): Int = {
	val socks = ar.groupBy(c => c)
	val pairs = socks.map(el => el._2.length / 2)
	val count = pairs.sum
	return count;
}

javaJAVA 7 & 8

static int sockMerchant(int n, int[] ar) {
	HashSet<Integer> socks = new HashSet<Integer>();
	int count = 0;
					
	for (Integer i:ar) {
		if (socks.contains(i))
			socks.remove(i);
			count++;
		else
			socks.add(i);
	}
	return count;
}

php PHP

function sockMerchant($n, $ar) {
	$socks = array_count_values($ar);
	$count = 0;

	foreach ($socks as $el) {
		$count += intdiv($el, 2);
	}
	return $count;
}

Thought: Having faith is to sign a blank sheet of paper and let God write what he wants.
Santo Agostinho

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