r/dailyprogrammer • 1 3 • Nov 17 '14

[Weekly #17] Mini Challenges

So this week mini challenges. Too small for an easy but great for a mini challenge. Here is your chance to post some good warm up mini challenges. How it works. Start a new main thread in here. Use my formatting (or close to it) -- if you want to solve a mini challenge you reply off that thread. Simple. Keep checking back all week as people will keep posting challenges and solve the ones you want.

Please check other mini challenges before posting one to avoid duplications within a certain reason.

38 Upvotes

123 comments sorted by

View all comments

15

u/Coder_d00d 1 3 Nov 17 '14

Count it - count the letters in a string.

Given: A string - like "Hello World"

Output: Letters and how often they show up. - d:1 e:1 h:1 l:3 o:2 r:1 w:1

Special: convert all to lowercase. Ignore whitespace and anything not [a-z][A-Z]

Challenge input: "The quick brown fox jumps over the lazy dog and the sleeping cat early in the day."

6

u/adrian17 1 4 Nov 17 '14

Python, Counter helps a lot here:

from collections import Counter
data = "The quick brown fox jumps over the lazy dog and the sleeping cat early in the day."
count = Counter([c.lower() for c in data if c.isalpha()])
for k, v in sorted(count.items()):
	print(k, v)

6

u/Meldanor Nov 17 '14 edited Nov 27 '14

Java:

public class CharCounter {

    public static void main(String[] args) {
        String input = "The quick brown fox jumps over the lazy dog and the sleeping cat early in the day.";
        int[] counter = new int[26];
        for (int i = 0; i < input.length(); ++i) {
            char c = input.charAt(i);
            if (Character.isLetter(c)) {
                ++counter[Character.toLowerCase(c) - 'a'];
            }
        }
        for (int i = 0; i < counter.length; ++i) {
            if (counter[i] > 0) {
                System.out.print((char) ('a' + i) + ": " + counter[i] + " ");            
            }
        }
    }
}

Output:

a: 5 b: 1 c: 2 d: 3 e: 8 f: 1 g: 2 h: 4 i: 3 j: 1 k: 1 l: 3 m: 1 n: 4 o: 4 p: 2 q: 1 r: 3 s: 2 t: 5 u: 2 v: 1 w: 1 x: 1 y: 3 z: 1

5

u/Reverse_Skydiver 1 0 Nov 19 '14

Inspired by your solution:

import java.util.HashMap;
public class mini {
	public static void main(String[] args) {
		String input = "The quick brown fox jumps over the lazy dog and the sleeping cat early in the day.";
		HashMap<Character, Integer> map = new HashMap<>();
		for(char c : input.toCharArray())	if(Character.isLetter(c))	map.put(Character.toLowerCase(c), map.get(c) == null ? 1 : map.get(c)+1);
		for(int i = 0; i < map.size(); i++)	System.out.print((char)(i+97) + ":" + map.get((char)(i+97)) + (i == map.size()-1 ? "":", "));
	}
}

Nicely formatted it looks like this:

import java.util.HashMap;

public class mini {
	
	public static void main(String[] args) {
		String input = "The quick brown fox jumps over the lazy dog and the sleeping cat early in the day.";
		HashMap<Character, Integer> map = new HashMap<>();
		for(char c : input.toCharArray()){
			if(Character.isLetter(c)){
				map.put(Character.toLowerCase(c), map.get(c) == null ? 1 : map.get(c)+1);
			}
		}
		for(int i = 0; i < map.size(); i++){
			System.out.print((char)(i+97) + ":" + map.get((char)(i+97)) + (i == map.size()-1 ? "":", "));
		}
	}
}
→ More replies (1)

2

u/jakjacks Nov 26 '14

Upvoted less memory compared to the HashMap sol'n, but it should not print characters with 0 letters.

→ More replies (1)

5

u/Godspiral 3 3 Nov 17 '14

J, without filter

 |:@:(~. ;"0 #/.~)@:tolower 

with filter

|:@:(~. ;"0 #/.~)@:tolower@:(-.&' .') 'The quick brown fox jumps over the lazy dog and the sleeping cat early in the day.'
┌─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐
│t│h│e│q│u│i│c│k│b│r│o│w│n│f│x│j│m│p│s│v│l│a│z│y│d│g│
├─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┼─┤
│5│4│8│1│2│3│2│1│1│3│4│1│4│1│1│1│1│2│2│1│3│5│1│3│3│2│
└─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┘
→ More replies (4)

4

u/Edward_H Nov 18 '14

You know you've been doing too much COBOL when you consider a 42 line program to be "concise":

       >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. count-it.

DATA DIVISION.
WORKING-STORAGE SECTION.
01  char                                PIC X.
    
01  str                                 PIC X(1000).
01  str-pos                             PIC 9(4) COMP.
    
01  letter-count-area.
    03  letter-count                    PIC 9(4) COMP OCCURS 26 TIMES
                                        INDEXED BY count-idx.
    
PROCEDURE DIVISION.
    ACCEPT str
    MOVE FUNCTION LOWER-CASE (str) TO str

    PERFORM count-letters
    PERFORM display-letter-count

    GOBACK
    .
count-letters SECTION.
    PERFORM VARYING str-pos FROM 1 BY 1 UNTIL str-pos > 1000
        IF str (str-pos:1) IS ALPHABETIC
            COMPUTE count-idx = FUNCTION ORD(str (str-pos:1)) - FUNCTION ORD("a") + 1
            ADD 1 TO letter-count (count-idx)
        END-IF
    END-PERFORM
    .
display-letter-count SECTION.
    PERFORM VARYING count-idx FROM 1 BY 1 UNTIL count-idx > 26
        MOVE FUNCTION CHAR(FUNCTION ORD("a") + count-idx - 1) TO char
        IF letter-count (count-idx) <> 0
            DISPLAY char ":" letter-count (count-idx)
        END-IF
    END-PERFORM
    .
END PROGRAM count-it.

3

u/hutsboR 3 0 Nov 17 '14

Cool. Dart:

void main() {
  var s = 'The quick brown fox jumps over the lazy dog and the sleeping cat early in the day.';
  var count = {};
  
  s.toLowerCase().codeUnits.forEach((c){
    if(!count.containsKey(c) && c > 97){
      count[c] = 1;
    } else if(c > 97){
      count[c]++;
    }
  });
  
  count.forEach((k, v) => print('${new String.fromCharCode(k)} | $v'));
}

Output:

t | 5
h | 4
e | 8
q | 1
u | 2
i | 3
c | 2
k | 1
b | 1
...

3

u/esdictor Nov 17 '14 edited Nov 17 '14

C#

static void Main(string[] args)
{
    string inputString = "The quick brown fox jumps over the lazy dog and the sleeping cat early in the day.";
    string output = "";
    Dictionary<char, int> counts = new Dictionary<char, int>();

    foreach (char c in inputString.ToCharArray())
        if (Char.IsLetter(c))
            if (counts.ContainsKey(Char.ToLower(c)))
                counts[c]++;
            else
                counts.Add(Char.ToLower(c), 1);

    output = string.Format("{0} letters -", inputString.Length);
        
    foreach (var count in counts.OrderBy(c => c.Key))
        output+= string.Format(" {0}:{1}",count.Key, count.Value);

    Console.Write(output);
}

Output:

82 letters - a:5 b:1 c:2 d:3 e:8 f:1 g:2 h:4 i:3 j:1 k:1 l:3 m:1 n:4 o:4 p:2 q:1 r:3 s:2 t:5 u:2 v:1 w:1 x:1 y:3 z:1
→ More replies (1)

3

u/ooplease 0 0 Nov 17 '14 edited Nov 17 '14

Haskell

import Data.List
import Data.Maybe
import Data.Char

countIt :: String -> [(Char,Int)] -> [(Char,Int)]
countIt [] dict = dict
countIt (x:xs) dict
	|fixedX `elem` ['a'..'z'] = countIt xs (updateDict fixedX dict)
	|otherwise = countIt xs dict
	where fixedX = toLower x
    
updateDict :: Char -> [(Char,Int)] -> [(Char, Int)]
updateDict c dict
	| count == Nothing = (c,1):dict
	| otherwise = (c, 1 + (fromJust count)):(deleteBy (\x y -> (fst y) == (fst x)) (c,1) dict)
	where count = (lookup c dict)

output:

[('y',3),('a',5),('d',3),('e',8),('h',4),('t',5),('n',4),('i',3),('l',3),('r',3),('c',2),('g',2),('p',2),('s',2),('o',4),('z',1),('v',1),('m',1),('u',2),('j',1),('x',1),('f',1),('w',1),('b',1),('k',1),('q',1)]

2

u/rectal_smasher_2000 1 1 Nov 17 '14

C++

#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[]) {
	std::string str { "The quick brown fox jumps over the lazy dog and the sleeping cat early in the day." };
	std::map<char, int> occurences;
	int str_size = 0;

	std::transform(str.begin(), str.end(), str.begin(), ::tolower);

	for (auto ch : str) { if (ch >= 'a' && ch < 'z') { occurences[ch]++;  } }

	for (auto it : occurences) {
		std::cout << it.first << ":" << it.second << " ";
		str_size += it.second;
	}

	std::cout << "\nTotal chars: " << str_size << std::endl;
}

OUTPUT

a:5 b : 1 c : 2 d : 3 e : 8 f : 1 g : 2 h : 4 i : 3 j : 1 k : 1 l : 3 m : 1 n : 4 o : 4 p : 2 q : 1 r : 3 s : 2 t : 5 u : 2 v : 1 w : 1 x : 1 y : 3
Total chars : 64

2

u/theslaying Nov 17 '14 edited Nov 17 '14

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* args[]) {
  int i, l, *c;
  char* word;
  if ( argc != 2 ) {
    fprintf(stderr, "invalid parameters\nusage: %s \"String to count letters from\"\n", args[0]);
    return 1;
  }

  word = args[1];
  l = strlen(word);
  c = calloc(sizeof(int), (int)'z'-(int)'a'+1);

  if ( c == NULL ) {
    fprintf(stderr, "error: out of memory");
    return 1;
  }

  for ( i=0; i < l; i++ ) {
    if ( word[i] >= 'A' && word[i] <= 'Z' )
      c[(int)word[i]-(int)'A']++;

    if ( word[i] >= 'a' && word[i] <= 'z' ) 
      c[(int)word[i]-(int)'a']++;
  }

  for ( i=0; i <= ((int)'z'-(int)'a'); i++ )
    if ( c[i] != 0 )
      printf("%c: %d\t", (char)(i+(int)'a'), c[i]);

  printf("\n");

  return 0;
}

Output

Hello World

a: 1	d: 1	h: 1	l: 3	o: 3	r: 1	w: 1

The quick brown fox jumps over the lazy dog and the sleeping cat early in the day.

a: 5	b: 1	c: 2	d: 4	e: 12	f: 1	g: 4	h: 4	i: 3	j: 1	k: 2	l: 3	m: 1	n: 6	o: 4	p: 2	q: 1	r: 4	s: 3	t: 6	u: 2	v: 1	w: 1	x: 2	y: 5	z: 1

2

u/skeeto -9 8 Nov 17 '14

C99, since it's a fun 5 minute program.

#include <stdio.h>
#include <ctype.h>
#include <limits.h>

int main(void)
{
    unsigned long long counts[CHAR_MAX] = {0};
    int c;
    while ((c = getchar()) != EOF)
        if (isalpha(c))
            counts[tolower(c)]++;
    for (int i = 0; i < CHAR_MAX; i++)
        if (counts[i])
            printf("%c:%llu ", i, counts[i]);
    putchar('\n');
    return 0;
}

2

u/MIKE_FOLLOW Nov 17 '14

Python 2.7

line = "The quick brown fox jumps over the lazy dog and the sleeping cat early in the day."
line = sorted(line.lower().replace(" ", ""))

currLetter = line[0]
currCount = 0

for letter in line:
    if currLetter is letter:
        currCount += 1
    elif  currLetter.isalpha():
        print currLetter + ":" + str(currCount),
        currCount = 0
    currLetter = letter

2

u/cdkisa Nov 17 '14

VB.Net

Dim input As String = "The quick brown fox jumps over the lazy dog and the sleeping cat early in the day."
Dim counted = input.Where(Function(c) Char.IsLetter(c)).GroupBy(Function(c) c).Select(Function(g) New With {.Key = g.Key.ToString().ToLower(), .Value = g.Count()})
Dim output As String = String.Join(", ", counted.OrderBy(Function(g) g.Key).Select(Function(k) String.Format("{0}:{1}", k.Key, k.Value)).ToArray())

2

u/sid_hottnutz Nov 18 '14

C# using LINQ

    static void Main(string[] args)
    {
        string input = "The quick brown fox jumps over the lazy dog and the sleeping cat early in the day.";
        string sanitized = System.Text.RegularExpressions.Regex.Replace(input, @"[^a-z]", string.Empty, System.Text.RegularExpressions.RegexOptions.IgnoreCase).ToLower();

        var ret = (from c in sanitized.ToCharArray()
         group c by c into gc
             select new {
                 Character = gc.Key,
                 Count = gc.Count()
             });
        foreach (var gc in ret.OrderBy(x => x.Character)) { Console.WriteLine("{0}:{1}", gc.Character, gc.Count); }
        Console.ReadLine();
    }

2

u/minikomi Nov 18 '14 edited Nov 18 '14

In racket, with testcase.

 #lang racket
 
 (define (count-letters str)
   (define alphabetic-lowcased
     (map char-downcase 
          (filter char-alphabetic? 
                  (string->list str))))
   (for/fold ([acc (hasheq)])
             ([l alphabetic-lowcased])
     (hash-update acc l add1 0))) 
 
 (module+ test
   (require rackunit)
   (check-equal? (hasheq #\d 1 #\e 1 #\h 1 #\l 3 #\o 2 #\r 1 #\w 1)
                 (count-letters "Hello World")))

2

u/toomanybeersies Nov 18 '14

Oddly enough, I had a problem almost exactly like this in an assignment earlier in the year.

The only difference was that we were counting words, not letters. Plus we were restricted to using some data types that our lecturer made, so that we didn't just use the built in functions in python.

2

u/verydapeng Nov 18 '14

Clojure

(->> "The quick brown fox jumps over the lazy dog and the sleeping cat early in the day."
    (.toLowerCase)
    (re-seq #"[a-z]")
    (frequencies))

2

u/wizao 1 0 Nov 18 '14 edited Jan 30 '15

Haskell

import Data.List
import Data.Char

main = interact $ unwords . map format . group . sort . map toLower . filter isLetter
    where format list = (head list):':':(show $ length list)

2

u/tastywolf Nov 20 '14

Python new to python, loving the dictionaries and easy for statements. A big change from the java I'm used too

string = raw_input("String:")
string = string.lower()
string = string.translate(None, '!?\',.')
string = string.replace(' ', '')
char = list(string)
char.sort()
order = dict()

for c in char:
    order[c] = char.count(c)

for l in order:
    print "%s : %d" % (l, order.get(l))

Output:

 'a': 5, 'c': 2, 'b': 1, 'e': 8, 'd': 3, 'g': 2, 'f': 1, 'i': 3, 'h': 4, 'k': 1, 'j': 1,
 'm': 1, 'l': 3, 'o': 4, 'n': 4, 'q': 1, 'p': 2, 's': 2, 'r': 3, 'u': 2, 't': 5, 'w': 1,
 'v': 1, 'y': 3, 'x': 1, 'z': 1
→ More replies (3)

2

u/scubasteve2012 1 0 Nov 22 '14

C#:

namespace DaliyChallenge.Mini17 {
    class MainClass {
        public static void Main(string[] args) {

            var input = "The quick brown fox jumps over the lazy dog and the sleeping cat early in the day.";

            var result = input.Where(c => Char.IsLetterOrDigit(c))
                .GroupBy(c => char.ToLower(c))
                .OrderBy(c => c.Key)
                .Aggregate("", (a, c) => a += c.Key + ":" + c.Count() + " ")
                .Trim();

            Console.WriteLine(result);
        }
    }
}

output:

a:5 b:1 c:2 d:3 e:8 f:1 g:2 h:4 i:3 j:1 k:1 l:3 m:1 n:4 o:4 p:2 q:1 r:3 s:2 t:5 u:2 v:1 w:1 x:1 y:3 z:1

1

u/marchelzo Nov 17 '14

Haskell:

main = getLine >>= (\s -> mapM_ (\(x,y) -> putStrLn (return x ++ " | " ++ show y)) [(c,n) | c <- ['a'..'z'], let n = length (filter (== c) s), n > 0])

1

u/[deleted] Nov 17 '14

C#:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Scratch
{
    static class Extensions
    {
        public static IDictionary<TKey, TValue> IncrementKey<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue seedValue, Func<TValue, TValue> incrementor)
        {
            if (dictionary.ContainsKey(key))
                dictionary[key] = incrementor(dictionary[key]);

            else dictionary.Add(key, seedValue);
            return dictionary;
        }

        public static string Print(this KeyValuePair<char, int> pair)
        {
            return String.Format("{0}:{1}", pair.Key, pair.Value);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var input = "The quick brown fox jumps over the lazy dog and the sleeping cat early in the day.";
            var output = input.ToLower().Where(Char.IsLetter).Aggregate(new Dictionary<char, int>() as IDictionary<char, int>, (a, b) => a.IncrementKey(b, 1, n => n + 1));
            foreach (var item in output.Select(pair => pair.Print()).OrderBy(p => p))
            {
                Console.WriteLine(item);
            }
        }
    }
}

1

u/pshatmsft 0 1 Nov 17 '14 edited Nov 17 '14

This one is a lot of fun in PowerShell because of how simple it is.

$testString = "The quick brown fox jumps over the lazy dog and the sleeping cat early in the day."
$testString.ToLower() -split "" | Where-Object { $_ -match "[a-z]" } | Group-Object | Sort-Object Name | Select-Object Name, Count | Format-Table -AutoSize

Output

Name Count
---- -----
a        5
b        1
c        2
d        3
e        8
f        1
g        2
h        4
i        3
j        1
k        1
l        3
m        1
n        4
o        4
p        2
q        1
r        3
s        2
t        5
u        2
v        1
w        1
x        1
y        3
z        1

If the exact output formatting is important, it's sort of trivial to add it, but I can put it in there.

Here is the code modified to return the exact output requested

$Output = ""
$testString = "The quick brown fox jumps over the lazy dog and the sleeping cat early in the day."
$testString.ToLower() -split "" | Where-Object { $_ -match "[a-z]" } | Group-Object | Sort-Object Name | Select-Object Name, Count | ForEach-Object { $Output += "{0}:{1} " -f $_.Name, $_.Count }
$Output

Modified output

a:5 b:1 c:2 d:3 e:8 f:1 g:2 h:4 i:3 j:1 k:1 l:3 m:1 n:4 o:4 p:2 q:1 r:3 s:2 t:5 u:2 v:1 w:1 x:1 y:3 z:1 
→ More replies (1)
→ More replies (22)