QUICK

QUICK

WRITE A PROGRAM IN YOUR FAVORITE LANGUAGE THAT CREATES A SORTED HISTOGRAM FOR AN ARRAY OR LIST AS (ELEMENT1 : COUNT, ELEMENT2 : COUNT, ...)

OR THIS BIRD IS GONNA STAB YOU

Other urls found in this thread:

haskell.org/ghc/
catb.org/esr/writings/unix-koans/ten-thousand.html
en.wikipedia.org/wiki/Anaphoric_macro
gist.github.com/ikbear/4038654
twitter.com/AnonBabble

FUCKING PYTHON BLACK MAGIC HOLY CRAP

def histogram(sequence):
return sorted([(element,sequence.count(element)) for element in set(sequence)],key=lambda e:e[1],reverse=True)

print(histogram(['y','o','u','g','u','n','n','a','g','e','t','s','t','a','b','b','e','d','m','a','t','e']))

FUCK YOU OP
I wanted to post such a thread

GET TO FUCKING WORK

...

Nice integers,
BIRD = """
def histogram(sequence):
return sorted([(element,sequence.count(element)) for element in set(sequence)],key=lambda e:e[1],reverse=True)

print(histogram(['y','o','u','g','u','n','n','a','g','e','t','s','t','a','b','b','e','d','m','a','t','e']))
"""

exec BIRD

You're hired.

yourMomLikes :: (Eq longDicks) => [longDicks] -> [longDicks]
yourMomLikes [] = []
yourMomLikes (the:bbc)
| any (== the) bbc = yourMomLikes bbc
| otherwise = the:(yourMomLikes bbc)

yourMomLoves :: (Eq longDicks) => [longDicks] -> longDicks -> (longDicks, Int)
yourMomLoves [] jizz = (jizz, 0)
yourMomLoves (black:cock) jizz
| jizz == black = (jizz, 1 + snd (yourMomLoves cock jizz))
| otherwise = (jizz, snd (yourMomLoves cock jizz))

gimmeABlackBaby :: (Eq longDicks) => [longDicks] -> [(longDicks, Int)]
gimmeABlackBaby tyronesCock = map (yourMomLoves tyronesCock) (yourMomLikes tyronesCock)

