Friday, April 11, 2008

Make a Distribution

Write a function which takes as input a string that consists only of the digits from 0 to 9 and outputs a distribution (like a grade distribution) showing how many times each digit appears in the string. Specifically, the following main

public static void main(String args[]){
String s = "01223334444566";
Distribution.doDistribution(s);
}
}

should produce the following output:

0:*
1:*
2:**
3:***
4:****
5:*
6:**
7:
8:
9:


We have an outer look that iterates over the numbers (chars) 0 to 9 and then we count how many times each one has occurred. Note that while the numbers in the example are in order, the instructions do not make that claim. A good programmer should realize that if the number are, in fact, always in order that we could re-write this program to use only one loop.


public class Distribution{
public static void doDistribution(String s){
for (char c = '0'; c <= '9' ; c++){
int index = 0;
int count = 0;
while ((index = s.indexOf(c,index)) != -1){
count++;
index++;
}
System.out.print(c + ":");
for (;count > 0; count--){
System.out.print("*");
}
System.out.println();
}
}

public static void main(String args[]){
String s = "01223334444566";
Distribution.doDistribution(s);
}
}


2 comments:

macellanius said...

I like your questions.
It's fun to solve each. :)

Here is my python code:


#!/usr/bin/env python

strr = "123444444456ttggfdeeaa~%/([AZDR F"

my_dict = {}


for i in range(33, 128):
how_many = 0
charac = chr(i)
#print charac
for symbol in strr:
if symbol==charac:
how_many+=1

my_dict[charac] = how_many

for i in range(33, 128):
charac = chr(i)
if my_dict[charac]!=0:
print charac, " : ", my_dict[charac]*"*"

________________________________________


This one actually counts all ascii symbols. It can also be limited to numbers.
By the way. It seems, I'll be hanging here on your blog and trying to solve those nice questions.
Regards...

Unknown said...

your method is not best case -- you are doing too many iterations -- splitting the string into a hash with a key would be better

ShareThis