Website Summary Files Commits Branches @commit @diff @stats
path: root / Sem. 15 / task2.cpp
blob: cc59a949a0a8cad7a1011d33bacbe9c9d22a58a9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include <iostream>
using namespace std;

int countWords(const char* text)
{
	bool wasLastCharSpace = true;
	int wordCount = 0;
	int len = strlen(text);

	for (int i = 0; i < len; i++)
	{
		if (wasLastCharSpace && text[i] != ' ' )
		{
			wordCount++;
			wasLastCharSpace = false;
		}
		else if (text[i] == ' ')
			wasLastCharSpace = true;
	}
	return wordCount;

}
int getWordLength(const char* text, int start)
{
	int len = 0;
	int index = start;

	while (text[index] != ' ' && text[index] != '\0')
	{
		index++;
		len++;
	}
	return len;
}

void copyChars(char* dest, const char* text, int start, int len)
{

	for (int i = start, index = 0; index < len; i++, index++)
		dest[index] = text[i];
	
	dest[len] = '\0';
}
void fillWords(char** words, const char* text)
{
	int len = strlen(text);
	int currentWordIndex = 0;

	for (int i = 0; i < len; i++)
	{
		if (text[i] == ' ')
			continue;

		int currentWordLen = getWordLength(text, i);

		words[currentWordIndex] = new char[currentWordLen + 1]; //(**)

		copyChars(words[currentWordIndex], text, i, currentWordLen);

		currentWordIndex++;
		i += currentWordLen;
	}
}

void swap(char** arr, int i, int j)
{
	char* wordPtr = arr[i];
	arr[i] = arr[j];
	arr[j] = wordPtr;
}
void selectionSort(char** arr, int len)
{
	for (int pos = 0; pos < len - 1; pos++)
	{
		int minIndex = pos;
		for (int i = pos; i < len; i++)
		{
			if (strcmp(arr[i], arr[minIndex]) < 0)  
				minIndex = i;
		}
		if (pos != minIndex)
			swap(arr, pos, minIndex);
	}
}

void free(char** words, int wordsCount)
{
	for (int i = 0; i < wordsCount; i++)
		delete[] words[i]; // (**)
	delete[] words; // (*)
}


bool hasDuplicatesWords(const char* text)
{
	int wordsCount = countWords(text);
	char** words = new char*[wordsCount]; // (*)
	fillWords(words, text);

	selectionSort(words, wordsCount);

	for (int i = 0; i < wordsCount - 1; i++)
	{
		if (strcmp(words[i], words[i + 1]) == 0)
			return true;
	}

	return false;
	
	free(words, wordCount);

}
int main()
{
	const char* text = "    hello friends.    how    are you frienYds. ";

	cout << hasDuplicatesWords(text);

}