Programming challenge

Roll you dices, and enhance your skills.
Purpose other lists of challenges.

Other urls found in this thread:

gcc.gnu.org/onlinedocs/gnat_rm/The-GNAT-Library.html
ada-auth.org/standards/12rm/html/RM-TOC.html
ada-auth.org/standards/12rm/html/RM-A-15.html
groups.google.com/forum/#!topic/comp.lang.ada/FKon24HOO0A
wolframalpha.com/input/?i=stephen wolfram net worth
p.sicp.me/h6s3r.cl
gnu.org/licenses/gpl.htmlstring
rosettacode.org/wiki/Averages/Mode#C
en.wikipedia.org/wiki/SLOB
en.wikipedia.org/wiki/Slab_allocation
news.ycombinator.com/item?id=10897460
reddit.com/r/compsci/comments/24alae/has_anyone_actually_read_any_of_the_the_art_of/
youtube.com/watch?v=eJGzz6CBi8c
gitgud.io/m712/palin/
github.com/RustIndia/Rust
stackoverflow.com/questions/12237282/whats-the-difference-between-so-la-and-a-library-files).
twitter.com/SFWRedditVideos

roll

rofl

easy/short challenges 93
(defun square (x) (* x x))(defun triangle-property (ax ay bx by cx cy) (let* ((seg1 (sqrt (+ (square (- by ay)) (square (- bx ax))))) (seg2 (sqrt (+ (square (- cy by)) (square (- cx bx))))) (seg3 (sqrt (+ (square (- ay cy)) (square (- ax cx))))) (perimetre (+ seg1 seg2 seg3)) (halfperimetre (/ perimetre 2)) (area (sqrt (* halfperimetre (- halfperimetre seg1 ) (- halfperimetre seg2 ) (- halfperimetre seg3 ))))) (format t "~&Perimetre: ~S" perimetre) (format t "~&Area: ~S" area)))

roll for short

Roll for short.

Rolling again, Monty-Hall problem is boring. Switch every time, 2/3 chance vs 1/3 chance.

Done in Mathematica, too easy..
< Quiet kid, I've got money to make.

// Author: Karlie Klossy// This is a function that turns celsiuses into fahrenheits :PPfn convertCelsius_to_fahrenheit(n: f32) -> f32 {// First multiply by 1.8 ....let mut a = n * 1.8;// Then add 32.0f32 (f stands for farenheit)a = a + 32.0f32;// Then add 4.0f because women are oppressed by air conditioning and// men must pay for their privilegea = a + 4.0f32;return a;}

with GNAT.Command_Line; use GNAT.Command_Line;with Ada.Text_IO; use Ada.Text_IO;with Ada.Float_Text_IO; use Ada.Float_Text_IO;procedure fahrenheit is type Math is (Patriarchal, Feminist); C : Float; M : Math; Oppression_Constant : constant Float := 4.0; function c2f_p return Float is (C * 1.8 + 32.0); function c2f_f return Float is (C * 1.8 + 32.0 + Oppression_Constant);begin case Getopt("p") is when 'p' => M := Patriarchal; when others => M := Feminist; end case; C := Float'Value(Get_Argument); case M is when Patriarchal => C := c2f_p; when Feminist => C := c2f_f; end case; Put(C, 3, 1, 0);end fahrenheit;Usage$ ./fahrenheit 100216.0$ ./fahrenheit -p 100212.0

Did you really need two cases there?

can't Get_Argument until after flags are processed, because stray args might be part of a flag. It looks lame in this small example, but I do the exact same thing in a larger project: set a bunch of variables as args are processed, and then go on to do different things depending on those variables.
OTOH, I barely know any Ada so this is probably terrible for other reasons.

Ahh.

I got 93 there, so here's another 93 solution. What is the best language, and why is it always mathematica?

(79: Mastermind game)
taking that as a roll.with Ada.Text_IO, Ada.Strings.Bounded, Interfaces;use Ada.Text_IO, Ada.Strings.Bounded, Interfaces;with Ada.Numerics.Discrete_Random;procedure mastermind is subtype Secret is Unsigned_32 Range 0 .. 16#FFFFF#; package Rand_Int is new Ada.Numerics.Discrete_Random (Secret); package Secret_IO is new Ada.Text_IO.Modular_IO (Secret); function A (N : Secret) return Secret is (N and 16#F0000#); function B (N : Secret) return Secret is (N and 16#0F000#); function C (N : Secret) return Secret is (N and 16#00F00#); function D (N : Secret) return Secret is (N and 16#000F0#); function E (N : Secret) return Secret is (N and 16#F000F#); gen : Rand_Int.Generator; guess : Secret; goal : Secret; correct : Integer; procedure ok (B : Boolean) is begin if B then correct := correct + 1; end if; end ok; S : String (1..9); -- 5 digits, plus "16#" in front and "#" in backbegin Rand_Int.Reset (gen); goal := Rand_Int.Random (gen); Secret_IO.Put (S, goal, Base => 16); Put_Line ("Difficulty Level (Cheat): " & S); loop correct := 0; Put ("Your guess? "); Secret_IO.Get (guess); ok (A (guess) = A (goal)); ok (B (guess) = B (goal)); ok (C (guess) = C (goal)); ok (D (guess) = D (goal)); ok (E (guess) = E (goal)); Put_Line ("Correct digits:" & Integer'Image (correct)); exit when correct = 5; end loop;end mastermind;As played:$ ./mastermind Difficulty Level (Cheat): 16#C08CB#Your guess? 16#C08CA#Correct digits: 4Your guess? 0Correct digits: 1Your guess? 16#C08CB#Correct digits: 5

Easy roll

redoing this one.with Ada.Text_IO, Ada.Float_Text_IO;with Ada.Command_Line, GNAT.Command_Line;use Ada.Text_IO, Ada.Float_Text_IO;use Ada.Command_Line, GNAT.Command_Line;procedure fahrenheit2 is C : Float; Oppression_Constant : constant Float := 4.0; function c2f_p return Float is (C * 1.8 + 32.0); function c2f_f return Float is (C * 1.8 + 32.0 + Oppression_Constant); F : access function return Float := c2f_f'Access; Usage : exception;begin loop case Getopt("p h") is when 'p' => F := c2f_p'Access; when 'h' => Put_Line ("usage: " & Command_Name & " [-p] "); New_Line; Put_Line ("-p enables patriarchal, womyn-oppressing math, for TOTAL SHITLORDS."); raise Usage; when others => exit; end case; end loop; C := Float'Value(Get_Argument); Put(F.all, 3, 1, 0);end fahrenheit2;
so, all of the hundreds of people here who obviously know Python Ada, where do you get your gnat documentation? Just look at this garbage: gcc.gnu.org/onlinedocs/gnat_rm/The-GNAT-Library.html
That's the official documentation. That's what you get info pages of. Click on any of those library links and gape in amazement and horror.

I've barely looked at ada, so there's someone else out there that can help you more, but I would imagine you go by this.
ada-auth.org/standards/12rm/html/RM-TOC.html
The standard library is in the appendix.

the standard library documentation is reasonable, but I was looking specifically for GNAT's extensions. For example the idiomatic thing to do in C or in a scripting language is to exit(1) after printing usage, but Ada doesn't seem to support that, so I raise an exception instead:$ ./fahrenheit2 -husage: ./fahrenheit2 [-p] -p enables patriarchal, womyn-oppressing math, for TOTAL SHITLORDS.raised FAHRENHEIT2.USAGE : fahrenheit2.adb:21

Looks like you have to set the exit status flag, and then allow your program to terminate.
ada-auth.org/standards/12rm/html/RM-A-15.html
Some discussion here.
groups.google.com/forum/#!topic/comp.lang.ada/FKon24HOO0A

thanks user. I'll leave it at this:with Ada.Text_IO, Ada.Float_Text_IO;with Ada.Command_Line, GNAT.Command_Line;use Ada.Text_IO, Ada.Float_Text_IO;use Ada.Command_Line, GNAT.Command_Line;procedure fahrenheit2 is C : Float; Oppression_Constant : constant Float := 4.0; function c2f_p return Float is (C * 1.8 + 32.0); function c2f_f return Float is (C * 1.8 + 32.0 + Oppression_Constant); F : access function return Float := c2f_f'Access; procedure usage is begin Put_Line ("usage: " & Command_Name & " [-ph] "); New_Line; Put_Line ("-p enables patriarchal, womyn-oppressing math, for TOTAL SHITLORDS."); raise Exit_From_Command_Line; end usage;begin loop case Getopt ("p h") is when 'p' => F := c2f_p'Access; when 'h' => usage; when others => exit; end case; end loop; begin C := Float'Value (Get_Argument); exception when Constraint_Error => -- Get_Argument = "" usage; end; Put (F.all, 3, 1, 0);exception when Exit_From_Command_Line => Set_Exit_Status (1);end fahrenheit2;
I also found the answer to my question: you get the docs from the source code. i.e., /usr/lib/gcc/x86_64-linux-gnu/4.9/rts-native/adainclude/g-comlin.ads for GNAT.Command_Line docs. It's very well commented and the Ada itself is helpful.

Yeah that library documentation looked like it was pretty much the header files themselves. I need to pickup my Ada book again, I read a bit about it in the summer, but got sidetracked by other more pressing interests. That code is so readable, I'm sure even a person on the street could tell what it does.

roll for short

Easy/Short challenge 57
Common Lisp