rle : {(count;first) @\:/: (where not =':[x]) _ x}

i think i saw this slut had sex with a doge

What's in the array killer bird, elements of any type?

link?

don't have a link rn, but she's part of Mexzoo.
she was also wearing the same dress and the same shoe.

# le ruby code artisan hipster shit meme
input = %w(bird bird bird bird is the word A-well-a bird bird bird bird is the word)
result = input.each_with_object(Hash.new(0)) { |word, counts| counts[word] += 1 }


Hehe, nice to see someone remebers my immature code from the last thread..

You're a genius, and I respect you.

I'M GONNA DO IT TOMORROW BIRD I SWEAR

#include
#include
#define HISTOGRAM_SIZE 5

typedef struct
{
char value;
int count;
} element;

typedef struct
{
element **elems;
int size, fill;
} histogram;

histogram *init_histogram(int size)
{
histogram *h = malloc(sizeof(histogram));
h->size = size;
h->fill = 0;
h->elems = malloc(sizeof(element*) * size);
return h;
}

void add_value_to_histogram(histogram *h, char value)
{
boolean value_found = FALSE;

if (h->fill == h->size)
{
h->elems = realloc(h->elems, sizeof(element*) * h->size * 2);
h->size *= 2;
}

for (int i = 0; i < h->fill; i++)
{
if (h->elems[i]->value == value)
{
h->elems[i]->count++;
int j = i - 1;
while (j >= 0 && h->elems[i]->count == h->elems[j]->count + 1)
j--;
if (j+1 != i)
{
element temp_elem;
temp_elem.value = h->elems[i]->value;
temp_elem.count = h->elems[i]->count;
h->elems[i]->value = h->elems[j+1]->value;
h->elems[i]->count = h->elems[j+1]->count;
h->elems[j+1]->value = temp_elem.value;
h->elems[j+1]->count = temp_elem.count;
}
value_found = TRUE;
break;
}
}

if (!value_found)
{
h->elems[h->fill] = malloc(sizeof(element));
h->elems[h->fill]->value = value;
h->elems[h->fill]->count = 1;
h->fill++;
}

}

void print_histogram(histogram *h, size_t size)
{
putchar('[');
for (int i = 0; i < size; i++)
if (i != size-1)
printf("(%c, %d), ", h->elems[i]->value, h->elems[i]->count);
else
printf("(%c, %d)", h->elems[i]->value, h->elems[i]->count);
putchar(']');
}

int main()
{
char array_of_characters[] = {'a', 'b', 'c', 'd', 'e', 'a', 'c', 'f', 'f', 'g', 'g', 'g', 'g', 'a', 'b', 'c', 'z', 'z', 'z', 'c', 'f', 'h', 'h', 'g', 'g', 'g'};

histogram *h = init_histogram(HISTOGRAM_SIZE);
for (int i = 0; i < sizeof(array_of_characters)/sizeof(array_of_characters[0]); i++)
{
add_value_to_histogram(h, array_of_characters[i]);
print_histogram(h, h->fill);
putchar('\n');
}

print_histogram(h, h->fill);

free(h);
}

>hurr C is da best
I think I'm going to be sick.

It's [ c o d e ] [ / c o d e], pajeet.

Why not do it with a linked list?

Awwww....
:3

Nah, I'm rather bad actually.
But hey, I keep trying..

>Nah, I'm rather bad actually.
>But hey, I keep trying..

That's all of us, user. That's all of us...

What is this language?

True dat.

Just take it and leave, Stabby Bird, I don't want any trouble!

using System;
using System.Collections.Generic;

namespace StabbyBirdSortedHistogram
{
class Program
{
static void HistogramIncrement(ref List histogram, string key)
{
for (int i = 0; i < histogram.Count; i++) {
if (String.Equals(histogram[i].Key, key)) {
histogram[i] = new KeyValuePair(histogram[i].Key, histogram[i].Value + 1);
return;
}
}

histogram.Add(new KeyValuePair(key, 1));
}

static int HistogramCompare(KeyValuePair x, KeyValuePair y)
{
return y.Value.CompareTo(x.Value);
}

static void Main(string[] args)
{
var items = new List();
var histogram = new List();

items.AddRange(args);

if (items.Count == 0) {
Console.WriteLine("The OP is a faggot");
return;
}

foreach (string item in items) {
HistogramIncrement(ref histogram, item);
}

histogram.Sort(HistogramCompare);
Console.WriteLine("(");

foreach (KeyValuePair pair in histogram) {
Console.WriteLine(" " + pair.Key + " : " + pair.Value + ",");
}

Console.WriteLine(")");
}
}
}

Since OP used Python I decided to go with C# instead. This was more of a challenge for me, being less familiar with the language, but it was a lot of fun. By the way I'm loving these threads, been looking forward to it all day.

q

Isn't this more efficient? Adding would be O(n) anyway but using the list would require calling malloc more often

map (head &&& length) . group . sort

took me 5 seconds or so. untested

I'm sure there's a more concise way to do it, but this was the first thing I thought of.
const charCount = new Map()
process.argv[0].split().forEach(letter => (charCount.has(letter)) ? charCount.set(letter, charcount.get(letter) + 1)) : charCount.set(letter, 1))
const sortedHistogram = Array.from(charCount.entries()).sort((left, right) => right[1] - left[1]).map(element => {element[0]: element[1]})

Explain this shit.

Wow, q looks sweet.

Another language to put on my list..

λ ghci
GHCi, version 7.10.3: haskell.org/ghc/ :? for help
λ "hello world"
"hello world"
λ sort it
" dehllloorw"
λ group it
[" ","d","e","h","lll","oo","r","w"]
λ map (head &&& length) it
[(' ',1),('d',1),('e',1),('h',1),('l',3),('o',2),('r',1),('w',1)]
λ :t (&&&)
(&&&) :: Arrow a => a b c -> a b c' -> a b (c, c')
λ (head &&& tail) "foo"
('f',"oo")
λ

what modules are you using?

Ahh, I see. Data.List nvm.

Hmm, I need to practice my regexes...

There's no regex here. Regex has no place in programming IMO.

i'm not doing your homework rajesh.

The only special thing about your code is the group function, which is a Haskell version of a group regex.

A call to malloc is insignificant, also use calloc

