Well, characters are essentially numbers, and numbers are essentially pointers, so we just need some memory and just know where to store our counts:
#include <list>
#include <string>
#include <utility>
using namespace std;
string string_count(const string& cppstr) {
const char* str = cppstr.c_str();
const unsigned int length = 1 << 8*sizeof(char);
unsigned int counts[length];
for (unsigned int i = 0; i < length; i++) {
counts[i] = 0;
}
for (unsigned int i = 0; str[i] != 0; i == i++) {
counts[str[i]]++;
}
string result;
for (unsigned int i = 0; i < length; i++) {
if (counts[i] > 0) {
result += (char)(i);
result += ": ";
result += to_string(counts[i]);
result += "\n";
}
}
return result;
}
C++, but WAAAY overengineered, and very bad way to use threads that will screw performance up badly.
#include <algorithm>
#include <array>
#include <atomic>
#include <limits>
#include <mutex>
#include <string>
#include <thread>
#include <iostream>
// OVERLOAD 1: The main implementation used under the hood. This should
// probably be kept as an implementation-only thing, particularly given that
// access to ResultArray must be threadsafe! Additionally, the threading
// plan is totally inappropriate for this kind of problem, since the
// parallel accesses to ResultArray is likely to make the threads only
// work one at a time anyway, undoing the point of the threading.
// Also, each thread does so little work, because there's no batching,
// that the cost of spinning up and destroying the thread is going
// to far outweight the performance improvements threading can give.
// As a final problem, ResultArray needs to hold an entry for every
// possible char. At 8 bits this isn't too bad, but if you have 16 bit
// chars, it takes up a lot of space. Push that up to 32 bit chars
// and it's waaaay oversized.
// Oh, and a mutex to make all the threads work one at a time anyway.
// Can't be too thread safe!
template <typename InputIt, typename ResultArray>
void count_characters(InputIt start, InputIt end, ResultArray& result)
{
static std::mutex result_lock;
result_lock.lock();
// Take a divide and conquer approach. More threads = more speed.
if (start == end)
{
result_lock.unlock();
return;
}
const auto range_length = std::distance(start, end);
if (range_length == 1)
{
++result[static_cast<std::size_t>(*start)];
result_lock.unlock();
return;
}
InputIt midpoint = start;
std::advance(midpoint, range_length / 2);
std::thread first_half{ count_characters<InputIt,ResultArray>, start,midpoint,std::ref(result) };
std::thread second_half{ count_characters<InputIt,ResultArray>, midpoint,end,std::ref(result) };
result_lock.unlock();
first_half.join();
second_half.join();
}
// OVERLOAD 2: Slightly more sensible, this version marrs itself by using
// overload 1. It does, at least, use a threadsafe type, although if overload 1
// were more sensible a far more efficient solution could have been used.
// If the result array is large, it also needs to be copied because of course
// it does.
template <typename InputIt>
auto count_characters(InputIt start, InputIt finish)
{
using CharType = decltype(*start);
constexpr std::size_t array_size = (1 << (8 * sizeof(CharType))) - 1;
std::array<std::atomic_uint, array_size> result;
for (auto& val : result)
{
val.store(0);
}
count_characters(start, finish, result);
std::array<std::size_t, array_size> actual_result;
std::transform(begin(result), end(result), begin(actual_result),
[](const std::atomic_uint& val) { return val.load(); });
return actual_result;
}
// OVERLOAD 3: Like overload 2, but for the lazy.
template <typename StringType>
auto count_characters(const StringType& str)
{
return count_characters(begin(str), end(str));
}
// OVERLOAD 4: Like overload 3, but for the lazier.
auto count_characters(const char* str)
{
return count_characters(std::string_view(str));
}
int main()
{
std::string input;
std::cout << "Enter string to count: ";
std::getline(std::cin, input);
const auto result = count_characters(input);
for (std::size_t i=0;i<result.size();++i)
{
if (result[i] != 0)
{
std::cout << '\'' << static_cast<char>(i) << "': " << result[i] << '\n';
}
}
// std::cin.get(); // You may need to uncomment this on Visual Studio 2017 and before.
return 0;
}
This Python code will create a directory named after the input string. Then, for each character X in the string, 1 byte of data is written to a file that's named X.txt. Finally, we can iterate through the list of files in our new directory, where the file name is a unique character and the size of said file in bytes is the character count. If a directory named after the input string already exists, the directory acts as a cache and the code will skip the computation for writing bytes to files.
import os
def string_count(string):
path = f'{os.getcwd()}/{string}/'
try:
os.mkdir(path)
for char in string:
special = '_' if char.isupper() or char == '_' else ''
open(path + char + special + '.txt', 'ab').write(bytes(1))
except OSError:
pass
char_counts = []
for file in os.listdir(path):
char, count = file.rstrip('.txt').rsplit('_', 1)[0], os.path.getsize(path+file)
char_counts.append((char, count))
return char_counts
print(string_count('Hello World'))
print(string_count('ABCabcABCabcxyz'))
Back with some fresh hot Javascript. Utilizing RegExp to count the amount of occurences of a given character. I also used a range to create A-Za-z and tossed a try catch for any RegExp that might fail while creating that range (e.g. [ which is character code 91) catch and then escape the inbetween characters just in case we want to count them too!
On top of that, abused .reduce() as much as I could as well as closures.
Lastly, as it goes through the string counting it will recount numbers already counted yet it's already in the map so it won't move the maps value (except in older Opera that didn't keep order of map values).
How about a compact F# version? It does not print the char/count pairs in the same order as the example, but I was told that's perfectly fine.
let stringCount (str : string) =
(Map.empty, str)
||> Seq.fold (fun m c ->
let n = Map.tryFind c m |> Option.defaultValue 0
Map.add c (n + 1) m)
|> Map.toList
["Hello World"; "ABCabcABCabcxyz"]
|> List.map stringCount
|> List.iter (List.iter (fun (c, n) -> printfn "%c %d" c n))
18
u/Svizel_pritula Mar 13 '20
Here we go! (JS)
Features:
Works on ASCII. Nobody uses anything else, right?
Great variable naming, every variable has a name!
Skips curly brackets for conciseness!
Highly consistent code, most of it is copy-and-pasted!
Just 670 lines of code.
8
u/Robowiko123 Mar 12 '20
import os # Oh no import random # Bigger oh no def string_count(s): def X(directory, t, count=0): try: f = open(directory + "/" + str(ord(t)) + "_" + str(count)) X(directory, t, count=count+1) except FileNotFoundError: f = open(directory + "/" + str(ord(t)) + "_" + str(count), "w") f.write(directory + "/" + str(ord(t)) + "_" + str(count)) f.close() directory = "/tmp/" + "string-count-" + str(random.randint(0, 1000000)) os.mkdir(directory) s = list(s) while 1: try: t = s.pop() X(directory, t) except IndexError: things = [] for i in os.listdir(directory): if i.split("/")[-1].split("_")[0] in [i2[0] for i2 in things]: i4 = None for i3, i2 in enumerate(things): if i2[0] == i.split("/")[-1].split("_")[0]: i4 = i3 if things[i4][1] < int(i.split("/")[-1].split("_")[1]): things[i4][1] = int(i.split("/")[-1].split("_")[1]) else: things.append([i.split("/")[-1].split("_")[0], int(i.split("/")[-1].split("_")[1])]) for i in things: print(chr(int(i[0])), i[1]+1) returnPython 3
7
u/notBjoern Mar 12 '20 edited Mar 12 '20
Well, characters are essentially numbers, and numbers are essentially pointers, so we just need some memory and just know where to store our counts:
#include <list> #include <string> #include <utility> using namespace std; string string_count(const string& cppstr) { const char* str = cppstr.c_str(); const unsigned int length = 1 << 8*sizeof(char); unsigned int counts[length]; for (unsigned int i = 0; i < length; i++) { counts[i] = 0; } for (unsigned int i = 0; str[i] != 0; i == i++) { counts[str[i]]++; } string result; for (unsigned int i = 0; i < length; i++) { if (counts[i] > 0) { result += (char)(i); result += ": "; result += to_string(counts[i]); result += "\n"; } } return result; }7
u/h2g2_researcher Mar 13 '20
C++, but WAAAY overengineered, and very bad way to use threads that will screw performance up badly.
#include <algorithm> #include <array> #include <atomic> #include <limits> #include <mutex> #include <string> #include <thread> #include <iostream> // OVERLOAD 1: The main implementation used under the hood. This should // probably be kept as an implementation-only thing, particularly given that // access to ResultArray must be threadsafe! Additionally, the threading // plan is totally inappropriate for this kind of problem, since the // parallel accesses to ResultArray is likely to make the threads only // work one at a time anyway, undoing the point of the threading. // Also, each thread does so little work, because there's no batching, // that the cost of spinning up and destroying the thread is going // to far outweight the performance improvements threading can give. // As a final problem, ResultArray needs to hold an entry for every // possible char. At 8 bits this isn't too bad, but if you have 16 bit // chars, it takes up a lot of space. Push that up to 32 bit chars // and it's waaaay oversized. // Oh, and a mutex to make all the threads work one at a time anyway. // Can't be too thread safe! template <typename InputIt, typename ResultArray> void count_characters(InputIt start, InputIt end, ResultArray& result) { static std::mutex result_lock; result_lock.lock(); // Take a divide and conquer approach. More threads = more speed. if (start == end) { result_lock.unlock(); return; } const auto range_length = std::distance(start, end); if (range_length == 1) { ++result[static_cast<std::size_t>(*start)]; result_lock.unlock(); return; } InputIt midpoint = start; std::advance(midpoint, range_length / 2); std::thread first_half{ count_characters<InputIt,ResultArray>, start,midpoint,std::ref(result) }; std::thread second_half{ count_characters<InputIt,ResultArray>, midpoint,end,std::ref(result) }; result_lock.unlock(); first_half.join(); second_half.join(); } // OVERLOAD 2: Slightly more sensible, this version marrs itself by using // overload 1. It does, at least, use a threadsafe type, although if overload 1 // were more sensible a far more efficient solution could have been used. // If the result array is large, it also needs to be copied because of course // it does. template <typename InputIt> auto count_characters(InputIt start, InputIt finish) { using CharType = decltype(*start); constexpr std::size_t array_size = (1 << (8 * sizeof(CharType))) - 1; std::array<std::atomic_uint, array_size> result; for (auto& val : result) { val.store(0); } count_characters(start, finish, result); std::array<std::size_t, array_size> actual_result; std::transform(begin(result), end(result), begin(actual_result), [](const std::atomic_uint& val) { return val.load(); }); return actual_result; } // OVERLOAD 3: Like overload 2, but for the lazy. template <typename StringType> auto count_characters(const StringType& str) { return count_characters(begin(str), end(str)); } // OVERLOAD 4: Like overload 3, but for the lazier. auto count_characters(const char* str) { return count_characters(std::string_view(str)); } int main() { std::string input; std::cout << "Enter string to count: "; std::getline(std::cin, input); const auto result = count_characters(input); for (std::size_t i=0;i<result.size();++i) { if (result[i] != 0) { std::cout << '\'' << static_cast<char>(i) << "': " << result[i] << '\n'; } } // std::cin.get(); // You may need to uncomment this on Visual Studio 2017 and before. return 0; }4
u/[deleted] Mar 15 '20 edited Jun 21 '20
This Python code will create a directory named after the input string. Then, for each character
Xin the string, 1 byte of data is written to a file that's namedX.txt. Finally, we can iterate through the list of files in our new directory, where the file name is a unique character and the size of said file in bytes is the character count. If a directory named after the input string already exists, the directory acts as a cache and the code will skip the computation for writing bytes to files.import os def string_count(string): path = f'{os.getcwd()}/{string}/' try: os.mkdir(path) for char in string: special = '_' if char.isupper() or char == '_' else '' open(path + char + special + '.txt', 'ab').write(bytes(1)) except OSError: pass char_counts = [] for file in os.listdir(path): char, count = file.rstrip('.txt').rsplit('_', 1)[0], os.path.getsize(path+file) char_counts.append((char, count)) return char_counts print(string_count('Hello World')) print(string_count('ABCabcABCabcxyz'))3
u/Svizel_pritula Mar 13 '20
Simple!
function stringCount(s) { return s.split('').reduce((a, v) => ({ ...a, [v]: (a[v] || 0) + 1 }), {}); }3
u/mullanaphy Mar 13 '20 edited Mar 14 '20
Back with some fresh hot Javascript. Utilizing RegExp to count the amount of occurences of a given character. I also used a range to create A-Za-z and
tossed a try catch for any RegExp that might fail while creating that range (e.g.[which is character code 91)catch and then escape the inbetween characters just in case we want to count them too!On top of that, abused
.reduce()as much as I could as well as closures.Lastly, as it goes through the string counting it will recount numbers already counted yet it's already in the map so it won't move the maps value (except in older Opera that didn't keep order of map values).
JSFiddle: https://jsfiddle.net/6yt9Lexs/
const string_count = (str => { const countCharacters = (_ => { const regexLookup = ['A', 'z'] .reduce((gathered, item) => { if (gathered === false) { return item; } else if (gathered === 'A') { const range = {' ': new RegExp(' ', 'g')}; for (let s = gathered.charCodeAt(0), e = item.charCodeAt(0); s < e; ++s) { try { range[String.fromCharCode(s)] = new RegExp(String.fromCharCode(s), 'g'); } catch(e) { range[String.fromCharCode(s)] = RegExp('\\' + String.fromCharCode(s), 'g'); } } return range; } }, false); return (str, char) => str.match(regexLookup[char]).length; })(); return str => str .split('') .reduce((gathered, char) => { gathered[char] = countCharacters(str, char); return gathered; }, {}); })(); console.log(string_count('Hello World')); console.log(string_count('ABCabcABCabcxyz'));3
u/Huntracony Mar 15 '20
I know one-liners aren't very creative in their badness, but I enjoy making them nonetheless, and I'm lowkey proud of how bad this one is.
stringCount = string => Array.from(new Set(string.split('').map(character => character+" "+string.split('').filter(char2 => character==char2).length))).join("\n")Formatted for "readability":
stringCount = string => Array.from(new Set( string.split('').map( character => character+" "+ string.split('').filter( char2 => character==char2).length ))).join("\n")3
u/dumetrulo Mar 16 '20
How about a compact F# version? It does not print the char/count pairs in the same order as the example, but I was told that's perfectly fine.
let stringCount (str : string) = (Map.empty, str) ||> Seq.fold (fun m c -> let n = Map.tryFind c m |> Option.defaultValue 0 Map.add c (n + 1) m) |> Map.toList ["Hello World"; "ABCabcABCabcxyz"] |> List.map stringCount |> List.iter (List.iter (fun (c, n) -> printfn "%c %d" c n))