(defun main (file) (with-open-file (filein file :direction :input) (with-open-file(fileout "/home/trouble/testtest-with-whitespace" :direction :output :if-exists :supersede :if-does-not-exist :create) (labels ((main () (let ((char (read-char filein nil :eof))) (cond ((eql char :eof) (format t "Job's done.")) ((char= char #\Space) (main)) (T (format fileout "~A" char) (main)))))) (main)))))

Fileout is (concatenate file "-without-whitespace")
Not directly pointing towards any file.

roll

use std::collections::HashMap;use std::time::{SystemTime, UNIX_EPOCH};const ORDER: usize = 3;#[derive(Default)]struct Lookup { map: HashMap,}struct Generator Generator { let mut rng = Rng::new(); Generator { lookup: self, state: self.map.keys() .nth(rng.uniform(self.map.len() as u32) as usize).unwrap().clone(), rng } }}impl { type Item = String; fn next(&mut self) -> Option { let values = &self.lookup.map[&self.state]; let value = values[self.rng.uniform(values.len() as u32) as usize].clone(); push(&mut self.state, value.clone()); Some(value) }}impl Rng { fn new() -> Self { let d = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); Rng((d * 1000000000).as_secs()) } fn next(&mut self) -> u32 { let tmp = self.0; self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1); let tmp2 = (((tmp >> 18) ^ tmp) >> 27) as u32; tmp2.rotate_right((tmp >> 59) as u32) } fn uniform(&mut self, max: u32) -> u32 { let limit = !0 - (!0 % max + 1); loop { let tmp = self.next(); if tmp = 80 { println!(); len = 0; } } println!();}fn push(slice: &mut [T], value: T) { assert!(slice.len() >= 2); for i in 0..slice.len() - 1 { slice.swap(i, i + 1); } let len = slice.len(); slice[len - 1] = value;}
man of Trump's age shouldn't be having any ice cream or soda. Ice cream in general is like sugary cancer, but definitely he should have a better diet if he hopes to make it more CIA Nigger proof. It mostly got used for uploading child porn and there was still a ton of people backing it to make money. And remember: You're still in debt. So you need to know about riseup. To begin with, they don't give a fuckuntil they are informed of their inferiority then they have to have all those methods available which is a stupid thing to do.What do you mean by "integrate"? Wine is already in pretty much every repo.▶Anonymous 14 days ago No.806654File (hide): cdb379a88d9ed5c⋯.jpg (50.6 KB, 600x654, 100:109, 6961ad9511bce0d5fbf724026c….jpg) (h) (u)What do you mean by shell? windows explorer or cmd?when I clicked "time" in cmd it shows time and asks me

rollin, need to git gud in C

Rolling
I'm a first semester C++ student, so this better not destroy my will to live

fml, i have not got good at resizing arrays for strings that aren't hardcoded max length, i know there's a library that just returns the string but not being able to do that bothers me.

fag detected. enjoy your square brackets kid

I'll do it in mathematica
LongestCommonSubsequence[s1, s2]

Enjoy!

Rolling

$_is.Prime(self.primality.map{|s| s.test_is_prime}) [ n : deriving __int64__ -> m bool ]
done

this is a mess. i figured out how to deal with unknown length files/strings though which was the ultimate goal.


fucking hell
#include #include #include struct read_file_response { int count; char* buffer;};/* read an unknown length file given filepathreturn char count and buff * in struct */struct read_file_response readFile(char *file_path){ FILE *fp; fp=fopen(file_path,"r"); int bufsize=1; char *buffer=malloc(bufsize); int index=0; int c; /* running realloc for every character probably isn't the fastest */ while( (c= fgetc(fp)) != EOF ) { if (index >= bufsize-1) { bufsize+=1; buffer=realloc(buffer,bufsize); } buffer[index]=c; index+=1; } struct read_file_response response; response.count=index; response.buffer=buffer; return response;}int countSubstring(char *sub,char *buffer) { char *bufpointer=buffer; int count=0; while( *bufpointer!=EOF && (bufpointer=strstr(bufpointer,sub)) ) { bufpointer+=1; count+=1; } return count;}int main(int argc, char *argv[]){ struct read_file_response response=readFile(argv[1]); printf("String:%s\n",response.buffer); int subcount=countSubstring("nigger",response.buffer); char *highest_sub; int highest_len=0; for (int start_i=0; start_i

Rolling

print("Number? ");INT n; read((n, new line));printf(($"The sum is "g(0)"."l$, (n >= 1 | n*(n+1)/2 | 0)))

RMS grant me luck

Stephen Wolfram grant me luck and shekels.

Wish I was a kike.

((([Oy, nice and easy. Thanks Yahweh)))

He's a legit genius.

I'll count that as a roll too. How can other standard libraries even compete?

He really is.
>wolframalpha.com/input/?i=stephen wolfram net worth

/*find how to pay a given amount of money in the least amount of euro coins/notes*/#include #include float fakemoney_types[15]={ 500,200,100,50,20,10,5,2,1,0.5,0.2,0.1,0.05,0.02,0.01};int main(int argc, char *argv[]){ float fakemoney=atof(argv[1]); float moneyleft=fakemoney; for (int i=0; i=1 ) { moneyleft=moneyleft-fakemoney_types[i]; type_count+=1; } if (type_count>0) { printf("%d ",type_count); if (fakemoney_types[i]>=1) { /* no ascii symbol for fake money*/ printf("€%0.0f ",fakemoney_types[i]); } else { printf("€%0.2f ",fakemoney_types[i]); } if (fakemoney_types[i]>2) { printf("note"); } else { printf("coin"); } if (type_count>1) { printf("s"); } printf("\n"); } } if (fakemoney>1.99) { printf("Y u be trippin doe u ain't got €%0.2f, broke ass nigga you need to hit up dem programs.\n", fakemoney); }}

except it's missing $0.01. off by 1 in loop whatever it's done

Warning: GPL!!!! Donut steal!
#include#include#includeint max(int a, int b){ return (a>b)?a:b;}void LCS(char *a, char *b, int an, int bn){ an += 1, bn += 1; int *suff = calloc(sizeof(int*), an * bn); int res = 0; char *c; int *ind; for(int i=0; i

this one's too easy
#include #include /*calculate bmi*/int main(int argc, char *argv[]){ char *str_height=malloc(sizeof(char)*4); char *str_weight=malloc(sizeof(char)*4); float height; float weight; printf("Height in inches:"); height=atof(fgets(str_height,4,stdin)); free(str_height); printf("Weight in pounds:"); weight=atof(fgets(str_weight,4,stdin)); free(str_weight); weight=weight/2.2; /*lb->kg*/ height=(height*2.54)/100; /*in->meters*/ float bmi=weight/(height*height); printf("bmi:%0.2f\n",bmi); if (bmi>25) { while(1==1) { printf("%0.2f bmi fatfuck detected\n",bmi); } } return 0;}

Gimmie a roll.

You're shitting me.
(reverse (second *posix-argv*))

Another easy roll please (Has to be quick, I have Halloween things to go to)

Done. Nice and easy.

...

Rollerino.

Huh, I didn't know there was a name for this sort of thing.

let me show you what a real enterprise-grade program looks like::- module bmi.:- interface.:- import_module float.:- type weight ---> lbs(float); kg(float).:- type height ---> in(float); ft(float); cm(float).:- type bmi == float.:- type anthrometric ---> human(height, weight, float); fatso.:- pred bmi(height::in, weight::in, anthrometric::out) is det.:- implementation.:- func cm(height) = float.cm(in(F)) = F * 2.54.cm(ft(F)) = F * 2.54 * 12.0.cm(cm(F)) = F.:- func kg(weight) = float.kg(lbs(F)) = F / 2.2.kg(kg(F)) = F.bmi(H, W, A) :- ( BMI > 25.0 -> A = fatso ; A = human(H, W, BMI) ), M = cm(H)/100.0, KG = kg(W), BMI = KG/(M*M).:- module main.:- interface.:- import_module io.:- pred main(io::di, io::uo) is det.:- implementation.:- import_module bmi, list, float, string.main(!IO) :- io.command_line_arguments(Args, !IO), ( Args = [Hs, Ws], to_float(Hs, H), to_float(Ws, W) -> bmi.bmi(bmi.in(H), bmi.lbs(W), A), ( A = human(_, _, BMI), io.format("%f\n", [f(BMI)], !IO) ; A = fatso, io.print_line("Fatso detected.", !IO) ) ; io.progname_base("bmicalc", P, !IO), io.format("usage: %s \n", [s(P)], !IO), io.set_exit_status(1, !IO) ).Compiling:$ mmc -i bmi$ mmc -o bmicalc main bmi$ ./bmicalc 72 17023.104353$ ./bmicalc 72 200Fatso detected.$ ./bmicalc usage: bmicalc $ ./bmicalc blah foousage: bmicalc

I'll do this eventually, roll.

shit's easy, reroll

here's my stupid solution to the erastothenes sieve, it currently isn't working because of some dumb exception and I don't feel like fixing it
#include#includeusing namespace std;int main(){ int sieveSize; int p = 2; //p is the first prime and supposed to represent every consecutive prime cout sieveSize; //prompts user for highest number they want the algorithm to evaluate vector vectorSieve(sieveSize); for (int init = 0; init < sieveSize; init++) { vectorSieve.at(init) = init + 2; //(this is supposed to set the first number to 2, and the second to 1 + 2, and so on, because the sequence is supposed to start at the first prime) } //initializes the vector with each value set to consecutive number - to sieveSize while (p != sieveSize) { for (int search = 0; search < sieveSize; search++) { if (search % p == 0 && search != 0 && search != p) { vectorSieve.at(search) = 0; } } //check if number in vector is divisible by p, sets number to zero if it is (not working: exception thrown [accessing empty vector] while reassigning to zero cout sieveSize; //(so the application doesn't immediately close) return 0;}

you've suffered enough user. Join me in the use of a more serious language:create numbers 100 allot0 constant Uncategorized1 constant Prime2 constant Skipped: red ( -- ) 27 emit ." [31m" ;: green ( -- ) 27 emit ." [32m" ;: null ( -- ) 27 emit ." [0m" ;: .numbers ( -- ) page 4 spaces 2 numbers 100 2 /string bounds do i c@ case Prime of green endof Skipped of red endof endcase dup 4 .r null dup 10 mod 0= if cr then 1+ loop drop cr ;: decide ( Category n -- ) numbers + c! .numbers 75 ms ;: skip-factors ( n-prime -- ) dup begin over + dup 100

Pick only one.

You were presented with a problem. Instead of creating a solution, you just created another problem.

does your meme lang into multi-threading? that's what the problem specifies

though i'm working on it too in C and I don't know how the fuck I would multithread it in any language.

sure.

in my case the sieve and the animation could be in separate threads, with the animation thread spying on the sieve's array. no real point to it (and the sieve would still need to sleep for the work to be observed), but I've used a similar technique in an admin interface to a web server, as an alternative to something like mod_status.

is there any way to multi-thread the actual seive? it seems like it's all deterministic.

The different calls to skip-factors could be in separate threads. They're modifying the same data structure but always separate parts of it. The challenge is to be smart with the main thread... One option:
1. Main advances to N
2. Advance to N+1 if N is already skipped
3. Otherwise, check to see if all worker threads are looking at >N. If so, mark prime and spawn new worker. Otherwise, sleep and repeat
No locking required. But I doubt it's what anyone had in mind.

Well the workers aren't necessarily modifying separate parts, but there's only a risk of assigning the same value multiple times. Performance, not behavior.

this
imagine you start at 2, thread pops, main goes to 3, thread pops, main goes to 4. if 2 thread hasn't zeroed/marked 4 yet, then you've got a whole unnecessary thread marking shit that's going to get marked by an earlier thread anyway.

if you have a starting set of known primes that contain n cores with primes, say 4 cores and 2,3,5,7, launch those threads first, and then join them all before launching another set of 4 threads, they might not overlap.

If main marked 4 prime and started a worker for it, the problem would be that 4 isn't prime. That's why the main thread has to make sure that all workers have advanced past what it's checking. But workers for 2 and 3 would both want to mark 6 12 18 etc as nonprime.

There is but when I did it wasn't faster than single threaded.
I didn't profile it but I'm pretty sure it was a cache issue.

Sieve in C minus multithreading since I haven't multithreaded anything in C yet and this seems like a shitty project to start on.
#include #include /* Copyright 2017 >>813314 All Rights ReservedUnlicensed use prohibited, licenses available for $79.99 on steamearly access *//* alloc and fill number array with 2->limit */void fill_num_array(int array_size, int *num_array){ for (int i=0; i

I need to clean this up more but I just realized I didn't put a return on any function. gcc wasn't complaining. apparantly that's not a requirement.

Close, I was Hugh Hefner.


Counting that as a roll. It turns the text into a 2D array and then uses built in padding functions.

Rollan

Easy/short challenge 60
Have to generate a random story.
My story is called "OY VEY STORY".

One output:
You name is Joseph Rothlevy.The currency is shekels.--------------------------------------------------Monday - Day 1You have 50000 shekels. You have 3 jokers left.You organise a VAT carbone tax scam. You win 100.000 shekelsToday, You spot a butterfly. It makes you wonder about life, about the after life, and especially about the money you need to make to become rich..--------------------------------------------------Wenersday - Day 2You have 199800 shekels. You have 3 jokers left. Messiah have 0.01 chance to appear.You win 10.000 shekels trading.Today, Incest is now authorised in the society. More chaos, more degeneracy, for the coming of our Messiah..--------------------------------------------------Thursday - Day 3You have 209600 shekels. You have 3 jokers left. Messiah have 0.011111111 chance to appear.You win 10.000 shekels trading.Today, One of your kid want money, calling you a miserly, so you give her a lot of cash..--------------------------------------------------Friday - Day 4You have 169400 shekels. You have 3 jokers left. Messiah have 0.011111111 chance to appear.Police have suspicions on you. 6 MILLIONS JEWS!!Suspicions dissapear.Today, Your coworker have insulted you. You said nothing, hands in your pockets and eyes fixing the ground..--------------------------------------------------Saturday - Day 5You have 159200 shekels. You have 2 jokers left. Messiah have 0.011111111 chance to appear.Oh Goy! It's Shabbat! Not work today!Today, Nothing happened..--------------------------------------------------Sunday - Day 6You have 159000 shekels. You have 2 jokers left. Messiah have 0.011111111 chance to appear.You win 50.000 shekels trading.Today, Another mass murder somewhere in the USA. Another stone on the path to the third temple, another stone of the full gunban road..--------------------------------------------------Monday - Day 7You have 208800 shekels. You have 2 jokers left. Messiah have 0.0125 chance to appear.Oy Gevalt! It's Tou Bichevat!Today, You crashed your car. You need a new one..--------------------------------------------------Tuesday - Day 8You have 158600 shekels. You have 2 jokers left. Messiah have 0.0125 chance to appear.Oy Gevalt! THE MESSIAH HAVE ARRIVED ! The Messiah made us, the chosen people, master of the earth! Mazeltov! I have Unlimited shekels now goys! You're all my slaves!

It's only one possible outcome. There is four outcome: The messiah arrive, you win 1 millions shekels, you get chased by the police and end up in telaviv, or you end in prison if you don't have money to change your identity. Everything is obviously random. Pain in the ass to balance the outcome, but it works.

This is the code (it's too big for here):
p.sicp.me/h6s3r.cl

I need to add more content to be generated. And maybe make it with more sentence, shown as a diary. But it works as hell.

A piece of the main function if you don't want to look it up:

(defun main () (defparameter date starting-date) (defparameter money starting-money) (defparameter jail-chance starting-jail-chance) (defparameter jokers starting-jokers) (defparameter antichrist-chance starting-antichrist-chance) (defparameter end-of-game NIL) (define-name) (Define-currency) (day))(defun day () (graphics 'sunrise) (cond ((= date day-goal) (setf end-of-game t)) ((> money 1000000) (graphics 'win) (setf end-of-game t)) ((or (< money -50000) (and (= jokers 0) (jail-p jail-chance))) (if (< money 50000) (graphics 'prison) (graphics 'telaviv)) (setf end-of-game t)) ((antichrist-apparition-p) (graphics 'antichrist) (setf end-of-game t)) ((and (> jokers 0) (jail-p jail-chance)) (graphics 'joker) (setf money (- money fine)) (setf jail-chance 0) (decf jokers 1)) ((zerop (mod date 5)) (format t "~&~A It's Shabbat! Not work today!" (exclamation))) ((random-jewish-festival-p) (format t "~&~A It's ~A!" (exclamation) (random-element jewish-festival-list))) ((scam-p) (setf money (+ money (scam money))) (setf jail-chance (+ jail-chance scam-jail-chance))) (T (setf money (+ money (trade money))) (setf jail-chance (+ jail-chance trade-jail-chance)))) (unless end-of-game (fact-of-the-day) (graphics 'midnight) (incf date 1) (setf money (- money per-day-need)) (day)))

Pretty simple. If there is more content, I'll put everything in files, and so modify the source code. Maybe implement a simple debt banking system, I don't know.

Kinda long. Implements the shunting yard algorithm, then evaluates the expression. Doesn't do powers.

def lexer(inp): ret = [] num = "" for c in inp: if c.isdigit(): num += c elif c in ['+', '-', '*', '/', '(', ')']: if num != "": ret.append(num) num = "" ret.append(c) else: if num != "": ret.append(num) num = "" ret.append(num) return retprec = { '+': 2, '-': 2, '/': 3, '*': 3 }def shunt(expr): ops = [] out = [] for val in expr: if val.isdigit(): out.append(val) elif val in ['+', '-', '*', '/']: if len(ops) > 0: while len(ops) > 0 and ops[-1] != '(' and prec[ops[-1]] >= prec[val]: out.append(ops.pop()) ops.append(val) elif val == '(': ops.append(val) elif val == ')': while ops[-1] != '(': out.append(ops.pop()) ops.pop() while len(ops) > 0: out.append(ops.pop()) return outdef evaluate(expr): stack = [] for val in expr: if val.isdigit(): stack.append(int(val)) elif val == '+': stack.append(stack.pop() + stack.pop()) elif val == '-': t = stack.pop() stack.append(stack.pop() - t) elif val == '*': stack.append(stack.pop() * stack.pop()) elif val == '/': t = stack.pop() stack.append(stack.pop() / t) return stack[-1]def main(): expr = str(raw_input("> ")) shunted = shunt(lexer(expr)) print ' '.join(shunted) print evaluate(shunted)if __name__ == "__main__": main()

Alright Stephen, give me a lucky roll again.

These are getting boring, I'll have to roll for hard next time.

A legit comic genius. One of the funniest writers I've read.

I don't think easy challenges are meant for this. Anyways rolling normal challenges.

has anyone used any of those site's listed in the OP on the first pic?

is it worth trying to solve a bunch of challenges there for jobs? seems like a scam but I'm thinking about signing up for the hell of it.

A ridiculous massive standard library! Here's your problem.

Learn some history, kid

*ridiculously

Project Euler is quite fun, it's math centric but for the first 50 or so problems, you could just brute force your way through problems. I did most of the first 200, and it's very heavily biased towards Number Theory. It was a lot of fun, I should go back to it someday. Not sure why RosettaCode is listed, it's not really for challenges. As for Jobs, I think most employers would be quite happy to see that you could complete a chunk of ProjectEuler problems, but you should also have a real world project you can showcase. Also, since the answers to these types of sites are all over the web, it would be very easy to game for Pajeet.

Rolling for long.

Couldn't figure out elegant approach to solving this problem. I could implement something like Fortune's algorithm but I'm to dumb do figure it out, so brute force it is. Roll something new.

I'm fucking retarded
#include#includeusing namespace std;int main(){ int sieveSize = -1; int p = 2; while (sieveSize < 0) { //p is the first prime and supposed to represent every consecutive prime cout sieveSize; //prompts user for highest number they want the algorithm to evaluate vector vectorSieve(sieveSize, 0); for (int init = 0; init < sieveSize; init++) vectorSieve.at(init) = init + 2; //(this is supposed to set the first number to 2, and the second to 1 + 2, and so on, because the sequence is supposed to start at the first prime) //initializes the vector with each value set to consecutive number - to sieveSize while (p != sieveSize) { for (int search = 0; search < sieveSize - p; search++) if (vectorSieve.at(search) % p == 0 && vectorSieve.at(search) != 0 && vectorSieve.at(search) != p) vectorSieve.at(search) = 0; //check if number in vector is divisible by p, sets number to zero if it is cout

it's funny i made those exact same mistakes on the c solution

You won't with that attitude! I'm sure you can though, and I recommend the book Computational Geometry by Mark de Berg, quite a comfy read.

I added proper spacing and fixed a few minor details
#include#include#includeusing namespace std;// Copyright 2017, Anonymous, under the terms of the GPL (General Public License) gnu.org/licenses/gpl.htmlstring kerning(string maxchar, string pchar);int main(){ int sieveSize = -1; int p; while (sieveSize < 0) { p = 2; //p is the first prime and supposed to represent every consecutive prime cout sieveSize; //prompts user for highest number they want the algorithm to evaluate vector vectorSieve(sieveSize, 0); for (int init = 0; init < sieveSize; init++) vectorSieve.at(init) = init + 2; //(this is supposed to set the first number to 2, and the second to 1 + 2, and so on, because the sequence is supposed to start at the first prime) //initializes the vector with each value set to consecutive number - to sieveSize while (p != sieveSize) { for (int search = 0; search < sieveSize - p; search++) if (vectorSieve.at(search) % p == 0 && vectorSieve.at(search) != 0 && vectorSieve.at(search) != p) vectorSieve.at(search) = 0; //check if number in vector is divisible by p, sets number to zero if it is cout

Erastotheme sieve

(defun square (x) (* x x))(defun init (n) (let ((list nil)) (dotimes (i (1+ n) (nreverse list)) (unless (or (zerop i) (= i 1)) (push i list)))))(defun main (n &optional (list (init n)) (compteur 1) reslist) (cond ((> (square (car list)) n) (append (nreverse reslist) list)) (T (main n (sieve (cdr list) (car list)) (1+ compteur) (cons (car list) reslist)))))(defun sieve (list el &optional reslist) (cond ((null list) (nreverse reslist)) ((zerop (mod (car list) el)) (sieve (cdr list) el reslist)) (T (sieve (cdr list) el (cons (car list) reslist)))))

lmfao stop paying attention to the retard "programming" in mathematica.

...

Please, it's about solving problems and moving on to the next in a way best suited to the language, with a personal preference for short problems.

whatever helps you sleep at night


lol

the point isn't to dig through the standard lib to draw the graph you need, the point is to do it yourself and learn something while doing it. flagcucks are worse than tripfags

No. The point is to show that Mathematica is programming master race, and to trigger idiots like you into getting upset about it.

...

pathetic

Did something happen at 4/g/? We seem to have a lot of newfags all of a sudden.

Didn't you realize that we're in the Holla Forums subreddit?

Forth is a little bit faster. For a sieve of size 0x01FFFFFF, Forth takes 72% as long to run the sieve and then to print out all the primes -- this, even though Forth's output is unbuffered.
But Forth is scaaary, unchecked, untyped. Compare::- module sieve.:- interface.:- import_module array, int.:- type sieve == array(categories).:- type categories ---> uncategorized; prime; composite.:- pred sieve(int::in, sieve::array_uo) is det.:- implementation.sieve(N, A) :- A0 = array.init(N, uncategorized), sieve(2, N, A0, A).:- pred sieve(int::in, int::in, sieve::array_di, sieve::array_uo) is det.sieve(N, Max, A0, A) :- ( N = Max -> A0 = A ; ( A0 ^ unsafe_elem(N) = uncategorized -> A1 = A0 ^ unsafe_elem(N) := prime, eliminate_factors(N, N, Max, A1, A2), sieve(N+1, Max, A2, A) ; sieve(N+1, Max, A0, A) ) ).:- pred eliminate_factors(int, int, int, sieve, sieve).:- mode eliminate_factors(in, in, in, array_di, array_uo) is det.eliminate_factors(Factor, N, Max, A0, A) :- ( N + Factor > Max -> A0 = A ; A1 = A0 ^ unsafe_elem(N + Factor) := composite, eliminate_factors(Factor, N + Factor, Max, A1, A) ).:- module main.:- interface.:- import_module io.:- pred main(io::di, io::uo) is det.:- implementation.:- import_module sieve, array, int, list, string, exception.:- func limit = int.limit = 0x01FFFFFF.main(!IO) :- sieve(limit, Sieve), put_prime(2, Sieve, !IO).:- pred put_prime(int::in, sieve::array_di, io::di, io::uo) is det.put_prime(N, Sieve, !IO) :- ( N = limit -> io.nl(!IO) ; unsafe_elem(N, Sieve) = C, ( C = prime, io.format("%d ", [i(N)], !IO), put_prime(N+1, Sieve, !IO) ; C = composite, put_prime(N+1, Sieve, !IO) ; C = uncategorized, throw("sieve failed") ) ).To build:$ mmc -i sieve$ mmc main sieve$ time ./main > /dev/nullreal 0m2.838suser 0m2.740ssys 0m0.096s

no

if you add a name and a tripcode to your posts we'll all know who the big-brain adult is around here :)

I read this wrong but it reminded me.


it seems like actually printing the primes to terminal takes longer than the seive it self. it's especially noticeable if it's all the primes between 2->10,000,000 or something.

It's probably the speed of the terminal. redirect to a file instead and see if it's faster.

time ./a.out 100000000 > resultsreal 0m6.453suser 0m6.276ssys 0m0.176stime ./a.out 100000000real 0m12.137suser 0m6.448ssys 0m0.380stime ./a.out 10000000 > resultsreal 0m0.485suser 0m0.472ssys 0m0.012stime ./a.out 10000000real 0m0.991suser 0m0.432ssys 0m0.048s
it looks like it takes almost exactly as long to print the results to terminal as it does to run the seive.

roll

Rollin'

roll

so my options are
084 - name art in ascii (boring)
184 - missile command game (less boring technically but still boring as a game)
(84%29+200) - IRC server and client
84 - surround a text file with asterisks
alright then. See you Sunday with an IRC client and server. emphasis on server.

roll

gimme something good

Here's the Mathematica version for this one. I do it for the fans, I will never let you down. >>813724

Prettier.

matrix = [[1,2],[3,4]]matrix.transpose

If its something 2hard4me I'm not going to do it.

Rerolling.

nigger... is u srs?

Not him, bet I could give that problem to most "professional developers" and they wouldn't know how to do it in C, especially without being provided a tree or hash table for storage.

you mean without going for the obvious O(N^2) solution right?
people treat hash tables as something that should be provided to you, but I bet you could still walk one of these developers through implementing a minimal hash table without much trouble.

Yeah, it's a big hint, but can be done in O(nlogn) time.

I was rolling for the first picture, if you'd notice there are two of them in the OP. I could probably do that challenge but it sounds boring.


I've already done a Snake game a few months ago.

example of a 'minimal hash table' for this problem:#include #include struct bucket { struct bucket *list; int key; int value; int valid;};struct hasht { int size; struct bucket *buckets;};struct getmode_acc { int value; int count;};typedef void (*ht_folder)(struct bucket *, void *);struct hasht *ht_create (int length) { struct hasht *ht = malloc(sizeof(struct hasht)); ht->buckets = malloc(sizeof(struct bucket) * length); ht->size = length; for (int i = 0; i < length; i++) { ht->buckets[i].list = NULL; ht->buckets[i].valid = 0; } return ht;}void ht_free (struct hasht *ht) { for (int i = 0; i < ht->size; i++) { for (struct bucket *b = ht->buckets[i].list; b;) { struct bucket *next = b->list; free(b); b = next; } } free(ht->buckets); free(ht);}void ht_fold (struct hasht *ht, ht_folder fn, void *acc) { for (int i = 0; i < ht->size; i++) { for (struct bucket *b = &ht->buckets[i]; b; b = b->list) { if (b->valid) fn(b, acc); } }}struct bucket *ht_get (struct hasht *ht, int key) { for (struct bucket *b = &ht->buckets[key % ht->size]; b; b = b->list) { if (b->valid && b->key == key) return b; if (!b->valid) { b->key = key; b->value = 0; b->valid = 1; return b; } if (!b->list) { b->list = malloc(sizeof(struct bucket)); b->list->valid = 0; b->list->list = NULL; } } abort();}void getmoder (struct bucket *b, void *void_acc) { struct getmode_acc *acc = void_acc; if (b->value > acc->count) { acc->count = b->value; acc->value = b->key; }}int getmode (int *a, int length) { struct hasht *counts = ht_create(length); for (int i = 0; i < length; i++) { ht_get(counts, a[i])->value++; } struct getmode_acc acc; acc.value = 0; acc.count = 0; ht_fold(counts, getmoder, &acc); ht_free(counts); return acc.value;}int main (int argc, char **argv) { if (argc < 2) { fprintf(stderr, "usage: %s [ ... ]\n", argv[0]); exit(1); } int *ints = malloc(sizeof(int) * (argc-1)); for (int i = 1; i < argc; i++) { ints[i-1] = atoi(argv[i]); } printf("%d\n", getmode(ints, argc-1)); return 0;}timing as written:$ time ./a.out 1 2 3 4 5 4 4 4 4 1 1 1 1 1 1 1 $(seq 1 39999) $(seq 1 20|perl -lne 'print 22')22real 0m0.039suser 0m0.026ssys 0m0.016stiming with ht_create(1) instead of ht_create(length) in getmode (i.e., this is just searching an association list as in Lisp on every lookup):$ time ./a.out 1 2 3 4 5 4 4 4 4 1 1 1 1 1 1 1 $(seq 1 39999) $(seq 1 20|perl -lne 'print 22')22real 0m2.781suser 0m2.767ssys 0m0.016s

...

ANIME GET THE FUCK OUT OF MY BOARD

roll

uhmm no, sweetie

checked

perl
my @d = ;print for (sort @d);__DATA__a300a1fgsa2fdsa10dfsa20srt

Are you a femanon?
Because that's probably the gayest answer I've ever read on programming threads. Maybe can you do worste with replacing the anime cancer with poneys, and ending your saying with a *tip*

Holla Forums is a Christian board. No false memeing and false witnessing allowed, unless you are not afraid of capital punishment by Our Lord.

...

How well does rosettacode.org/wiki/Averages/Mode#C run on your test input? That's an example of using a sorting approach instead of a map based one.

They sort the list, so they can find the number of distinct numbers in the list, and then the they just count the run lengths to build their frequency table.

on an i7-7700HQ, after s/double/int/ and taking inputs from the command line, the sorting approach is consistently slower, though only in the range of 10 ms to 40ms.

With input from a mmaped file containing 6 million 32-bit integers (so, "W\0\0\0" for the number 87), sorting does a lot worse, while the hashtable's numbers are about the same as for the command line. I timed it in different ways (loops of this 'loop', sleeps/no sleep), but this run is representative:$ export PS1='$ '$ for x in sortmode getmode; do echo $x; time ./${x}2 6mil.dat; donesortmodegot 1 modes: value = 24, count = 6304real 0m0.601suser 0m0.562ssys 0m0.040sgetmode24real 0m0.078suser 0m0.046ssys 0m0.033s$ for x in sortmode getmode; do echo $x; time ./${x} $(cat 6mil); donesortmodegot 1 modes: value = 49, count = 133real 0m0.098suser 0m0.059ssys 0m0.039sgetmode49real 0m0.079suser 0m0.058ssys 0m0.022s

(the '6mil' file there, without the .dat, only has 100k numbers in it.)

with a wider range of random numbers sorting does worse:got 6 modes: value = 254328, count = 9 value = 766833, count = 9 value = 4806620, count = 9 value = 5181859, count = 9 value = 5470730, count = 9 value = 5566819, count = 9real 0m1.007suser 0m0.967ssys 0m0.039sgetmode254328real 0m0.209suser 0m0.169ssys 0m0.040sOTOH it find all the modes whereas getmode picks the lowest one with this dummy hashtable, and should pick a random one with a real hash function.

Yeah that makes sense, as the sorting should be O(nlogn) vs O(n) for the hash table with (amortized O(1)).

Wew, I'm terrible at programming. I'm already stuck at the second problem in project euler

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Break it down. First of all, can you successively generate numbers from the Fibonacci sequence?

Never mind, I was able to fix it:
def fib(limit): a, fib, sumEven = 0, 1, 0 while fib < limit : a, fib = fib, fib + a if a % 2 == 0 : sumEven += a return sumEvenprint(fib(4000000))

My mistake was that I was adding the numbers from fib, but that always overshot the limit, so then I realised I could add the numbers from a, because they are always one step before fib

nevar forget

project euler is really shitty for programming challenges, its just all math

It's good but not for beginners. The focus on optimization is good and you get the joy of trying to convert math papers into code.

u wot m8

math isn't really going to help anons sort their hentai collection

programming challenges are good if you need some stuff to do while learning a language.
euler is not good because all problems revolve around math instead of allowing you to use different parts of your language to solve different problems.
verdict: its shit

conclusion: Project Euler is a math challenges site that describes problems in a computation-inviting matter.
a programming challenges site would keep forums open for early problems, at the very least.

No it's actually for when you know a language to an average level and want to really learn how code works.
Doing something like a sieve to calculate the sum of primes below 10^9 is a good exercise. It's about scaling your "simple" "elegant" solutions and realising you know almost nothing.

REMINDER

if your program doesn't pass valgrind with 0 memory leaks you have to rewrite it until it does

speaking of valgrind, i'm still trying to get the hang of C
this code is valgrinds demonstration of a memory leak
#include void f(void) { int* x = malloc(10 * sizeof(int)); x[10] = 0; // problem 1: heap block overrun } // problem 2: memory leak -- x not freed int main(void) { f(); return 0; }

is x not freed when the function f returns? I thought it was? do all variables/arrays you you allocated memory for with malloc need to be explicitly freed?

No of course it isn't freed. C doesn't reference-count or garbage-collect. malloc doesn't know that you didn't store it's return elsewhere. There are some other functions for your purpose. Look at related functions in the manpages.
Yes you have to explicitly free what you malloc, if you want it to be freed. You can use something like Boehm GC, but if you go that far you may as well use another language.

lol is this ironic

Not in C.
Variables in the stack are released when their scope ends.
Variables in the heap must be explicitly freed.

thanks, i don't know what i was thinking. i thought this code didn't work. i was messing around at some point and something like this wasn't working. i couldn't access the array outside of the function after returning a pointer to it when it was malloc'd. i tested this again it obviously works, so I don't know what the problem was.
#include #include char *f(void){ char *x = malloc(1 * sizeof(char)); x[0]='c'; return x;}int main(void){ char *a; a=f(); printf("%s",a); return 0;}
also reading on stack vs heap now i just realized the stack is supposed to be a lot faster. i think what i was trying to do earlier and fucking up on, is declaring the array as
char x=[1];
and then trying to return x, which wasn't going to work, because i guess that was on the stack and get's deleted when the function exits, while
char *x=malloc(sizeof(char));
is on the heap and does not.

From what I can tell, the only problem in your code here is that you are using the string format %s in printf when you should be using the character format %c. A string in C is 1 or more characters in an array followed by a '\0' null character. Try changing that and see what happens.

ya i know that's not the way it's supposed to be, it works fine though, gcc doesn't throw any errors. if i change the exact same code from %s to %c in the printf function, it won't take a pointer, gcc throws a warning and the output is fucked. i have to change it to
printf("%c",*a);

Because %c expects a char and %s expects a char *. Try compiling with -Wall and -pedantic and see what warnings pop up.

gcc -Wall -pedantic still throws no errors or warnings with

with the string "array" being a pointer to a single character

Neat.
I am guessing the output is 'c' then a bunch of characters, even control characters?
Maybe that's what hackers do to read protected memory?

no it's just 'c'. identical to sending printf a character with printf("%c",*a).

i was thinking about that too. I thought there was no way to know the length of the array without the null terminator. how does printf know that there's no more characters.

unless gcc knows and it's fucking with the output to prevent reading memory it shouldn't be.

it's called luck with your padding

you can definitely read into b's heap from a.
#include #include int main(void){ char *a=malloc(sizeof(char)); // allocate for single char char *b=malloc(50*sizeof(char)); // allocate a bunch more shit; b[5]='n'; b[6]='i'; b[7]='g'; b[8]='g'; b[9]='e'; b[10]='r'; a[0]='c'; printf("%s\n",a); //just outputs 'c' for (int i=0;i

luck. malloc does nothing. use calloc instead.

literally zero difference in the output. the A is still there.
#include #include int main(void){ char *a=(char*)calloc(1,sizeof(char)); // allocate for single char char *b=(char*)calloc(50,sizeof(char)); // allocate a bunch more shit; b[5]='n'; b[6]='i'; b[7]='g'; b[8]='g'; b[9]='e'; b[10]='r'; a[0]='c'; printf("%s\n",a); //just outputs 'c' for (int i=0;i

this gets even more trippy
#include #include int main(void){ char *a=(char*)calloc(1,sizeof(char)); char *b=(char*)calloc(50,sizeof(char)); a[0]='a'; a[1]='b'; //b-e haven't been allocated a[2]='c'; a[3]='d'; a[4]='c'; a[5]='e'; b[0]='d'; // why doesn't this overwrite a b[1]='i'; b[2]='n'; b[5]='n'; b[6]='i'; b[7]='g'; b[8]='g'; b[9]='e'; b[10]='r'; printf("a:%s\n",a); printf("a_overrun:"); for (int i=0;i

putting the callac for *b immediatly after a[0], a[1], etc, and before b[0]='d', doesn't change the output.

gcc -O0 -Wall -pedantic test.c
also shows no errors or warnings and the output is the same as
gcc test.c.
same with -O1 and -O2 and -O3

Verdict is you're a simpleton who belongs processing web forms. It's SUPPOSED to be about mathematical challenges you dumb nigger. Why you think it is called project Euler?

Optimization level makes no difference because calloc is a function. The code for it is in a lib so -Ox makes no difference. It'll never allocate just one byte because it's more efficient to waste a few bytes on small (and rare) allocations. Also sizeof(char) is just plain retarded since char is the one type the spec defines a size for.

The point is that math makes for a poor set of challenges as it has a narrow spectrum. Day to day programming doesn't have a lot to do with math.

...

not an argument

doesn't a have a lot to do with math beyond basic algebra.

Lol retard

When you use C, most of your math is manually keeping track of lengths.

keeping track of lengths is unnecessary

If you think day to day programming has much to do with math, your knowledge of math is very limited. Even doing gamedev, I'm rarely touching anything even slightly mathy, and gamedev doesn't usually go past basic trig these days.

Because each subsequent call to callac (or any *alloc) doesn't necessarily give you a piece of memory which continues from the last. Remember the order of allocations and deallocations can come in any arbitrary order, and memory that has been freed should be made available. The implementation of a heap/freestore is done with a linked list. Now to optimize against fragmentation, some operating systems use multiple "pools" of memory, say one for example one for small, medium, large allocations. In that case, your alloc of 1 char, might be very far away from b [Why don't you print the addresses of each pointer and find out?]

Are game engines so advanced these days that blue hairs don't even need to know elementary linear algebra?

Another point. I said that the heap is implemented with a linked list? Well the bookkeeping header to keep track of how big your allocated chunk of memory usually immediately precedes the area you're given to work with. Overwriting that means you'd corrupt your entire heap and enjoy a really nasty bug down the line, should you ever try to free that corrupted allocation.

Project Euler doesn't pretend to be for "day to day programming", it's computerized recreational mathematics. If is for an elite class of patricians who enjoy mathematics for its own sake, a concept beyond comprehension of the plebeian filth.

roll

But I want to see the header file too

Rolling for short Mathematica.

It's been Sunday for a while now. Post code, faggot.

that's interesting i'll look into that header. apparently gcc or gnu/libc might have some malloc stats or information functions i'm going to try to find those. i figured this would boil down to how the libraries/os/gcc is doing it behind the scenes.

most of the answers i find asking about this on stackoverflow are hilarious.

also if it's undefined behavior and i'm doing a nono why isn't gcc complaining about it? i get no warnings doing something like
char *a=malloc(100);a[500]='f';
and it totally works.

changing from
for (int i=0;i

roll

i guess this is the correct way to underrun. this shows much more interesting output. all the ascii characters are behind *a and *b.
the first 4 characters of *a are also behind *b, but not the rest.
#include #include int main(void){ char *a=(char*)calloc(1,sizeof(char)); char *b=(char*)calloc(50,sizeof(char)); a[0]='a'; a[1]='b'; //b-e haven't been allocated a[2]='c'; a[3]='d'; a[4]='e'; a[5]='f'; b[0]='d'; // why doesn't this overwrite a b[1]='i'; b[2]='n'; b[5]='n'; b[6]='i'; b[7]='g'; b[8]='g'; b[9]='e'; b[10]='r'; printf("a:%s\n",a); printf("a_underrun:"); for (int i=0;i

I assume by "primordial" they meant "primorial".

You're welcome, but of course you're going to get better answers here than StackOverflow! Yes, it is the operating system that ultimately decides how memory is managed. I remember one assignment from university where we had create a SLOB memory allocated in 68K asm. Fun stuff.

See these for some more details.
en.wikipedia.org/wiki/SLOB
en.wikipedia.org/wiki/Slab_allocation

let's roll

didn't understand the phrasing of the challenge. I've done plenty of multi-dimensional arrays before. what makes them dynamic?

ended up relearning some basics of vector math and thinking about how object based motion blur works instead.

Automatically resizing.

niggerlicious
#include #include #include #ifndef BIG_ENDIAN#define ascii_to_int16(s1, s2) s1 * 256 + s2#else#define ascii_to_int16(s1, s2) s2 * 256 + s1#endifint16_t roman_table[26] = { 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000, ascii_to_int16('I', 0), ascii_to_int16('I', 'V'), ascii_to_int16('V', 0), ascii_to_int16('I', 'X'), ascii_to_int16('X', 0), ascii_to_int16('X', 'L'), ascii_to_int16('L', 0), ascii_to_int16('X', 'C'), ascii_to_int16('C', 0), ascii_to_int16('C', 'D'), ascii_to_int16('D', 0), ascii_to_int16('C', 'M'), ascii_to_int16('M', 0),};int main(int argc, char** argv){ if (argc < 1) { return 1; } char romans[0x20]; long int dec = strtol(argv[1], 0, 10); if (dec < 1) { return 1; } int counter = 0; while (dec) { for (int i = 12; i>=0; --i) { if (roman_table[i]

resizing an existing array? you'd have to move everything to a different array of the desired size, wouldn't you? that would be retarded.

It's not retarded, quite common in fact. Usually you grow your array to 1.5 or so times the previous size each time, to cut down on the future number of resize operations.

rolling

can it grow indefinitely? that will cause a problem. or if it can't then you could just reserve that maximum size to begin with. I realize you would be reserving space that could be used differently in the mean-time (until your array needs it), but I guess I'm very much in a offline / traditional computer with finite space mindset. I can see how infinitely growing arrays could make sense in a server farm context. but if I wanted to get a machine with finite hard drive to do things then there's not much utility to making use of hard drive space that I know I will run out of eventually. it would be wise to plan ahead and make sure we never exceed the limitations. and at that point what could we do with the initially saved space, knowing we will have to give it up eventually?

also there's the fact that using the space more by writing an almost identical array over and over will wear down our physical device faster and take up processing time.

am I missing something? probably, I'm a noob.

just use a vector lmao

yeah you are a noob. You're such a noob that you've just worried that down might be up.
yes a strategy like "double the buffer each time we run out of memory" is a strategy without an upper bound. Generally you are responsible for imposing a limit if you want one.
Programming as if resources were infinite is appropriate for single-user desktop systems, and not for servers. It's not an issue of resources being plentiful or not; it's a matter of responsibility (the desktop is the property of the guy asking you to consume infinite memory: do as you're told; the guy who asked you to do that can see the consequences for the machine and learn not to do that again; a server meanwhile frequently performs tasks on behalf on untrusted users, who shouldn't be allowed to carry on a DOS attack via "hi guys I just bought a new album and song #1 is ".
disk space is irrelevant. the performance characteristics of hitting the disk vs. hitting RAM diverge so extremely that you're always explicitly working with one or the other. yes, swap exists, and if a typical webserver for example starts running out of swap what typically results is horrifying death.
doubling an array doesn't necessarily result in a move of that array; the memory allocator takes care of that. writing to memory over and over again is not a serious problem. the cost of moving the array is either miniscule in the face of the advantages of continuing to use an array (sequential access to memory is much faster than random access, also cache) vs. another structure, or you shouldn't be using an array in the first place.

im not doing that. re-rolling

lmao no it's not


This is only true for very specific types of programs and users.

grats, you disagree with ESR's cult of "0, 1, Many" even more than I do. Meanwhile this fellow I'm talking to is under the impression that server programming = working with clustered alien supercomputers with hot-extensible RAM. Please help me unconfuse him instead of making trivial objections.

...

Of course it has an upper bound, but as the programmer, you're in control of how much you're putting into the resizable data structure. If your requirements are humongous, then certainly you will fine tune the structure or use a more appropriate strategy. High level languages all provide resizable data structures, so this detail is elided from the thought process of those programmers.

I said it could grow 1.5 times just as a simple example to get the point across. In reality, fancier implementations will adjust the growth rate depending on the current size. In the beginning it will make sense to double, but as size increases, the rate will approach closer to 1. In some high level implementations of maps, I've seen the implementations make more radical changes, such as dynamically change the backing store depending on the size. Say switching between hash tables and tree structures, all without the programmer's knowledge.

Now lurk "The Art of Computer Programming" for 3 volumes.

is that an actual recommendation or are you just sharing that meme?

Reading Knuth is next to Godliness, user.

They're good books, not for everyone though. It really is computer science rather than software engineering.

If you want to hear snarky comments about the books from the "LOL tech moves so fast any text on tech is out of date as soon as it hits print because by that time 50 new javascript frameworks have arrived XDDDDD " crowd of web dev clowns, you'll find that here:
news.ycombinator.com/item?id=10897460
reddit.com/r/compsci/comments/24alae/has_anyone_actually_read_any_of_the_the_art_of/

I do recommend it. It is a worthy endeavour and will make you a better man.

Thanks. I'm looking for "classics" so to speak. I think I would do well to get closer to the metal so the further back in history the better (up to a point). All the frameworks on top of frameworks stuff doesn't interest me, I want to know how computers and programs really work from the bottom up, then write something that runs fast. It seems like the natural path for me. Whether I'm talented enough to get anywhere is a different question.

Has anyone ever taken him up on his autistic challenge?

I can read the whole thing. I haven't started yet, but I can.

This faggot deserves to be hung drawn and quartered. He epitomizes every fucking know it all dipshit I've encountered in the software industry.

Sounds like you'll really enjoy it. It is theoretical but covers fundamentals from the bottom up. Take your time with it though, it's not a book you can speed read.

There's this Steve Jobs one too.


< "You're full of shit," Knuth responded.

No book is a book I can speed read. I tend to read so thoroughly finishing books at all becomes a real problem.

Rolling for easy and normal.

gno. Reroll.

Crack open the hood fam.
youtube.com/watch?v=eJGzz6CBi8c

roll

I just drew that really quick with my clit mouse. best dick I've ever drawn.

gonna be doing a few rolls every so often so I've got stuff to do next time the power inevitably goes out for no reason.

Pajeet?

East Texas.

For the easy challenges, gitgud.io/m712/palin/
Chip-8 emulator sounds cool, I'll try to do it.

Roll !

another roll

binary search.... that's too easy

Not trying to nitpick but dynamic arrays are traditionally arrays that are set during run-time against static arrays which are set at compile-time. realloc'ing arrays however forces them into the dynamic category.

That's good, because you are wrong. You're confusing dynamic arrays with dynamically allocated arrays.

Rollan.

I guess I could do a simple pixel art frame by frame editor, but it'll take a long fucking time. I'll just do the 22 one for now so someone will bully me while I work on that.
def fact(num, mult = 1): if(num

I was going to poke fun at your TCO envy.

Doing it that way, instead of the easy but objectively wrong way makes it run a bit better on any language I tried (java, C, python), but fuck if it isn't as good as a Tail Recursion optimized language.
Java at least has the "our code is shit, the language will break if we implement tail recursion right now" excuse, but I still wish these language making nerds would care a bit about tail recursion.

roll

Heh. Well, to stay in the true spirit of the functional style you might as well code that as side-effect free, by moving the two statements into argument expressions.

Go for trips

hopefully something easy

rolling

// Challenge 03// Secure password generator// Note: Unicode 0x00 to 0x20 is blank, and 0x7F is del,// so we ignore those. package mainimport ( "math/big" "crypto/rand" "fmt") func main() { max := *big.NewInt(95)// 7F - 20 = 5F p := make([]rune, 8) for i := 0; i < len(p); i++ { n, _ := rand.Int(rand.Reader, &max) p[i] = rune(32 + n.Int64()) // we add 32 to avoid anything blank (0x20) } fmt.Println(string(p))}

you fucked up

Sorry, what?

your generated passwords only have ~53 bits of security. i wouldn't call that secure. it is barely enough assuming the server uses a proper pbkdf.

Oh, googled it. Just generate twice and concatenate them.

Roling for another easy one liner.

Reroll (already did)

I am so fucking smart!

I did the first 10 easy challenges in a day and accidentally `rm *`'d the folder. I meant to type `rm *~`. Now I don't want to program ever again

rolling

this should probably become a more generalized * number to text function which is why the buffer fuckery, but it was taking too long, I got lazy, and I wanted to avoid copypasting for every x10 up to a trillion etc.
#include #include #include // 1-19char *singles[19]= {"one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fiveteen","sixteen","seventeen","eighteen","nineteen"};char *doubles[8]= {"twenty","thirty","fourty","fivety","sixty","seventy","eighty","ninety"};struct dyn_buffer { int bufsize; int contentsize; char *buffer;};void appendtobuffer(struct dyn_buffer *buffer, char *content) { if ( (buffer->contentsize+strlen(content)) > buffer->bufsize ) { buffer->bufsize+=40; realloc(buffer->buffer, buffer->bufsize); printf("resized buffer to:%d\n",buffer->bufsize); } strcat(buffer->buffer,content);}char *numtostr(int number) { struct dyn_buffer strbuf; strbuf.buffer=malloc(40); strbuf.bufsize=40; strbuf.contentsize=0; if (number99) { appendtobuffer(&strbuf, "error"); // trim the buffer realloc(strbuf.buffer, strbuf.contentsize+1); return strbuf.buffer; } if (number0) { if (number

fuck looking at this now it memory leaks the buffer.

...

it was the end of the day lol

...

Well, you learned a valuable lesson on something of little worth. Think about what could have made that process safer.

I was thinking about playing games dropping the suffixes and storing them in a separate array to form the words but didn't and this was the result.

more string fuckery with this roll. dealing with strings in C is fun but I think I'm getting used to it. initially I used calloc but I imagine butting that into a loop along with free is a huge waste of performance, it's better to just make sure the char arrays are terminated right and use memcmp instead of strcmp.

palindrome
#include #include #include void reverse_string(char *dest, char *source, int src_length) { // don't copy the last character, null terminator (i>=1) for (int i=src_length; i>=1; i-=1) { //printf("dest[%d]=source[%d]=%c\n",(src_length-i), i-1, source[i-1]); dest[src_length-i]=source[i-1]; } //insert null terminator dest[src_length]=0;}int find_palindrome(char *str, char *palindrome) { int str_length=strlen(str); int str_start_index=0; int test_length=0; int p_length=0; char *test_string=malloc(strlen(str)+1); char *reverse_test_string=malloc(strlen(str)+1); while(str_start_index0) { printf("largest palindrome:%s\n",palindrome); } else { printf("no palindrome found\n"); }}

Let's roll

print eval $ARGV[0]

This:
To be fair the rm command sucks ass, you should write a "del" one that moves shit to a trash bin instead, and a "flushbin" one that does run rm on a trashbin.
Shouldn't be too hard.

(checked)
Stallman BTFO!

the roll

Easy roll.

Simple account management in Mathematica.

What is even the point

To complete the task.

Of you trying to compete with me? Very little. Accept Wolfram as your Lord and Saviour.

r o l l

first time messing with ncurses. the magic behind terminal programs dealing with the screen is gone.

I tried implementing a 7-segment led, which doesn't look the best, but it probably doesn't look great on an actual 7-segment led either.

digital clock
#include #include #include #include /* 7-segment led, 5x7 0001 21 2 3334 54 5 666*/static char seg_zero[7]={'X','X','X',' ','X','X','X'};static char seg_one[7]={' ',' ','X',' ',' ','X',' '};static char seg_two[7]={'X',' ','X','X','X',' ','X'};static char seg_three[7]={'X',' ','X','X',' ','X','X'};static char seg_four[7]={' ','X','X','X',' ','X',' '};static char seg_five[7]={'X','X',' ','X',' ','X','X'};static char seg_six[7]={' ','X',' ','X','X','X','X'};static char seg_seven[7]={'X',' ','X',' ',' ','X',' '};static char seg_eight[7]={'X','X','X','X','X','X','X'};static char seg_nine[7]={'X','X','X','X',' ','X',' '};static char seg_error[7]={'X','X',' ','X','X',' ','X'};void print_seg(char number, int column, int row) { char *seg; switch (number) { case 0: seg=seg_zero; break; case 1: // use also for colon seg=seg_one; break; case 2: seg=seg_two; break; case 3: seg=seg_three; break; case 4: seg=seg_four; break; case 5: seg=seg_five; break; case 6: seg=seg_six; break; case 7: seg=seg_seven; break; case 8: seg=seg_eight; break; case 9: seg=seg_nine; break; default: seg=seg_error; } mvprintw(row, column," %c%c%c \n",seg[0],seg[0],seg[0]); mvprintw(row+1, column,"%c %c\n",seg[1],seg[2]); mvprintw(row+2, column,"%c %c\n",seg[1],seg[2]); mvprintw(row+3, column," %c%c%c \n",seg[3],seg[3],seg[3]); mvprintw(row+4, column,"%c %c\n",seg[4],seg[5]); mvprintw(row+5, column,"%c %c\n",seg[4],seg[5]); mvprintw(row+6, column," %c%c%c \n",seg[6],seg[6],seg[6]); return;}void print_double(int number, int column, int row) { int tens=number/10; int singles=number%10; print_seg(tens, column, row); print_seg(singles, column+6, row); return;}void print_time(struct tm *time) { //print_double(time->tm_hour,0,0); print_double(10,0,0); print_seg(1,11,0); //1=: print_double(time->tm_min,19,0); print_seg(1,30,0); print_double(time->tm_sec,38,0);} int main(int argc, char *argv[]) { time_t rawtime; struct tm *local_tm; initscr(); cbreak(); timeout(1000); while(1==1) { time(&rawtime); local_tm=localtime( &rawtime ); print_time(local_tm); mvprintw(8,0,"press q or ctrl+c to exit\n"); char input=getch(); if (input=='q') { break; } refresh(); } endwin();}

i don't even know wtf that means, reroll

A group? It's a simple algebraic structure consisting of an operation, a (non empty) set and three axioms. I can explain it if you wish.

not bad user, but it could use a little polish.#include #include #include #include /* 7-segment led, 5x7 0001 21 2 3334 54 5 666*/static char digits[11][7] = { {'X','X','X',' ','X','X','X'}, {' ',' ','X',' ',' ','X',' '}, {'X',' ','X','X','X',' ','X'}, {'X',' ','X','X',' ','X','X'}, {' ','X','X','X',' ','X',' '}, {'X','X',' ','X',' ','X','X'}, {' ','X',' ','X','X','X','X'}, {'X',' ','X',' ',' ','X',' '}, {'X','X','X','X','X','X','X'}, {'X','X','X','X',' ','X',' '}, {'X','X',' ','X','X',' ','X'},};void print_seg(char number, int column, int row) { char *seg = digits[(number > 9 || number < 0) ? 10 : number]; mvprintw(row, column," %c%c%c \n",seg[0],seg[0],seg[0]); mvprintw(row+1, column,"%c %c\n",seg[1],seg[2]); mvprintw(row+2, column,"%c %c\n",seg[1],seg[2]); mvprintw(row+3, column," %c%c%c \n",seg[3],seg[3],seg[3]); mvprintw(row+4, column,"%c %c\n",seg[4],seg[5]); mvprintw(row+5, column,"%c %c\n",seg[4],seg[5]); mvprintw(row+6, column," %c%c%c \n",seg[6],seg[6],seg[6]);}void print_double(int number, int column, int row) { int tens=number/10; int singles=number%10; print_seg(tens, column, row); print_seg(singles, column+6, row);}void print_time(struct tm *time) { //print_double(time->tm_hour,0,0); print_double(10,0,0); print_seg(1,11,0); //1=: print_double(time->tm_min,19,0); print_seg(1,30,0); print_double(time->tm_sec,38,0);}int main(int argc, char *argv[]) { time_t rawtime; initscr(); cbreak(); timeout(1000); for (;;) { time(&rawtime); print_time(localtime(&rawtime)); mvprintw(8,0,"press q or ctrl+c to exit\n"); char input=getch(); if (input=='q') { break; } refresh(); } endwin();}

ugh, you used hard tabs. and I used an editor that hid that from me. hence the odd indentation.

thanks i'm sure i could figure it out, but i'm trying to learn the libraries and the language, not math atm.


i was thinking i should have put those in a 2d array.
this is some wizardry though:
char *seg = digits[(number > 9 || number < 0) ? 10 : number];
I didn't even know that was a thing. I didn't know you could do that and it took me a second to even figure out what the fuck to search for, "conditional operators".
I don't think I've ever seen that used.

the fact that you can stick what's the equivalent of an if/else statement inside of a variable declaration blows my mind. list comprehensions in python are the closest I can think of. looking it up i guess python has them too, I've just never used them or known about them.

speaking of python... the nim equivalent of C's ternary operator is a little more obvious:const curses = "libncurses.so.5"template fucking(n: untyped): untyped = proc n {.dynlib: curses, importc, noconv.}fucking initscrfucking endwinfucking cbreakfucking refreshproc timeout(n: int) {.dynlib: curses, importc.}proc mvprintw(x,y: int, s: cstring) {.dynlib: curses, importc: "mvprintw", varargs.}proc mvprintw2(x,y: int, s: cstring, a, b: char) {.dynlib: curses, importc: "mvprintw", varargs.}proc mvprintw3(x,y: int, s: cstring, a, b, c: char) {.dynlib: curses, importc: "mvprintw", varargs.}proc getch(): char {.dynlib: curses, importc.}const digits = [ ['X','X','X',' ','X','X','X'], [' ',' ','X',' ',' ','X',' '], ['X',' ','X','X','X',' ','X'], ['X',' ','X','X',' ','X','X'], [' ','X','X','X',' ','X',' '], ['X','X',' ','X',' ','X','X'], [' ','X',' ','X','X','X','X'], ['X',' ','X',' ',' ','X',' '], ['X','X','X','X','X','X','X'], ['X','X','X','X',' ','X',' '], ['X','X',' ','X','X',' ','X'],]proc print_seg(n, column, row: int) = let seg = digits[if n > 9 or n < 0: 10 else: n] mvprintw(row, column," %c%c%c \n",seg[0],seg[0],seg[0]) mvprintw(row+1, column,"%c %c\n",seg[1],seg[2]) mvprintw(row+2, column,"%c %c\n",seg[1],seg[2]) mvprintw(row+3, column," %c%c%c \n",seg[3],seg[3],seg[3]) mvprintw(row+4, column,"%c %c\n",seg[4],seg[5]) mvprintw(row+5, column,"%c %c\n",seg[4],seg[5]) mvprintw(row+6, column," %c%c%c \n",seg[6],seg[6],seg[6]) proc print_double(n: range[0 .. 59], column, row: int) = let tens = n div 10 singles = n mod 10 print_seg(tens, column, row) print_seg(singles, column+6, row) import timesproc print_time(`when`: TimeInfo) = print_double(`when`.hour,0,0) print_seg(1,11,0) print_double(`when`.minute,19,0) print_seg(1,30,0) print_double(`when`.second,38,0) setControlCHook(proc() {.noconv.} = quit())initscr()addQuitProc(endwin)cbreak()timeout 1000while true: getTime().getLocalTime.printTime mvprintw 8, 0, "press q or ctrl+c to exit" if getch() == 'q': break refresh()disclaimer: I'm like a day into learning Nim

i've never heard of nim. looking it up it looks interesting
python's equivalent is backwards
a=(x+5) if (a>b) else 0
which looks almost exactly like list comprehensions
a=[ (x+5) for x in range(10) ]

rolling

For the easy challenge, in Python 2.7 :
print(reduce(lambda x,y: x+y,range(int(input("n = "))+1)))
Can't start the markov chain one right now, but I will later in the day, it's just the right amount of difficulty for me.

you do realise that can be O(1) right?

Is this by order of difficulty?
Are we allowed to skip some?

I don't think so. No, you cannot skip, the roll is the future you chose.

This.

O(1) algorithms aren't always the best choice if the constants are relatively large for small N and you'll never reach very large N.

Stop making a fool of yourself, there are no large constants in this case.
Arithmetic series: n*(n+1)/2.

I was just speaking generally, not about that case.

proc sumUpTo(n: int): int = for x in 0 .. n: result += x100_000_000.sum_up_to.echotakes about a second to run.proc sumUpTo(n: int): int = for x in 0 .. n: result += x template sumUpToFast(n: int): int = const sum = sumUpTo(n) sum100_000_000.sum_up_to_fast.echotakes about a millisecond to run.
had to recompile nim itself though. can only have compiler/vmdef.nim:MaxLoopIterations iterations in compile-time loops

rolling for easy

TRIGGERD
That won't work because the n comes in at run time.

... unless your compiler lets you pre-calculate those values (up to say a large N) and load them into data immediately. As in, compile time memoizing.

#include int prime_after(int n){ if (n < 2) return 2;keep_it_up: for (int i = 2, n2 = ++n / 2; i

Rollan

#include uint64_t reverse_num(uint32_t n){ uint8_t digits[10]; uint8_t i = 0; for (; n; ++i, n /= 10) digits[i] = n % 10; uint64_t res = 0; for (uint64_t j = 1; i--; j *= 10) res += digits[i] * j; return res;}int main(){ std::cout

wild. As much as I've avoided C++, I'm still surprised that I never noticed that it had that 1'234 numeral syntax.proc reverse_num(n: uint32): uint64 = var m = n while m > 0'u32: result = (result * 10) + (m mod 10) m = m div 10 echo 1_234_567.reverseNumecho 4_123_456_789'u32.reverseNum

Late night quick roll.

Nice and quick.

#include #include #include std::string_view shortest_word(std::string_view s){ constexpr auto part_of_word = [](char c){ return std::isalpha(c) || c == '\''; }; size_t start = 0, finish = ~size_t(0); const auto check_if_shortest = [&](size_t a, size_t b){ if (b - a < finish - start) start = a, finish = b; }; size_t i, j = 0; for (;;) { if (j == s.size()) goto get_out; if (part_of_word(s[j])) { i = j; break; } search_for_more: ++j; } do { if (++j == s.size()) { check_if_shortest(i, j); goto get_out; } } while (part_of_word(s[j])); check_if_shortest(i, j); goto search_for_more; get_out: return finish + 1 ? s.substr(start, finish - start) : "";}int main(){ std::cout

#include #include #include templateT mode_of(const T* arr, size_t sz){ std::unordered_map n; while (sz --> 0) ++n[arr[sz]]; return std::max_element(n.begin(), n.end(), [](auto&& a, auto&& b){ return a.second < b.second; })->first;}template inline T mode_of(const T(& arr)[sz]) { return mode_of(arr, sz); }int main(){ int arr[] = {45, 78, 1, 3, 45, 2, 1, 1, 67, 78, 67, 45, 3, 2, 45, 45, 2}; std::cout

Have to leave in four minutes. Quickest roll ever please.

Phew.

We don't have a cyclical blogposting thread so I'll just post this here, tangentially related. polite sage

I'm not in CS nor am I a programmer, but it still feels bad man.

creating problems and fixing them is how learning occurs.

stop using Cjeet and Cjeet++ and use rust intead

...

pajeets are too dumb for rust. What's your excuse, brainlet?

github.com/RustIndia/Rust

reroll

Brainlet manchild goes to GitHub, Sees code of conduct, doesn't feel good and changes - AUTISM. Many such cases!

hmm, you're right, that's not nearly prominent enough. They need to have CoC links at the top and also on every single line after. Otherwise it's not welcoming, and otherwise I won't be sure enough that the men in the community are aware of any rules like "don't rape me" or "don't assume my gender". Without more CoCs how will they get female streetshitters?

this comment violates the rust code of conduct.
-Deliberate misgendering.
-Unwelcome comments regarding a person’s lifestyle choices
-Offensive comments related to gender, gender identity
-Sustained disruption of discussion

also no virtual rape allowed, and racism allowed against straight people, white people, or men.

forgot other pic

Good god. Can you imagine how disputes over pull requests go with those clowns.

Also roll.

#include #include void higher_lower_computer_guesses(int lower, int higher){ if (lower > higher) std::swap(lower, higher); std::cout

#include #include #include #include void greet(){ static const std::unordered_set persona_non_grata = { "Ajit Pai", "Steve Klabnik", "Bill Gates", "Mark Zuckerberg", "Larry Page", "Sergey Brin", "The AIDS-ridden corpse of Steve Jobs", }; std::cout

import sets, strutilsconst persona_non_grata = [ "Ajit Pai", "Steve Klabnik", "Bill Gates", "Mark Zuckerberg", "Larry Page", "Sergey Brin", "The AIDS-ridden corpse of Steve Jobs",].toSetwrite stdout, "Hi, what's your name? "let name = read_line(stdin)if name.all_chars_in_set(Whitespace): echo "Nice name, loser."elif name in persona_non_grata: echo "Fuck off."else: echo "Greetings, " & name & ". How are you today?"I'm liking all this C++ actually. Please define some classes so that I can stop liking it.

#include #include #include std::string to_text(uint8_t num){ if (num > 99) return "too many"; static constexpr const char* units[20] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}, * tens[10] = {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; if (num < 20) return units[num]; uint8_t low = num % 10, high = num / 10; return tens[high] + (low ? std::string("-") + units[low] : std::string());}std::string capitalized(std::string s){ s[0] = std::toupper(s[0]); return std::move(s);}void bottles_of_beer(){ for (auto [i, cur, s] = std::tuple(99, to_text(99), std::string("s")); i;){ std::cout

>#include

roll for easy

There you go,
#include #include templateclass linked_list{ class node { public: node(std::unique_ptr node_, const T& datum_) : list_(std::move(node_)), datum_(datum_) {} T& get() { return datum_; } const T& get() const { return datum_; } linked_list& next() { return list_; } const linked_list& next() const { return list_; } private: linked_list list_; T datum_; };public: linked_list() {} auto& insert(const T& t) { next_ = std::make_unique(std::move(next_), t); return *this; } auto& remove() { next_ = std::move(next_->next().next_); return *this; } operator bool() const { return next_ != nullptr; } auto* operator->() { return next_.get(); } const auto* operator->() const { return next_.get(); }private: linked_list(std::unique_ptr next_) : next_(std::move(next_)) {} std::unique_ptr next_;};int main(){ linked_list muh_list; muh_list.insert(1).insert(2).insert(3); muh_list->next()->next().remove().insert(6); for (const auto* cur = &muh_list; *cur; cur = &(*cur)->next()) std::cout get()

roll

Rolling.

Another one, maybe something more challenging.

needed experience with gtk, so i wrote this for gtk with

changes. can't believe it even works. looks even worse but it's a 7-segment in text. i expected more problems which makes me nervous. Did the UI with glade, which in typical gnome fashion required compiling from source because the existing version in the repo's immediately pinned a cpu to 100% and started leaking ram, even after you closed the window, whenever you added a button. The XML glade shits out is readable but long so I'm not going to post it unless anyone really cares. It's just 7 labels inside a grid inside a window.
#include #include #include #include #include /* 7-segment led, 5x7 0001 21 2 3334 54 5 666*/static char digits[11][7] = { {'X','X','X',' ','X','X','X'}, {' ',' ','X',' ',' ','X',' '}, {'X',' ','X','X','X',' ','X'}, {'X',' ','X','X',' ','X','X'}, {' ','X','X','X',' ','X',' '}, {'X','X',' ','X',' ','X','X'}, {' ','X',' ','X','X','X','X'}, {'X',' ','X',' ',' ','X',' '}, {'X','X','X','X','X','X','X'}, {'X','X','X','X',' ','X',' '}, {'X','X',' ','X','X',' ','X'},};static char led_names[8][6] = { "led_0","led_1","led_2","led_3","led_4", "led_5","led_6","led_7"};void gen_seg_str(char number, char *seg_str) { char *seg = digits[(number > 9 || number < 0) ? 10 : number]; char row[7][8]= { {' ',seg[0],seg[0],seg[0],' ','\n','\0'}, {seg[1],' ',' ',' ',' ',seg[2],'\n','\0'}, {seg[1],' ',' ',' ',' ',seg[2],'\n','\0'}, {' ',seg[3],seg[3],seg[3],' ','\n','\0'}, {seg[4],' ',' ',' ',' ',seg[5],'\n','\0'}, {seg[4],' ',' ',' ',' ',seg[5],'\n','\0'}, {' ',seg[6],seg[6],seg[6],' ','\n','\0'} }; strcpy(seg_str,row[0]); for (int i=1;itm_hour/10),seg_str); gen_seg_str( 1,seg_str); gtk_label_set_text(label,seg_str); label=GTK_LABEL(gtk_builder_get_object(builder,led_names[1])); //gen_seg_str( (local_tm->tm_hour%10),seg_str); gen_seg_str( (local_tm->tm_hour%10),seg_str); gtk_label_set_text(label,seg_str); label=GTK_LABEL(gtk_builder_get_object(builder,led_names[2])); gen_seg_str( 1,seg_str); //1=: gtk_label_set_text(label,seg_str); label=GTK_LABEL(gtk_builder_get_object(builder,led_names[3])); gen_seg_str( (local_tm->tm_min/10),seg_str); gtk_label_set_text(label,seg_str); label=GTK_LABEL(gtk_builder_get_object(builder,led_names[4])); gen_seg_str( (local_tm->tm_min%10),seg_str); gtk_label_set_text(label,seg_str); label=GTK_LABEL(gtk_builder_get_object(builder,led_names[5])); gen_seg_str( 1,seg_str); //1=: gtk_label_set_text(label,seg_str); label=GTK_LABEL(gtk_builder_get_object(builder,led_names[6])); gen_seg_str( (local_tm->tm_sec/10),seg_str); gtk_label_set_text(label,seg_str); label=GTK_LABEL(gtk_builder_get_object(builder,led_names[7])); gen_seg_str( (local_tm->tm_sec%10),seg_str); gtk_label_set_text(label,seg_str);}int main(int argc, char *argv[]) { GtkBuilder *builder; GObject *window; gtk_init(&argc, &argv); builder=gtk_builder_new(); gtk_builder_add_from_file(builder, "ascii_clock_gtk.ui",NULL); window=gtk_builder_get_object(builder,"window"); g_signal_connect(window,"destroy",G_CALLBACK (gtk_main_quit), NULL); g_timeout_add_seconds(1, update_labels,builder); gtk_main();}

i just spent the last hour trying to figure out how the hell to statically link gtk3 into the executable, to run on systems without it. there doesn't seem to be much information about it. the linker can't find the libraries with -static, and neither can I. Are they not included in the package with the dev shit? I've gotta figure out how the linking works more in general, but presumably if I can compile and run it on my system, the libraries have to be fucking somewhere, why can I not include them into the executable. The best I can find is compilation guide on the gnome wiki for gtk3. Is that what I have to do, compile gtk3 myself? is it not in the package manager? If I don't have the libraries, how the fuck am I running this to begin with?
I'm compiling this at the moment with
#!/bin/bashgcc `pkg-config --cflags gtk+-3.0` -o a.out $1 `pkg-config --libs gtk+-3.0`
adding -static is obviously way too easy of a solution. it finds some of the libraries pkg-config shits out, but not gtk-3.

nice.

roll

In order to statically compile a library in, it has to be statically compiled itself. You can probably check if you have installed with
ls -l /usr/lib | grep libgtk.\*\\.la

Surely the linker could chase down all the requisite dependencies anyways?

How to do proper animations on a GTK aplication? So far I've done this:
- Create a GtkDrawingArea
- Add draw callback to advance to next frame
- Add 60/s timeout to do gtk_widget_queue_draw(widget);
It works but there's a bit of screentearing, might be my drivers/compositor though. Is there a better way of doing this? I want to have bezier animations as shit. How to implement/learn about bezier interpolation?

If they are installed, then yes. The command I suggested would have given output showing you if they were installed, else it would have produced no output at all.
If you simply have the .so files for the library you can only dynamically link against it. You have to have the .la files to statically link against it.

Ahh I see.

Big ol' state + register machine with some recursion for good measure: #include #include #include #include int parse_arithmetic_consume(std::string_view& s, bool(* end_of)(const std::string_view&)){ static constexpr auto add = +[](int a, int b){ return a + b; }, sub = +[](int a, int b){ return a - b; }, mul = +[](int a, int b){ return a * b; }, div = +[](int a, int b){ return a / b; }; static constexpr auto get_op = +[](char c){ switch (c){ case '+': return add; case '-': return sub; case '*': return mul; case '/': return div; default: return (int(*)(int, int))nullptr; } }; int acc[2] = {0, 0}, val = 0; auto acc_op = add, val_op = add; bool neg = false; const auto accumulate = [&]{ if (neg) { val = -val; neg = false; } if (val_op == add || val_op == sub){ acc[0] = acc_op(acc[0], acc[1]); acc[1] = std::exchange(val, 0); acc_op = val_op; } else acc[1] = val_op(acc[1], std::exchange(val, 0)); };seek_value: for (;; s.remove_prefix(1)){ if (end_of(s)) goto finished; else if (s[0] == '-') neg = !neg; else if (s[0] == '(') goto parse_inner_expression; else if (isdigit(s[0])) goto parse_value; }parse_value: for (;; val *= 10){ val += s[0] - '0'; s.remove_prefix(1); if (end_of(s)){ accumulate(); goto finished; } else if (!isdigit(s[0])){ accumulate(); goto seek_op; } }parse_inner_expression: s.remove_prefix(1); val = parse_arithmetic_consume(s, +[](const std::string_view& s){ return s.empty() || s[0] == ')'; }); accumulate(); if (s.empty()) goto finished; s.remove_prefix(1); if (end_of(s)) goto finished; goto seek_op;seek_op: for (;;){ if ((val_op = get_op(s[0]))){ s.remove_prefix(1); goto seek_value; } s.remove_prefix(1); if (end_of(s)) goto finished; }finished: return acc_op(acc[0], acc[1]);}int parse_arithmetic(std::string_view s, bool(* end_of)(const std::string_view&) = +[](const std::string_view& s){ return s.empty(); }){ return parse_arithmetic_consume(s, end_of);}int main(){ std::cout

Daily Mathematica quick roll.

...

thanks for the info, i ran it, I don't have those .la files. I did manage to download and compile gtk-3 with enable-static, and it did generate those .la files, but pointing gcc at that directory with
gcc ....... -L(dir with gtk .la files) -lgtk+-3.0 ....
didn't work.

I have to play more games with it. From what I read the linker needs .a files, not the .la files, which aren't actually the static libraries (stackoverflow.com/questions/12237282/whats-the-difference-between-so-la-and-a-library-files). when i compiled gtk-3.0 with enable-static it either didn't generate those .a files or I didn't find the directory they're in. It would be nice if *buntu had a package for this, but I don't think it does, or i can't find that either.

It's a much bigger deal that I thought. From what I gathered I don't just need to compile gtk-3 with static libraries, I'm going to need to compile it's whole dependency tree with static libraries.

It seems like it's more effort than it's worth but now I want to be able to do it atleast once with some simple gtk program, just to have done it. It would be nice in the future if I write something to not have to prefix the installation with 'step 1, even though i'm giving you the binary please install these 100 packages first to run it'.

It looks like there are static built libraries available for to cross compile to windows, but that's a whole different game.

Whoops, sorry for getting those mixed up. I shouldn't have confused them considering I recently created a .la file manually for some OpenGL library.
If you are worried about dependencies you can bundle dependencies along with your application. I know teamspeak takes this approach. Another thing you could look into are snappies / flatpack memes.

apparently what I need to do here is use "ar" to take all the .o files after i finish compiling them with static enabled and turn them all into one big ".a". file. I'm going to try that now, I'm sure it's going to be a big fucking mess. I'll have to try bundling dependencies too. I take it that means copying all of the .so library files into the build directory and telling the compiler to specifically link to those instead of the default directories.

actually i didn't need to do any of that. just run make install on gtk after compiling and it generates them for you, preferably after giving configure a prefix that doesn't shit up your system.

finally, it works. a.out now 37MB.
gcc $1 `pkg-config --static --cflags gtk+-3.0` -static -static-libgcc -o a.out -Wl,-dynamic-linker=/lib64/ld-linux-x86-64.so.2 -Wl,-Bstatic -L$GTK_BUILD_DIR/lib/ -lgtk-3 -lgdk-3 -Wl,-Bdynamic -latk-bridge-2.0 -latspi -ldbus-1 -lpthread -lsystemd -lgio-2.0 -lXinerama -lXi -lXrandr -lXcursor -lXcomposite -lXdamage -lXfixes -lwayland-cursor -lwayland-egl -lwayland-client -lmirclient -lprotobuf-lite -pthread -lpthread -lxkbcommon -lmircore -lmircookie -lepoxy -ldl -lpangocairo-1.0 -lpangoft2-1.0 -lharfbuzz -lgraphite2 -lpango-1.0 -lm -latk-1.0 -lcairo-gobject -lcairo -lz -lpixman-1 -lfontconfig -lexpat -lfreetype -lexpat -lfreetype -lz -lpng16 -lm -lz -lm -lpng16 -lm -lz -lm -lxcb-shm -lxcb-render -lXrender -lXext -lX11 -lpthread -lxcb -lXau -lXdmcp -lgdk_pixbuf-2.0 -lm -lpng16 -lm -lz -lm -lz -lgio-2.0 -lz -lresolv -lselinux -lmount -lgmodule-2.0 -pthread -ldl -lgobject-2.0 -lffi -lglib-2.0 -pthread -lpcre -pthread -lrt
you can apparently mix static/dynamic loading with -Wl,-Bstatic and -Wl,-Bdynamic. gdk-3 and gtk-3 are what i built static libraries for, that links statically, the laundry list of shit after dynamic is what I would have to build static libraries for to link for a fully static binary lol. it works though, ldd a.out shows a bunch of dynamic links but nothing for gtk-3 or gdk-3, and it's now 37mb instead of the few k it was before.
i also had to specify -Wl,-dynamic-linker=/lib64/ld-linux-x86-64.so.2 or some fucking reason, because what gcc was shitting out kept reporting not found when trying to execute, some research later, readelf -l a.out shows "Requesting program interpreter /lib/ld64.so.1", which wasn't there. ldd had a dynamic link to it, but that was irrelevant apparantly, specifying the link switch solved the problem.

what a mess.

opengl?

Need to learn it.

#lang racket(define elems (vector "I" "AM" "A" "OR" "AND" "JUICE" "RUM"))(define nb-el (vector-length elems))(define weights (vector (vector 0 1 0 0 0 0 0) (vector 0.45 0 0.45 0 0 0.05 0.05) (vector 0 0 0 0 0 0.5 0.5) (vector 0 0.1 0.1 0 0 0.4 0.4) (vector 0 0.1 0.1 0 0 0.4 0.4) (vector 0 0.2 0 0.4 0.4 0 0) (vector 0 0.2 0 0.4 0.4 0 0) ))(define (get-new-index prev-i) (define (helper fac n) (begin (set! fac (- fac (vector-ref (vector-ref weights prev-i) n))) (if ( n 0) (string-append (vector-ref elems i) " " (helper (- n 1) (get-new-index i))) "." ) ) (helper n first-i))

I guess I should group tokens into categories like nouns, verbs, and stuff to make the declaration of weight matrixes easier, but I'm cognitively unable to go down that rabbithole right now


Oh yeah the Gauss trick... I'm too much of a mathlet to remember that kind of things tbh senpai

Nothing makes girls hornier than a closed-form solution user. You can just grab them by the pussy, and when you program in Mathematica (a functional language by the way), they let you do it.

Quick roll.

Reroll, boring.

wrong

...

I'm curious as to why you'd say that. It's not a purely functional language like Haskell, but it is just as functional as multi-paradigm languages like lisp or in the case I was referring to, Racket. Procedural programming is possible (and in some cases it makes sense), but that style is often discouraged in Wolfram language.

this version is far superior, rolling and i'm rounding down to the first medium.

roll

I'm already doing that with Nlang. Reroll

gno thank you I value my time

Roll, see you soon when I have the time.

roll

Roll

rolla

Rollan on the easy list

Shit, doing something in a new language( (scheme) ) takes a lot more when you don't have a lot of time:

(define next-char (lambda (c n) (integer->char (+ (char->integer c) n))))(define j (lambda (l n) (if (= (length l) 1) (cons (next-char (first l) n) ()) (cons (next-char (first l) n) (j (list-tail l 1) n)))))(define f (lambda (s n) (list->string (j (string->list s) n))))
I didn't even check for capitals and numbers, whatever. I'm going to try to do the ones on the other lists, too.