[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y ] [Home]
4chanarchives logo
QUICK WRITE A PROGRAM IN YOUR FAVORITE LANGUAGE THAT CREATES
Images are sometimes not shown due to bandwidth/network limitations. Refreshing the page usually helps.

You are currently reading a thread in /g/ - Technology

Thread replies: 157
Thread images: 16
File: killer bird.jpg (29 KB, 412x430) Image search: [Google]
killer bird.jpg
29 KB, 412x430
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
>>
File: 1467625165247.jpg (27 KB, 412x430) Image search: [Google]
1467625165247.jpg
27 KB, 412x430
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']))
>>
>>55429983
FUCK YOU OP
I wanted to post such a thread
>>
File: 1467625165247.jpg (12 KB, 321x298) Image search: [Google]
1467625165247.jpg
12 KB, 321x298
>>55430042
GET TO FUCKING WORK
>>
File: soccer.webm (3 MB, 640x640) Image search: [Google]
soccer.webm
3 MB, 640x640
>>
>>55430000
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

>>
>>55430630
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}
>>
>>55430585
i think i saw this slut had sex with a doge
>>
What's in the array killer bird, elements of any type?
>>
>>55431005
link?
>>
>>55431027
don't have a link rn, but she's part of Mexzoo.
she was also wearing the same dress and the same shoe.
>>
>>55429983

# 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 }


>>55430776

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

You're a genius, and I respect you.
>>
I'M GONNA DO IT TOMORROW BIRD I SWEAR
>>
#include <stdio.h>
#include <stdlib.h>
#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);
}
>>
>>55431363
>hurr C is da best
I think I'm going to be sick.
>>
>>55431363

It's [ c o d e ] [ / c o d e], pajeet.
>>
>>55431363
Why not do it with a linked list?
>>
>>55431263

Awwww....
:3

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

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

That's all of us, anon. That's all of us...
>>
>>55430946

What is this language?
>>
>>55431456

True dat.
>>
File: c21f859648beecd86da1c063.jpg (128 KB, 640x459) Image search: [Google]
c21f859648beecd86da1c063.jpg
128 KB, 640x459
>>55429983
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<KeyValuePair<string, int>> histogram, string key)
{
for (int i = 0; i < histogram.Count; i++) {
if (String.Equals(histogram[i].Key, key)) {
histogram[i] = new KeyValuePair<string,int>(histogram[i].Key, histogram[i].Value + 1);
return;
}
}

histogram.Add(new KeyValuePair<string, int>(key, 1));
}

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

static void Main(string[] args)
{
var items = new List<string>();
var histogram = new List<KeyValuePair<string, int>>();

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<string, int> 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.
>>
>>55431466
q
>>
>>55431397
Isn't this more efficient? Adding would be O(n) anyway but using the list would require calling malloc more often
>>
>>55429983
map (head &&& length) . group . sort


took me 5 seconds or so. untested
>>
File: js.png (10 KB, 1052x1052) Image search: [Google]
js.png
10 KB, 1052x1052
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]})
>>
>>55431599
Explain this shit.
>>
>>55431554

Wow, q looks sweet.

Another language to put on my list..
>>
>>55431680
λ ghci
GHCi, version 7.10.3: http://www.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")
λ
>>
>>55431724

what modules are you using?
>>
>>55431724
>>55431788

Ahh, I see. Data.List nvm.
>>
>>55431724
Hmm, I need to practice my regexes...
>>
>>55431816
There's no regex here. Regex has no place in programming IMO.
>>
>>55429983
i'm not doing your homework rajesh.
>>
>>55431826
The only special thing about your code is the group function, which is a Haskell version of a group regex.
>>
>>55431592
A call to malloc is insignificant, also use calloc
>>
>>55431841
What makes you think this is homework?
>>
>>55429983
I don't have any favourite language, sorry bird.
>>
>>55432185
One of us is going to get stabbed and it's not me.
>>
>>55429983
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 <= 0 goto 110
85 if a(j-1) <= a(j) goto 110
90 k=a(j): a(j)=a(j-1): a(j-1)=k
95 j=j-1
100 goto 80
110 next i
150 rem make histogram
175 j=a(0)
190 n=0
200 for i=0 to size
210 if a(i)<>j then goto 300
220 c=a(i)
230 n=n+1
250 goto 400
300 print c;
310 print ": ";
320 print n
330 n=1
340 j=a(i)
350 c=j
400 next i
405 rem get trailing entry
410 if n<>1 goto 500
420 print c;
430 print ": ";
440 print n
500 end

