Twenty years ago, during my first year in academia, my Pascal tutor set us some top-notch assignments.
Your mission:
Write a program which draws a diamond of the form illustrated below. The letter which is to appear at the widest point of the figure (E in the example) is to be specified as input data.
Here’s a scan of the original hand-out:
My original Pascal solution, which I prototyped using BBC Basic V, took less than a page of fan-fold listing paper and was implemented as a console application. 50% of the listing dealt with input validation and “do you want to run the program again?” code! I will convert the example line-by-line into C# for later publication here! Of course, were I to write it today, it should look very different!
I’d be keen to see your solutions, written in your choice of programming language. Novelty value for uniqueness in your choice of programming language may well be rewarded! Procedural, object-oriented, functional, dynamic, verbose, terse…the choice is yours!
“What’s in it for me?” you might ask?
Well, nothing really, a bit of kudos and the feeling of a job well done! However, I will offer the two best/novel UK-based solutions a much-coveted DDD polo shirt (modelled here!). My decision is final, colour may vary, size might not be the same size as you, yada yada, other legalese applies, etc.
Submission by comments here on this post, by e-mail (top right About Me), or via Twitter @camurphy please!
Over to you!
UPDATE: Comments seem to mangle the code formatting, it has been suggested that code is submitted either via e-mail or via http://pastebin.com/
makeDiamond := $E.
charValue := makeDiamond asInteger.
diff := charValue – 65 + 1.
diamondStream := WriteStream on: String new.
mid := 0.
diamondBlock := [:x |
start := diff – mid.
1
to: start
do: [:y | diamondStream nextPut: Character space].
diamondStream nextPut: x asCharacter.
1
to: mid * 2 – 1
do: [:y | diamondStream nextPut: Character space].
mid > 0 ifTrue: [diamondStream nextPut: x asCharacter].
diamondStream nextPut: Character cr].
65
to: charValue
do:
[:x |
diamondBlock value: x.
mid := mid + 1].
mid := mid – 2.
(65 to: charValue – 1)
reverseDo:
[:x |
diamondBlock value: x.
mid := mid – 1].
^diamondStream contents asText emphasizeAllWith: #family -> #courier
Ptython code using recursion
uppers=”ABCDEFGHIJKLMNOPQRSTUVWXYZ”
spaces=” ”
def diamond(current,max):
# print current,max,
char=uppers[current]
if current ==0:
a=spaces[0:max]+”A”
else:
a=spaces[0:max-current]+char+spaces[0:(current*2)-1]+char
print a
if current <max:
diamond(current+1,max)
print a
def main():
a=raw_input('enter letter :')
n=ord(a)-97
diamond(0,n)
return 0
if __name__ == '__main__': main()
hopefully the indentation will not be lost
Ptython code using recursion
reposted with spaces replaced with ~
uppers=”ABCDEFGHIJKLMNOPQRSTUVWXYZ”
spaces=”~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~”
def~diamond(current,max):
#~~~~print~current,max,
~~~~char=uppers[current]
~~~~if~current~==0:
~~~~~~~~a=spaces[0:max]+”A”
~~~~else:
~~~~~~~~a=spaces[0:max-current]+char+spaces[0:(current*2)-1]+char
~~~~print~a
~~~~if~current~<max:
~~~~~~~~diamond(current+1,max)
~~~~~~~~print~a
def~main():
~~~~a=raw_input('enter~letter~:')
~~~~n=ord(a)-97
~~~~diamond(0,n)
~~~~return~0
if~__name__~==~'__main__':~main()
#include
#include
#define PRINTLINE(x) do { buffer[cmax – (x)] = buffer[cmax + (x) – ‘A’ – ‘A’] = (x);\
printf(“%s\n”, buffer);\
buffer[cmax – (x)] = buffer[cmax + (x) – ‘A’ – ‘A’] = ‘ ‘;\
} while (0)
int main(int argc, char *argv[])
{
char cmax, i, buffer[52];
if (argc < 2 || (cmax = argv[1][0]) ‘Z’)
return 1;
memset(buffer, ‘ ‘, 51);
buffer[51] = 0;
for (i = ‘A’; i = ‘A’; i–)
PRINTLINE(i);
return 0;
}
#include
#include
#define PRINTLINE(x) do { buffer[cmax – (x)] = buffer[cmax + (x) – ‘A’ – ‘A’] = (x);\
printf(“%s\n”, buffer);\
buffer[cmax – (x)] = buffer[cmax + (x) – ‘A’ – ‘A’] = ‘ ‘;\
} while (0)
int main(int argc, char *argv[])
{
char cmax, i, buffer[52];
if (argc < 2 || (cmax = argv[1][0]) ‘Z’)
return 1;
memset(buffer, ‘ ‘, 51);
buffer[51] = 0;
for (i = ‘A’; i = ‘A’; i–)
PRINTLINE(i);
return 0;
}
your blog destroyed my piece of art
private void Diamond(StringWriter sw, char c)
{
int pivot = (int)(c – ‘A’);
for (int i = 0; i 0)
sw.Write(“{0}”, new String(‘ ‘, spaces));
sw.Write(“{0}”, (char)(c – (char)spaces));
if (interior > 0)
sw.Write(“{0}{1}”, new String(‘ ‘, interior), (char)(c – (char)spaces));
sw.WriteLine();
}
}
A single statement in python:
print (‘\n’.join (map (lambda x: ‘%s%c%s’ % (‘ ‘ * (x [1] – x [0] ), chr (x [0] ),
” if x [0] == 65 else ‘%s%c’ % (‘ ‘ * ( (x [0] – 65) * 2 – 1), chr (x [0] ) ) ),
(lambda x: zip (list (range (65, x + 1) ) + list (range (x – 1, 64, -1) ),
[x] * ( (x – 64) * 2 – 1) ) ) (ord (input () ) ) ) ) )
[…] ago (ahem!), my Pascal tutor set us a programming exercise. The full details are documented in this post. In a nutshell, we had to create a [Pascal] program that accepted a letter A thru Z and plotted a […]
In simple Python code:
l = raw_input()
lines = ord(l) – 64
for i in range(lines):
print ” “*(lines – i – 1)+chr(65+i)+(” “*(2*i-1))+ (“” if i == 0 else chr(65+i))
for i in range(lines-1,-1,-1):
print ” “*(lines – i – 1)+chr(65+i)+(” “*(2*i-1))+ (“” if i == 0 else chr(65+i))
can someone create efc formula in code form ?? where I can then create a active efc calculator on my website. ?
It is I rarely find in the Internet as entertainment and you have something interestinghere. Your page is lovely, your graphics highlight, not to mention that you refer to, the use of relevant what you’re talking. Of course you are a in a million, good!
Simple C code to print the diamond:
#include
void pline(char current) {
int dif = current – ‘a’;
for (int r = 1; r < 52; r++) {
if (r == (26 + dif)) { printf("%c",current); return; }
else if (r == (26 – dif)) printf("%c",current);
else printf(" ");
}
}
int main()
{
char e, current = 'a';
printf("Enter a letter: ");
scanf("%c",&e);
if (e 122) {
printf(“Please enter a lowercase letter\n”);
return 0;
}
int dif = e – ‘a’;
for (int i = 1; i < (dif * 2) + 2; i++) {
pline(current);
if (i <= dif) current++;
else current–;
printf("\n");
}
return 0;
}
Well, as long as it’s been posted in every other language, let’s get some brute force Java in here.
import java.util.Scanner;
public class SillyDiamond {
static final String alphabet = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println(“Select a letter for diamond: “);
String input = s.nextLine();
int letter = findLetter(input);
for(int i = 0; i < letter*2 + 1; i++)
{
DoWork(letter, i);
}
}
private static int findLetter(String x){
for(int i=0; i < alphabet.length(); i++)
{
if(x.toUpperCase().charAt(0) == alphabet.charAt(i))
{
return i;
}
}
return -1;
}
private static void DoWork(int letter, int current)
{
for(int i = 0; i < letter*2 + 1; i++)
{
int spaces1 = letter – current + 1;
if(current letter)
{
int spaces2 = current – letter;
if(i == spaces2 || i == letter*2 – spaces2)
{
System.out.print(alphabet.charAt(letter – spaces2));
} else
{
System.out.print(” “);
}
}
}
System.out.println();
}
}
Very simple one done in python, I am a beginner so am almost embarassed to post it after viewing some of the other solutions. There is absolutely no error checking and it only runs once. I will probably add error checking when I have time. It only runs once also
#!/usr/bin/python
userInput = input(“Enter a letter: “)
print(“””
A
B B
C C
D D”””,”\n”,” “, userInput, ” “, userInput,”””
G G
H H
I I
J
“””)
All of my white space was removed and some odd characters were posted, not sure how to mae it post differently.
Solution in python:
key = raw_input(‘Enter a letter:’).upper()
if len(key) > 1 or ord(key) 90:
—-print ‘Input not valid.’
else:
—-offset = ord(key) – 65
—-print (offset * ‘ ‘) + ‘A’
—-for i in range(1 – offset, offset):
——–print abs(i) * ‘ ‘ + chr(65 + (offset – abs(i))), \
————((offset – abs(i) – 1) * 2) * ” ” + chr(65 + (offset – abs(i)))
—-print (offset * ‘ ‘) + ‘A’
This comment system doesn’t escape > and < signs.
line 2 is: if len(key) > 1 or ord(key) < 65 or ord(key) > 90:
[…] for programming challenges today and ran across one that was more than twenty years old. It was an old scan of an assignment a fellow posted about his days in college taking Pascal. The idea behind the challenge is to write a program that takes user input for size, and builds a […]
Solution in VBScript using minimum possible lines of code.
Do: inp = Asc(Inputbox(“Uppercase Letter: “)) – 64: Loop Until inp > 0 And inp < 27
Msgbox main(1)
Function main (ltr)
main = main & spaces(ltr)
If ltr < inp Then main = main & Chr(13) & main(ltr + 1) & Chr(13) & spaces(ltr)
End Function
Function spaces (num)
For i = 1 to 2 * inp – 1
spaces = spaces & " "
If i = inp – (num – 1) Or i = inp + (num – 1) Then spaces = Left(spaces,i – 1) & Chr(num + 64)
Next
End Function