r/ProgrammingPrompts • • Jan 14 '15

[Easy] Letter Counter

Any language permitted.

Problem: Create a program where you input a string of characters, and output the number of each letter. Use vowels by default.

For example: asbfiusadfliabdluifalsiudbf -> a: 4 e: 0 i: 4 o: 0 u: 3

Bonus points: Make it command-line executable, with an optional mode to specify which letters to print.

17 Upvotes

60 comments sorted by

View all comments

1

u/erxyi Feb 15 '15

nasm x86 %define arg1 ebp+8 %define arg2 ebp+12 %define arg3 ebp+16

section .text
global count_letters

;count_letters(char *str,int strlen,  char *output)
;output has to be 26 el. table!

;void count_letters(char *str,int strlen,  char *output)
;output has to be 26 el. table!
count_letters:
	;starting stuff
	push ebp
	mov ebp, esp
	
	push ebx
	push ecx
	push edx
	push esi
	
	;using esi as base register for loading a character
	mov esi, [arg1]
	
	;moving strlen in proper place in order to use loop instruction
	mov ecx, [arg2]
	dec ecx
	
	;same as esi, but for output table
	mov ebx, [arg3]
	
main_loop:
	xor eax, eax
	mov al, [esi+ecx]
	cmp al, ' '
	je next
	
	sub eax, 'a' ; ['a';'z'] - 'a' = [0; 25]
	
	inc byte [ebx+eax]	
next:
	loop main_loop


	pop esi
	pop edx
	pop ecx
	pop ebx
	pop ebp
	ret

And simple driver: #include <stdio.h> #include <string.h> extern count_letters(char *str, int strlen, char *output);

int main(int argc, char **argv)
{
	if(argc!=2)
		return 1;
		
	char tab[26] = { 0 } ;
	char *vowels = "aeiyou";
	count_letters(argv[1], strlen(argv[1]), tab);
	
	int i = 6;
	
	while( --i >= 0 )
		printf("%c: %d ", vowels[i], tab[vowels[i]-'a']);
		
		
	puts("");
	return 0;
}

I'm assuming that all test strings are correct, ie. no [0x01; 'a'-1] etc.