took me a fucking half hour and it probably still isn't really properly right
how did anyone fucking deal with this shit
ended up writing a bit in C and then porting it back into basic after getting stuck on the corners (start and end of array results were wrong)
insertion sort because I'm fucking lazy, can't be arsed to write a quicksort
>>
input <- readline("give me a shitload of numerical values separated by commas you asshat: ")
input <- as.numeric(strsplit(input,",")[[1]])
if (any(is.na(input))){
stop("You fucking jackass, you gave me a non-numerical value")
}
valueNames <- sort(unique(input))
valueCounts <- rep(0,length(valueNames))
for (eachPos in 1:length(valueNames)) {
valueCounts[eachPos] <- sum(input %in% valueNames[eachPos])
}
output <- data.frame(Element = valueNames,Count=valueCounts)

R doesn't really have named-value dicts/arrays and lists in R are BALLS, so I put it in a dataframe, and fuck you knifebird if you have a problem with it
>>
File: Untitled.png (2 KB, 675x438) Image search: [Google]
Untitled.png
2 KB, 675x438
>>55432437
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
>>
>>55432435
Ah yeah. Javascript is great.
>>
>>55432435
>sorted
>>
>>55432528
Python

>>55432544
Python dictionaries are sorted
>>
>>55432557
They are in javascript as well. The items are dictionary keys whose count is the value.
>>
>>55432528
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.
>>
>>55431599

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
>>
File: ZPicooa.gif (1 MB, 300x173) Image search: [Google]
ZPicooa.gif
1 MB, 300x173
>>55432822
>not hopping on the meme train
>>
>>55431858
>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”.
>>
>>55432557
>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
>>
>>55432557
>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)}
>>
File: 1467529829548.png (156 KB, 342x276) Image search: [Google]
1467529829548.png
156 KB, 342x276
>>55429983
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)
>>
>>55434384
>sorted histogram
did you even read the murderous avian's prompt?
>>
File: 1437511806239.jpg (243 KB, 573x446) Image search: [Google]
1437511806239.jpg
243 KB, 573x446
>>55431363
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?
>>
>>55434430
>>
>>55434421
just add
table.sort(args)
brah
>>
>>55429983
You mean a bar plot, a histogram is for a continuous variable, not count
>>
template<typename T>
void print_histogram(const std::vector<T>& data)
{
std::map<T, int> histogram;
for(const T& e : data)
histogram[e]++;

for(auto& d : histogram)
std::cout << d.first << ": " << d.second << std::endl;
}

print_histogram(std::vector<std::string>{"fuck", "you", "bird", "bird"});
>>
>>55434430
It took a lot of me not to let this trigger me.
>>
>>55434474
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
>>
>>55434444
>falling for the easiest b8
Nice 4x4s
>>
File: Rplot.png (3 KB, 580x370) Image search: [Google]
Rplot.png
3 KB, 580x370
library(ggplot2)
v1 <- sample(1:9, 100, replace = TRUE)
df <- data.frame(v1)
ggplot(df, aes(x=factor(v1), fill=factor(v1), y = v1)) + geom_bar(stat="identity")
>>
>>55432524
Make sweet love to me please.
>>
>>55431539
Okay, so I'm not the only one that likes these threads...
>>
>>55431665
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})))

>>
>>55436322
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
>>
>>55434423
Why is triggering anon?
>>
>>55436505
>more than one line long
>in fact, waayy more than one line long
Gee, I wonder why
>>
>>55436515
>writing your own algorithm
>using existing one
Gee
>>
>>55436515
>>55436533
Oh sorry, you were triggered because you expected
import solver

solver.solve() with some list comprehension and lambda
>>
>homework
>>
File: Foo.png (459 B, 93x35) Image search: [Google]
Foo.png
459 B, 93x35
>>55436533
>>55436662
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
http://catb.org/esr/writings/unix-koans/ten-thousand.html
>>
>>55436720
Meh, programming languages are there and you can do whatever the fuck you want with them
>>
>>55436720
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 https://en.wikipedia.org/wiki/Anaphoric_macro
>>
>>55436845
This
>>
>>55429983

fuck you

