Untitled

 avatar
unknown
golang
a year ago
1.7 kB
4
Indexable
package main

import (
	"fmt"
	"strings"
	"sync"
)

func main() {
	input := [][]string{
		{"ana", "parc", "impare", "era", "copil"},
		{"cer", "program", "leu", "alee", "golang", "info"},
		{"inima", "impar", "apa", "eleve"},
	}

	result := mapReduce(input, mapFunction, reduceFunction)
	fmt.Printf("Numărul mediu de cuvinte cu număr par de vocale și număr divizibil cu 3 de consoane: %.2f\n", result)
}

func mapReduce(input [][]string, mapFunc func([]string) int, reduceFunc func([]int) float64) float64 {
	var wg sync.WaitGroup
	mapResult := make(chan int, len(input))

	for _, words := range input {
		wg.Add(1)
		go func(words []string) {
			defer wg.Done()
			mapResult <- mapFunc(words)
		}(words)
	}

	go func() {
		wg.Wait()
		close(mapResult)
	}()

	reduceInput := []int{}
	for count := range mapResult {
		reduceInput = append(reduceInput, count)
	}

	return reduceFunc(reduceInput)
}

func mapFunction(words []string) int {
	count := 0
	for _, word := range words {
		if hasEvenVowels(word) && hasDivisibleBy3Consonants(word) {
			count++
		}
	}
	return count
}

func reduceFunction(counts []int) float64 {
	totalCount := 0
	for _, count := range counts {
		totalCount += count
	}
	return float64(totalCount) / float64(len(counts))
}

func hasEvenVowels(word string) bool {
	vowelCount := 0
	vowels := "aeiouAEIOU"
	for _, char := range word {
		if strings.ContainsRune(vowels, char) {
			vowelCount++
		}
	}
	return vowelCount%2 == 0
}

func hasDivisibleBy3Consonants(word string) bool {
	consonantCount := 0
	consonants := "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
	for _, char := range word {
		if strings.ContainsRune(consonants, char) {
			consonantCount++
		}
	}
	return consonantCount%3 == 0
}
Editor is loading...
Leave a Comment