What makes you think this is homework?

I don't have any favourite language, sorry bird.

One of us is going to get stabbed and it's not me.

yesterday was harder
list = [ 1, 2, 3, 4, 5, 6, 1, 1, 2, 3, 3, 3 ]

dict = {}
for item in list:
if item in dict:
dict[item] += 1
else:
dict[item] = 1

print(dict)

I was going to do this in C, but C64 BASIC it is.
2 rem load data
3 size=19
5 dim a(size)
10 data 9, 2, 3, 5, 1
15 data 2, 4, 7, 4, 4
20 data 2, 6, 7, 7, 2
25 data 2, 3, 4, 5, 0
30 for i=0 to 19
40 read a(i)
50 next i
55 rem sort
60 for i=1 to size
70 j=i
80 if j

input

ah, shit, it's not formatted correctly, forgot to check the OP on that
oh well, I was gonna get stabbed anyway because this sure as fuck isn't my favorite language

Ah yeah. Javascript is great.

>sorted

Python

Python dictionaries are sorted

They are in javascript as well. The items are dictionary keys whose count is the value.

dict = {}
for item in list:
dict[item] += 1

wouldn't that work, shouldn't it start as 0 or are there some type things going on.

Damn, that's.. short!
O_O"

I copied your approach into Ruby:

"hello world"
.split("")
.group_by { |i| i }
.map { |k,v| [k, v.length] }

QUICK DO MY HOMEWORK!!!!
you posted this thread a few days ago with a different question do your own homework

>not hopping on the meme train

>which is a Haskell version of a group regex.
Either you don't understand what the Haskell group function does or I don't understand what you mean by “group regex”.

>Python dictionaries are sorted
except they're not at all

they're in an order that's platform specific and definitely not in any consistent sorting

>Keys and values are iterated over in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond. This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys()). Another way to create the same list is pairs = [(v, k) for (k, v) in d.items()].
your example only worked because coincidentally the range of input values was in sorted order in your input

def histogram(collection: Traversable[Any]) = {collection.groupBy(x=>x).mapValues(_.size).toSeq.sortBy(_._2)}

HAH

Lua was made for this one. You will notice and bow down to this beautiful code

function array(...)
args = {...}
for i, v in ipairs(args) do
print("Element"..i..": "..v)
end
end

array(34,23,35,65)

>sorted histogram
did you even read the murderous avian's prompt?

this is my favorite solution because its the most triggering

*tentatively raises paw*

Ummm you know that programming challenges have nothing to do with technology, right?

...

just add table.sort(args) brah

You mean a bar plot, a histogram is for a continuous variable, not count