>>>>>>>>,[>,]<[[>>>+<<<-]>[<+>-]<+<]>[<<<<<<<<+>>>>>>>>-]<<<<<<<<[[>>+
>+>>+<<<<<-]>>[<<+>>-]<[>+>>+>>+<<<<<-]>[<+>-]>>>>[-<->]+<[>->+<<-[>>-
<<[-]]]>[<+>-]>[<<+>>-]<+<[->-<<[-]<[-]<<[-]<[[>+<-]<]>>[>]<+>>>>]>[-<
<+[-[>+<-]<-[>+<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<]<<[>>+<<-]>[>[>+>
>+<<<-]>[<+>-]>>>>>>[<+<+>>-]<[>+<-]<<<[>+>[<-]<[<]>>[<<+>[-]+>-]>-<<-
]>>[-]+<<<[->>+<<]>>[->-<<<<<[>+<-]<[>+<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]
<<]>[[-]<<<<<<[>>+>>>>>+<<<<<<<-]>>[<<+>>-]>>>>>[-[>>[<<<+>>>-]<[>+<-]
<-[>+<-]>]<<[[>>+<<-]<]]>]<<<<<<-]>[>>>>>>+<<<<<<-]<<[[>>>>>>>+<<<<<<<
-]>[<+>-]<+<]<[[>>>>>>>>+<<<<<<<<-]>>[<+>-]<+<<]>+>[<-<<[>+<-]<[<]>[[<
+>-]>]>>>[<<<<+>>>>-]<<[<+>-]>>]<[-<<+>>]>>>]<<<<<<]>>>>>>>>>>>[.>]
>>
Clojure standard library master race

(def make-histogram frequencies)
>>
>>55436935
It sort them, but doesn't show the number of times each symbol is seen
>>
>>55436949
But you're given an argument string as input.
>>
C#

public Dictionary<int, int> 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());
>>
>>55437028
>C# can't even into unstructured code
lel, enjoy those two extra lines
>>
>>55436998
> (frequencies "hello world")
{\h 1, \e 1, \l 3, \o 2, \space 1, \w 1, \r 1, \d 1}
>>
File: 078.jpg (79 KB, 859x1160) Image search: [Google]
078.jpg
79 KB, 859x1160
>>55429983
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:
https://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:
<?php
function histogram($a) {
$ret = [];
foreach($a as $k) {
@$ret[$k]++; // to suppress E_NOTICE about uninitialized key
}
asort($ret); // use arsort here for descending order
return $ret;
}


gotta fly for now! see you tomorrow
>>
>>55429983
BIRDY PLS NO KILL
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>

using namespace std;

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

int main()
{
string input;
cin>>input;
map<char,int> hist;
map<char,int>::const_iterator histIt;
vector<pair<char, int> > 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<<mapVector[i].first<<" : "<<mapVector[i].second+1<<endl;

return 0;
}
>>
>>55437351

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 <utility>
#include <tuple>
#include <algorithm>


// <1,1,1,2,2,3,3> returns pair<seq<1, 3>, seq<2,2,3,3>>
template<size_t N, size_t H, size_t... I>
struct count {
static auto c() {
return std::pair<
std::index_sequence<H, N>,
std::index_sequence<I...>
>{};
}
};

template<size_t N, size_t H, size_t... I>
struct count<N, H, H, I...> {
static auto c() {
return count<N+1, H, I...>::c();
}
};


// generates histogram type for input sequence type
template<size_t... C>
struct histogram {
constexpr static size_t size = sizeof...(C);
using indices = std::make_index_sequence<size>;
// 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<size-1; ++i)
for (size_t j=0; j<size-i-1; ++j)
if (a.a[j] > a.a[j+1]) {
auto tmp = a.a[j];
a.a[j] = a.a[j+1];
a.a[j+1] = tmp;
}
return a;
}

// Return index sequence of sorted type
template<size_t... I>
constexpr static auto sort_1(std::index_sequence<I...>) {
return std::index_sequence<sort_2().a[I]...>{};
}
constexpr static auto sort() {
return sort_1(indices{});
}

constexpr static auto create_1(std::index_sequence<>) {
return std::tuple<>{};
}
template<size_t H, size_t... T>
constexpr static auto create_1(std::index_sequence<H, T...>) {
auto x = count<1, H, T...>::c();
return std::tuple_cat(
std::make_tuple(x.first),
create_1(x.second)
);
}
constexpr static auto create() {
return create_1(sort());
}
};

