-
Notifications
You must be signed in to change notification settings - Fork 1
/
palindrome.d
executable file
·66 lines (60 loc) · 1.52 KB
/
palindrome.d
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
import std.stdio;
import std.algorithm.mutation;
import std.algorithm.iteration;
import std.string;
bool isPalindrome(string input)
{
char[] inputCopy = chomp(input).dup;
reverse(inputCopy);
return input == inputCopy;
}
void buildPalindrome(string input)
{
char[] inputChs = chomp(input).dup;
int[char] occurrencesAA;
foreach (char c; inputChs)
{
int* v = (c in occurrencesAA);
if (v !is null)
*v += 1;
else
occurrencesAA[c] = 1;
}
int[char] oddsAA;
int[char] evensAA;
foreach (char c; occurrencesAA.byKey())
{
if (occurrencesAA[c] % 2 == 0)
evensAA[c] = occurrencesAA[c];
else
oddsAA[c] = occurrencesAA[c];
}
if (oddsAA.length > 1)
writeln(input, " cannot be made into a palindrome");
else
{
char[] buildStr;
foreach (char c; evensAA.byKey())
foreach (i; 0 .. evensAA[c] / 2)
buildStr ~= c;
char single = 'x';
foreach (char c; oddsAA.byKey())
{
if (oddsAA[c] > 1)
foreach (i; 0 .. oddsAA[c] / 2)
buildStr ~= c;
else
single = c;
}
char[] revCopy = buildStr.dup;
reverse(revCopy);
writeln("A palindromic form of ", input, " is ", buildStr ~ single ~ revCopy);
}
}
void main(string[] args)
{
if (isPalindrome(args[1]))
writeln(args[1], " is a palindrome");
else
buildPalindrome(args[1]);
}