template
void print_histogram(const std::vector& data)
{
std::map histogram;
for(const T& e : data)
histogram[e]++;

for(auto& d : histogram)
std::cout

It took a lot of me not to let this trigger me.

doesn't work that way bro

best you can do is get the keys, sort the keys, then use the sorted keys to return sorted values

>falling for the easiest b8
Nice 4x4s

library(ggplot2)
v1

Make sweet love to me please.

Okay, so I'm not the only one that likes these threads...

Updated javascript one-liner that takes the first argument passed to Node and prints a character histogram.
console.log(JSON.stringify(process.argv[0].split('').sort().join('').match(/(.)\1*/g).sort((left, right) => left.length - right.length).map(letter => {letter: letter.length})))

Fuck, formatting.
console.log(JSON.stringify(process.argv[0].split('').sort().join('').match(/(.)\1*/g).sort((left, right) => left.length - right.length).map(letter => {letter: letter.length})))

Does this guy get 4chins to do his hw for him every day? No wait he could just copy and paste from stack overflow

Why is triggering user?

>more than one line long
>in fact, waayy more than one line long
Gee, I wonder why

>writing your own algorithm
>using existing one
Gee

Oh sorry, you were triggered because you expected
import solver

solver.solve() with some list comprehension and lambda

>homework

Not only is that a misrepresentation of the truth, but programming languages are for getting things done, not writing the world's longest, most elaborate fizzbuzz implementation. You can feel smug about doing things the long way, but in the end you've only cheated yourself.

I leave you with the wisdom of Master Foo
catb.org/esr/writings/unix-koans/ten-thousand.html

Meh, programming languages are there and you can do whatever the fuck you want with them

In some cases yes.

But why should I use algorithm with complexity nlog(n) when I can write one by myself which runs for log(n)?

(defun big-black-cocks (list)
(let ((candy-ass NIL))
(dolist (roody-poo list (sort candy-ass :key #'car))
(aif (assoc roody-poo candy-ass)
(progn (delete it candy-ass)
(push (rplacd it (1+ (cdr it))) candy-ass))
(push (cons roody-poo 1) candy-ass)))))

Would have looked a lot better if fags had actually defined (setf assoc) in ANSI CL. aif is borrowed from en.wikipedia.org/wiki/Anaphoric_macro

This

fuck you

>>>>>>>>,[>,]>>+>[-]>[-]+[-]
+[-[>>[-]+

Clojure standard library master race

(def make-histogram frequencies)

It sort them, but doesn't show the number of times each symbol is seen

But you're given an argument string as input.

C#

public Dictionary CreateHistogramBuckets(int[] input, int bucketSize) {
return input.GroupBy(i => (i / bucketSize)*bucketSize)
.ToDictionary(group => group.Key, group => group.Count());
}


or if you don't want it in buckets, it's just:
return input.GroupBy(i => i)
.ToDictionary(group => group.Key, group => group.Count());

>C# can't even into unstructured code
lel, enjoy those two extra lines

> (frequencies "hello world")
{\h 1, \e 1, \l 3, \o 2, \space 1, \w 1, \r 1, \d 1}

hm, interesting I haven't heard the term "histogram" being used outside of the context of image data

go doesn't provide sorted maps ootb so you'd have to use something like this:
gist.github.com/ikbear/4038654
regardless it's as easy as
package main

import (
"fmt"
)

func main() {
test := []string{"y", "o", "u", "g", "u", "n", "n", "a", "g", "e", "t", "s", "t", "a", "b", "b", "e", "d", "m", "a", "t", "e"}
hist := map[string]int{}
for _, r := range test {
hist[r]++
}
fmt.Printf("%#v\n", hist)
}
bringing these things together might give me a headache so take some php instead:

BIRDY PLS NO KILL
#include
#include
#include
#include

using namespace std;

bool compare(const pair&i, const pair&j){
return i.second > j.second;
}

int main()
{
string input;
cin>>input;
map hist;
map::const_iterator histIt;
vector mapVector;

for (int i = 0 ; i < input.size() ; ++i) {
histIt = hist.find(input[i]);

if( histIt == hist.end() )
hist[input[i]]= 0;
else
++hist[input[i]];
}

for (histIt = hist.begin() ; histIt != hist.end() ; ++histIt )
mapVector.push_back(*histIt);

sort(mapVector.begin(), mapVector.end(), compare);

for (int i = 0 ; i< mapVector.size() ; i++)
cout

Ooops, change that
for (int i = 0 ; i< mapVector.size() ; i++)

to

for (int i = 0 ; i< mapVector.size() ; ++i)

c++ template metaprogramming version

#include
#include
#include


// returns pair
template
struct count {
static auto c() {
return std::pair<
std::index_sequence,
std::index_sequence
>{};
}
};

template
struct count {
static auto c() {
return count::c();
}
};


// generates histogram type for input sequence type
template
struct histogram {
constexpr static size_t size = sizeof...(C);
using indices = std::make_index_sequence;
// Sorts the input at compiletime, and returns index_sequence
// with sorted type
struct const_array { size_t a[size]; };
constexpr static auto sort_2() {
const_array a{C...};
// std::sort is not constexpr friendly using a bubble sort
for (size_t i=0; i

whoops.
the input is in the histogram templates type

histogram h;

the output is a tuple of integer sequences
wher ethe first number is element, and 2nd is its count.
std::tuple<
std::integer_sequence,
std::integer_sequence,
std::integer_sequence >

i should of made it look a bit better though.

>boost

just to print the type name nicely.

Too lazy to do it better:

use std::collections::BTreeMap;

fn histogram(list: &[T]) -> BTreeMap {
let mut map = BTreeMap::new();

for e in list {
if map.contains_key(e) {
let c = map.remove(e).unwrap();
map.insert(e.clone(), c+1);
} else {
map.insert(e.clone(), 1);
}
}

map
}