//
// v v
// 1 2 3 3 2 1
//

#include <iostream>
#include <typeinfo>
#include <boost/core/demangle.hpp>
int main() {
using boost::core::demangle;
histogram<1,2,1,3,2,1,2,3,3,3,3,3,1> h;
std::cout << demangle(typeid(h).name()) << '\n';
std::cout << demangle(typeid(h.create()).name()) << '\n';
}
>>
>>55437651
whoops.
the input is in the histogram templates type

histogram<1,2,1,3,2,1,2,3,3,3,3,3,1> 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<unsigned long, 1ul, 4ul>,
std::integer_sequence<unsigned long, 2ul, 3ul>,
std::integer_sequence<unsigned long, 3ul, 6ul> >


i should of made it look a bit better though.
>>
>>55437628
>boost
>>
>>55437702
just to print the type name nicely.
>>
Too lazy to do it better:

use std::collections::BTreeMap;

fn histogram<T: Ord + Clone>(list: &[T]) -> BTreeMap<T, usize> {
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
}
>>
>>55431599
>>55432802
>>55434283
>>55436339

I like how Haskell, Ruby, Scala and JavaScript all use the "sort / group / map" concept.

Funtional programming is just so neat...


>>55431363

Uhm.. at first I thought "this is over-engineering". But after having a second look it looks actually pretty much to the point.

I will look throught it in detail later to refresh my C knowledge, thanks.


>>55432437
>>55436935

Honourable mentions.

(Even though the brainf**k guy probably used a code generator..)
>>
I saw some machine learning approaches about the issue. do you guys have some source, where to start leaning about this shit?
>>
#include <stdio.h>
#include <stdlib.h>
#include "sortedhistogram.h"

int main(int argc, char** argv) {
int c;
sortedhistogram h;
sortedhistogram_init(&h);
while(1) {
c = getchar();
if(c == EOF) {
break;
}
sortedhistogram_add(&h, c);
}
sortedhistogram_print(&h);
return EXIT_SUCCESS;
}


1 / 3
>>
#ifndef SORTEDHISTOGRAM_HEADER
#define SORTEDHISTOGRAM_HEADER

#define SORTEDHISTOGRAM_CAPACITY 10

typedef struct {
char* elements;
int* amounts;
int capacity;
int size;
int max;
} sortedhistogram;

void sortedhistogram_init(sortedhistogram*);
void sortedhistogram_add(sortedhistogram*, char);
void sortedhistogram_print(sortedhistogram*);

#endif


2 / 3
>>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "sortedhistogram.h"

void sortedhistogram_init(sortedhistogram* h) {
h->capacity = SORTEDHISTOGRAM_CAPACITY;
h->elements = malloc(sizeof(char) * h->capacity);
assert(h->elements);
h->amounts = malloc(sizeof(int) * h->capacity);
assert(h->amounts);
h->size = 0;
h->max = -1;
}

int sortedhistogram_find(sortedhistogram* h, char c) {
int pos;
for(pos = 0; pos < h->size; pos++) {
if(h->elements[pos] == c) {
return pos;
}
}
return -1;
}

void sortedhistogram_enlarge(sortedhistogram* h) {
if(h->size >= h->capacity) {
h->capacity += SORTEDHISTOGRAM_CAPACITY;
h->elements = realloc(h->elements, sizeof(char) * h->capacity);
assert(h->elements);
h->amounts = realloc(h->amounts, sizeof(int) * h->capacity);
assert(h->amounts);
}
}

void sortedhistogram_add(sortedhistogram* h, char c) {
int pos = sortedhistogram_find(h, c);
if(pos == -1) {
sortedhistogram_enlarge(h);
pos = h->size;
h->elements[pos] = c;
h->amounts[pos] = 0;
h->size++;
}
h->amounts[pos]++;
if(h->amounts[pos] > h->max) {
h->max = h->amounts[pos];
}
}

void sortedhistogram_print(sortedhistogram* h) {
int amount;
int pos;
for(amount = h->max; amount > 0; amount--) {
for(pos = 0; pos < h->size; pos++) {
if(h->amounts[pos] == amount) {
printf("%c %d\n", h->elements[pos], amount);
}
}
}
}


3 / 3

Hooray for O(n^2)
>>
>>55436846
nvm, you were supposed to call (setf cdr) on assoc.
(defun big-black-cocks (list)
(let ((candy-ass NIL))
(dolist (roody-poo list (sort candy-ass :key #'car))
(aif (assoc roody-poo candy-ass)
(incf (cdr it))
(push (cons roody-poo 1) candy-ass)))))
>>
>>55438468
Neat, you've got a header and everything. Just one remark, I would have done the reordering in add like the guy above did
>>
>>55438446
>>55438457
>>55438468

Is it just me or does this leak memory?
>>
>>55439016
Yeeeep
>>
>>55431294
Where
>>
>>55439016
No. Once the program shuts down the operating system frees everything. And since the data structure only allocates additional memory during run time, there is no leak.
>>
>>55439047
>No. Once the program shuts down
Hi Pajeet
>>
>>55439047
Not every operating system. Furthermore he really should have included a free method
>>
>>55439102
>>55439113
None of the memory is reused. It's a conscious choice. But I'd be happy to add one for 50 bucks. Do you have paypal?
>>
>>55439047
Not every program finishes executing in a ordinary fashion. Crashes can cause memory to not get freed
>>
>>55430000
4 (FOUR) repeating digits wew lad also Python is best language (you could have done that in a one-liner, too)
>>
>>55439154
That's irrelevant to the code I posted. A free function would not help in this case.
>>
>>55438173
New approach, using iterators and pattern matching

use std::collections::BTreeMap;

fn histogram<T: Ord + Clone>(list: &[T]) -> BTreeMap<T, usize> {
list.into_iter()
.fold(BTreeMap::new(), |mut map, key| {
match map.get(key) {
Some(&val) => map.insert(key.clone(), val + 1),
None => map.insert(key.clone(), 1)
};
map
})
}
>>
>>55439187
Of course it would, you could free memory right after using the histogram and shorten the interval of time where a crash could occur and make a problem. Theoretically. It's always a god practice to explicitly free all memory. Just stop making excuses and admit you didn't think about it
>>
>>55439223
I did think about it and chose not to. Look at the carefully structured design of my code and tell me I "accidentally" forgot. Of all the things you could have nagged about, for example the performance or data structure, you chose this insignificant shit. You're gonna get stabbed.
And it doesn't leak memory. All the dynamically allocated memory is used right up until termination. And after that it's the operating system's job to free memory after a program is done, no matter if it crashed or not. In fact, leaving out the manual free() makes the entire program run and terminate faster, by exactly 0.000000000000000000000000000001 seconds. Suck it, Pajeet-kun.
>>
>>55439300
Gosh you're ignorant lmao
>>
>>55439372
But i did think about it and chose not to. Look at the carefully structured design of my code and tell me I "accidentally" forgot. Of all the things you could have nagged about, for example the performance or data structure, you chose this insignificant shit. You're gonna get stabbed.
And it doesn't leak memory. All the dynamically allocated memory is used right up until termination. And after that it's the operating system's job to free memory after a program is done, no matter if it crashed or not. In fact, leaving out the manual free() makes the entire program run and terminate faster, by exactly 0.000000000000000000000000000001 seconds. Suck it, Pajeet-kun.
>>
>>55439372
You're just jealous of my doubles.
>>
>>55429983
>OR THIS BIRD IS GONNA STAB YOU
#define STAB HUG
int main() {
return 0;
}
>>
>>55429983
Please stab me, bird. My life sucks anyways.
>>
>>55439300

>it's not a bug, it's a feature!

spoken like a true develloper..

now fix your shit
>>
>>55438375

You mean this?

>http://joelgrus.com/2016/05/23/fizz-buzz-in-tensorflow/
>>
[CODE]import collections

def histogram(iterable):
return collections.Counter(iterable)
[/CODE]

Python is not my favorite language through.
>>
import collections

def histogram(iterable):
return collections.Counter(iterable)


Python is not my favorite language through.
>>
import collections

def histogram(iterable):
return collections.Counter(iterable)


Python is not my favorite language through.
>>
Who got that gif of the bird stealing a knife?
>>
>>55434143
>>55432557
in a lot of python implementations, the id (hash) of integers is the integer itself, though.
>>
>>55440781
key* not id
fuck I need food
>>
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Printer;

my %out;

grep !$out{$_}++, qw/z z z z z a q b b b r t a z z z l k f g g g/;

p %out;
>>
>>55440592
>>55440602
>>55440611
That's the way to go faggot
>>
>>55429983
OH SHIT
>>
>>55440872

Cool !

I copied your approach into Ruby, Perl-Sama:

out = Hash.new(0)
%w/z z z z z a q b b b r t a z z z l k f g g g/.grep(//){|i| out[i] +=1}
p out
>>
>>55440799
>>55440781
Okay, so, in some python installations, you've met the goal of the challenge.

It still seems not very aboveboard to have an implementation-specific solution. It's a portability nightmare.
>>
>>55441710
>>55440781
Ah, found something:
http://stackoverflow.com/a/25793361
>The hash() of an integer is itself but that doesn't necessarily mean that lower integers will appear before higher ones since the hash is taken modulo table size in order to allocate it to a bucket.
>>
>>55441241
Nicely done.
>>
>>55429983
Wait what's histogram? Can't find it in the index of my Ruby on Rails Vol. XI
>>
C#
var solution = array.Select(e => new Tuple<int, int>(e, array.Count(x => x == e)))
.Distinct()
.OrderByDescending(x => x.Item2);
>>
>>55442358
they're up to 11 now? fuck me
>>
>>55439209
Is BTreemap default sorted by value?
>>
>>55431363
>typedef struct ...
Kill yourself
>>
>>55442358
It's a fancy term for counting the number of occurrences of every element. The histogram of "Hello" shows 2 x l and 1 x for all other letters.
>>
hist(df)
>>
>>55445294
see >>55434476
>>
Here's my Java implementation:

import java.util.Arrays;
import java.util.TreeMap;

public class SortedHistogram {


public TreeMap<String, Integer> getHistogram(String[] input) {

Arrays.sort(input);

TreeMap<String, Integer> result = new TreeMap<>();

for (int i = 0; i < input.length; i++) {
Integer count = result.get(input[i]);
if (count == null) {
result.put(input[i], 1);
} else {
result.put(input[i], count + 1);
}
}

return result;
}

public static void main(String[] args) {

String[] initialArray = {"d", "a", "k", "k", "a", "d", "a", "k", "k", "a", "a", "n", "o", "n", "i", "s", "b", "a", "k", "a"};
SortedHistogram histogram = new SortedHistogram();
System.out.println(histogram.getHistogram(initialArray));

}

}
>>
>>55444742
Yes
>>
>>55444742
>>55445654

https://doc.rust-lang.org/std/collections/#use-a-btreemap-when
>>
That was short

->>>>>->-[[->>+<<]>>-]>>-<+[-<+]->,
[[[->>+<<]>>-]>++[-<+]->,]++++++++[
-<+++++<++++<+++++++<+++++>>>>]<+.<
.<++<++++>>>>>+>+[->[<<<-<+[-<+]->[
->.>>.<<<]+>+[->+]>.>++++++++[->+++
+++>+++++++<<]>>++.<<+++++[->>-----
<<]>>-.[-]<.[-]]<<[->>+<<]>>+>+]+[-
<+]>[->>>.<<<]>>>>+.
>>
>>55446513
http://www.clifford.at/bfcpu/bfcomp.html
?
>>
>>55447409
yes, it is brainfuck.

I usually use https://copy.sh/brainfuck/ , it has a nice debugger and pretty fast
>>
>>55439178
It is a one-liner.
>>
File: somebody kill me.gif (74 KB, 360x202) Image search: [Google]
somebody kill me.gif
74 KB, 360x202
>finished first year of college in cs
>mfw I have no idea what anyone is talking about
>mfw pic related
>>
>>55432437
decided to actually go check it for robustness -- it actually works just fine with any data I decided to throw at it, except one notable thing being off

replace line 30 with
30 for i=0 to size

because it used the hardcoded 19 as max as originally posted (remember: arrays in c64 basic are defined by their highest addressable index, so "dim a(19)" is an array with 20 slots), so if you feed it longer/shorter data and change the size, it breaks there

also, fuck me, C64 basic is slow as fuck
as posted, it takes like 4 seconds before printing the result, and nearly two more seconds to slowly print the results to screen
Thread replies: 157
Thread images: 16

banner
banner
[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y] [Home]

All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
If a post contains personal/copyrighted/illegal content you can contact me at [email protected] with that post and thread number and it will be removed as soon as possible.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com, send takedown notices to them.
This is a 4chan archive - all of the content originated from them. If you need IP information for a Poster - you need to contact them. This website shows only archived content.