[–]▶ No.812872>>813414 >>814436 >>815118 >>815849 >>815918 >>823198 >>823367 >>826587 [Watch Thread][Show All Posts]
Roll you dices, and enhance your skills.
Purpose other lists of challenges.
▶ No.812893>>812929
▶ No.812911
▶ No.812929
>>812893
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)))
▶ No.812944>>812955
▶ No.812946>>812947
▶ No.812947>>812949
>>812946
Rolling again, Monty-Hall problem is boring. Switch every time, 2/3 chance vs 1/3 chance.
▶ No.812949
>>812947
Done in Mathematica, too easy..
> b-but you didn't do anything.
< Quiet kid, I've got money to make.
▶ No.812955>>812979
>>812944
// Author: Karlie Klossy
// This is a function that turns celsiuses into fahrenheits :PP
fn 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 privilege
a = a + 4.0f32;
return a;
}
▶ No.812979>>812993 >>813100 >>813113
>>812955
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 100
216.0
$ ./fahrenheit -p 100
212.0
▶ No.812993>>812997 >>813001
>>812979
Did you really need two cases there?
▶ No.812997>>813001
>>812993
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.
▶ No.813001>>813220
>>812997
Ahh.
>>812993
I got 93 there, so here's another 93 solution. What is the best language, and why is it always mathematica?
▶ No.813100
>>812979 (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 back
begin
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: 4
Your guess? 0
Correct digits: 1
Your guess? 16#C08CB#
Correct digits: 5
▶ No.813106
▶ No.813113>>813119
>>812979
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] <celsius>");
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: https://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.
▶ No.813119>>813120
>>813113
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.
http://www.ada-auth.org/standards/12rm/html/RM-TOC.html
The standard library is in the appendix.
▶ No.813120>>813121
>>813119
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 -h
usage: ./fahrenheit2 [-p] <celsius>
-p enables patriarchal, womyn-oppressing math, for TOTAL SHITLORDS.
raised FAHRENHEIT2.USAGE : fahrenheit2.adb:21
▶ No.813121>>813125
▶ No.813125>>813139
>>813121
thanks anon. 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] <celsius>");
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.
▶ No.813139
>>813125
>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.
▶ No.813157>>813159
▶ No.813159>>813160
>>813157
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)))))
▶ No.813160
>>813159
Fileout is (concatenate file "-without-whitespace")
Not directly pointing towards any file.
▶ No.813195
>>813182
use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};
const ORDER: usize = 3;
#[derive(Default)]
struct Lookup {
map: HashMap<[String; ORDER], Vec<String>>,
}
struct Generator<'a> {
lookup: &'a Lookup,
state: [String; ORDER],
rng: Rng
}
struct Rng(u64);
impl Lookup {
fn extend<I>(&mut self, iter: I) where I: Iterator<Item=String> {
let mut state: [String; ORDER] = Default::default();
for s in iter {
self.map.entry(state.clone()).or_insert_with(|| Vec::new()).push(s.clone());
push(&mut state, s);
}
}
fn generate(&self) -> 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<'a> Iterator for Generator<'a> {
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
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 <= limit {
return tmp % max;
}
}
}
}
fn main() {
let mut lookup = Lookup::default();
lookup.extend(include_str!("../lol.txt").split(' ').map(|s| s.to_owned()));
let mut len = 0;
for s in lookup.generate().take(150) {
print!("{} ", s);
len += s.len();
if len >= 80 {
println!();
len = 0;
}
}
println!();
}
fn push<T>(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
fuck
until 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.806654
File (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
▶ No.813197>>813200
rollin, need to git gud in C
▶ No.813199
Rolling
I'm a first semester C++ student, so this better not destroy my will to live
▶ No.813200>>813243 >>813271
>>813197
>find the longest common substring
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.
▶ No.813220>>813243
>>813001
>apple logo
>mathematica
fag detected. enjoy your square brackets kid
▶ No.813243>>813271
>>813200
I'll do it in mathematica
LongestCommonSubsequence[s1, s2]
>>813220
Enjoy!
▶ No.813251>>813253
▶ No.813253
>>813251
$_is.Prime(self.primality.map{|s| s.test_is_prime}) [ n : deriving __int64__ -> m bool ]
done
▶ No.813271>>813314 >>815850
>>813200
this is a mess. i figured out how to deal with unknown length files/strings though which was the ultimate goal.
>>813243
fucking hell
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct read_file_response {
int count;
char* buffer;
};
/* read an unknown length file given filepath
return 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<response.count;start_i++)
{
for (int end_i=start_i+1; end_i<response.count;end_i++)
{
int sub_length=end_i-start_i;
char *sub=malloc(sub_length);
int sub_i=0;
for (int c_i=start_i; c_i<end_i+1; c_i++)
{
/*printf("%c",response.buffer[c_i]);*/
char c=response.buffer[c_i];
if (c!='\n')
{
sub[sub_i]=c;
sub_i+=1;
}
}
int sub_count=countSubstring(sub,response.buffer);
if (sub_count>1 && sub_length>highest_len)
{
highest_sub=sub;
highest_len=sub_length;
}
}
}
printf("highest_len:%s length:%d\n",highest_sub,highest_len);
}
rolling for another one.
▶ No.813282>>813286
▶ No.813286
>>813282
print("Number? ");
INT n; read((n, new line));
printf(($"The sum is "g(0)"."l$, (n >= 1 | n*(n+1)/2 | 0)))
▶ No.813301>>813302 >>813303 >>813596 >>818047
Stephen Wolfram grant me luck and shekels.
▶ No.813302>>813304
>>813301
>"Stephen Wolfram initially struggled in school and had difficulties learning arithmetic"
>his mother worked at Oxford
>???
>Wolfram suddenly start publishing papers on quantum physics at 15 and get his PhD by 20
Wish I was a kike.
▶ No.813303
>>813301
((([Oy, nice and easy. Thanks Yahweh)))
▶ No.813304>>813305 >>813307 >>813608
>>813302
He's a legit genius.
▶ No.813305
>>813304
I'll count that as a roll too. How can other standard libraries even compete?
▶ No.813314>>813315 >>813320
>>813271
/*find how to pay a given amount of money in the least amount of euro coins/notes*/
#include <stdio.h>
#include <stdlib.h>
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<15; i++)
{
int type_count=0;
while( moneyleft/fakemoney_types[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);
}
}
▶ No.813315
>>813314
except it's missing $0.01. off by 1 in loop whatever it's done
▶ No.813316
>>813297
Warning: GPL!!!! Donut steal!
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int 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<an; i++){
for(int j=0; j<bn; j++){
ind = &suff[(i+1) * bn + (j+1)];
if(a[i] != b[j]){
*ind = 0;
}else{
*ind = suff[i * bn + j] + 1;
int l = *ind;
if(l > res){
res = l;
c = &a[i+1-res];
}
}
}
}
free(suff);
c[res] = '\0';
printf("%i %s\n",res,c);
}
int main(int argc, char **argv){
if(argc <= 2) return -1;
LCS(argv[1], argv[2], strlen(argv[1]), strlen(argv[2]));
return 0;
}
Warning: GPL!!!! Donut steal!
▶ No.813320>>813411
>>813314
this one's too easy
#include <stdio.h>
#include <stdlib.h>
/*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;
}
▶ No.813380>>813381
▶ No.813381
>>813380
>Reverse a string
You're shitting me.
(reverse (second *posix-argv*))
▶ No.813383>>813384 >>813387
Another easy roll please (Has to be quick, I have Halloween things to go to)
▶ No.813384>>813564
>>813383
Done. Nice and easy.
▶ No.813387>>813564
>>813383
>I have Halloween things to go to
>anon puts on his fursuit and pretends to be a child
▶ No.813396>>813398
▶ No.813398
>>813396
>demoeffects
Huh, I didn't know there was a name for this sort of thing.
▶ No.813411
>>813320
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 <height in inches> <weight in pounds>\n", [s(P)], !IO),
io.set_exit_status(1, !IO)
).
Compiling:
$ mmc -i bmi
$ mmc -o bmicalc main bmi
$ ./bmicalc 72 170
23.104353
$ ./bmicalc 72 200
Fatso detected.
$ ./bmicalc
usage: bmicalc <height in inches> <weight in pounds>
$ ./bmicalc blah foo
usage: bmicalc <height in inches> <weight in pounds>
▶ No.813414>>813415
>>812872 (OP)
I'll do this eventually, roll.
▶ No.813415
>>813414
>bmi calculator
shit's easy, reroll
▶ No.813430>>813441 >>813447
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<iostream>
#include<vector>
using namespace std;
int main()
{
int sieveSize;
int p = 2;
//p is the first prime and supposed to represent every consecutive prime
cout << "Enter number-to sieve." << endl;
cin >> sieveSize;
//prompts user for highest number they want the algorithm to evaluate
vector<int > 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 << p << ' ';
vectorSieve.erase(vectorSieve.begin());
//outputs and deletes last p from vector
while (vectorSieve.front() == 0)
{
vectorSieve.erase(vectorSieve.begin());
}
//erases non-primes at start of vector to find next p (prime)
p = vectorSieve.front();
//sets the next prime to p
}
cin >> sieveSize;
//(so the application doesn't immediately close)
return 0;
}
▶ No.813441>>813524 >>813678 >>813849
>>813430
you've suffered enough anon. Join me in the use of a more serious language:
create numbers 100 allot
0 constant Uncategorized
1 constant Prime
2 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 <=
while
Skipped over decide
repeat 2drop ;
: sieve ( -- )
numbers 100 Uncategorized fill
100 2 do
i numbers + c@ 0= if
Prime i decide
i skip-factors
then
loop .numbers ;
: .primes ( -- )
numbers 100 bounds do
i c@ Prime = if
i numbers - .
then
loop ;
To run it, load it into a Forth and type SIEVE and hit enter. Then .PRIMES and hit enter. Case insensitive. With gforth:
$ gforth -e 'include sieve.fs sieve .primes cr bye'
2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
$
With the primes in green and skipped numbers in red. This is animated as the sieve runs and categorizes numbers.
▶ No.813447>>813678
>>813430
>here's my stupid solution
>it currently isn't working because of some dumb exception and I don't feel like fixing it
Pick only one.
You were presented with a problem. Instead of creating a solution, you just created another problem.
▶ No.813524>>813525 >>813527 >>813632
>>813441
does your meme lang into multi-threading? that's what the problem specifies
▶ No.813525>>813527
>>813524
though i'm working on it too in C and I don't know how the fuck I would multithread it in any language.
▶ No.813527>>813529
>>813524
sure.
>>813525
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.
▶ No.813529>>813531 >>813552
>>813527
is there any way to multi-thread the actual seive? it seems like it's all deterministic.
▶ No.813531>>813532 >>813533
>>813529
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.
▶ No.813532>>813533
>>813531
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.
▶ No.813533>>813535
>>813532
>>813531
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.
▶ No.813534
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.
▶ No.813535
>>813533
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.
▶ No.813552
>>813529
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.
▶ No.813561>>813562 >>813678 >>814016
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 <stdio.h>
#include <stdlib.h>
/* Copyright 2017 >>813314 All Rights Reserved
Unlicensed use prohibited, licenses available for $79.99 on steam
early access */
/* alloc and fill number array with 2->limit */
void fill_num_array(int array_size, int *num_array)
{
for (int i=0; i<=array_size; i++)
{
num_array[i]=i+2;
}
}
/* print the number array */
void print_num_array(int array_size,int *num_array)
{
printf("number_array\n");
for (int i=0; i<=array_size; i++)
{
printf("%-3d ",num_array[i]);
if (i % 10 == 0)
{
if (i!=0)
{
printf("\n");
}
}
}
printf("\n");
}
/* seive a single number */
void seive_index(int number_i, int array_size,int *num_array)
{
for (int i=number_i+num_array[number_i]; i<=array_size; i+=num_array[number_i])
{
num_array[i]=0;
}
}
/* print primes, non-primes will be zero */
void print_primes(int array_size,int*num_array)
{
printf("primes:");
for (int i=0; i<=array_size; i++)
{
if ( num_array[i]!=0 )
{
printf("%d ",num_array[i]);
}
}
printf("\n");
}
int main(int argc, char *argv[])
{
int prime_limit=atoi(argv[1]);
printf("prime_limit:%d\n",prime_limit);
int array_size=prime_limit-2;
int *num_array=malloc(sizeof(int)*array_size+1);
fill_num_array(array_size,num_array);
/*print_num_array(array_size,num_array);*/
seive_index(0,array_size,num_array);
for (int i=0; i<=array_size; i++)
{
if (num_array[i]!=0)
{
seive_index(i,array_size,num_array);
}
}
/*print_num_array(array_size,num_array);*/
print_primes(array_size,num_array);
}
▶ No.813562
>>813561
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.
▶ No.813564
>>813387
>>anon puts on his fursuit and pretends to be a child
Close, I was Hugh Hefner.
>>813384
Counting that as a roll. It turns the text into a 2D array and then uses built in padding functions.
▶ No.813578>>813594
▶ No.813593
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 1
You have 50000 shekels. You have 3 jokers left.
You organise a VAT carbone tax scam. You win 100.000 shekels
Today, 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 2
You 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 3
You 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 4
You 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 5
You 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 6
You 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 7
You 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 8
You 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):
https://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.
▶ No.813594
>>813578
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 ret
prec = { '+': 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 out
def 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()
▶ No.813596>>813604
>>813301
Alright Stephen, give me a lucky roll again.
▶ No.813604>>813614
>>813596
These are getting boring, I'll have to roll for hard next time.
▶ No.813608
>>813304
A legit comic genius. One of the funniest writers I've read.
▶ No.813614>>813629
>>813604
>doing easy challenges with a language that comes with massive standard library
I don't think easy challenges are meant for this. Anyways rolling normal challenges.
▶ No.813615>>813634
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.
▶ No.813629>>813634 >>813672
>>813614
A ridiculous massive standard library! Here's your problem.
▶ No.813632
>>813524
>FORTH
>meme-lang
Learn some history, kid
▶ No.813634
>>813629
*ridiculously
>>813615
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.
▶ No.813668
▶ No.813672>>813703 >>813724
>>813629
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.
▶ No.813678>>813686 >>813708
>>813441
>>813447
>>813561
I'm fucking retarded
#include<iostream>
#include<vector>
using 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 << "Enter number-to sieve." << endl;
cin >> sieveSize;
//prompts user for highest number they want the algorithm to evaluate
vector<int > 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 << p << ' ';
vectorSieve.erase(vectorSieve.begin());
//outputs and deletes last p from vector
while (vectorSieve.front() == 0)
vectorSieve.erase(vectorSieve.begin());
//erases non-primes at start of vector to find next p (prime)
p = vectorSieve.front();
//sets the next prime to p
}
cout << "\nEnter any positive integer to end the program.\n Entering a negative integer will restart the program.\n";
cin >> sieveSize;
}
//(so the application doesn't immediately close)
return 0;
}
I reread this and immediately saw two fucking huge mistakes the program was checking the vector's POSITION for primes, and I forgot to change the for loop to account for the deleted vector cells
▶ No.813686
>>813678
it's funny i made those exact same mistakes on the c solution
▶ No.813703
>>813672
>I'm to dumb do figure it out
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.
▶ No.813708
>>813678
I added proper spacing and fixed a few minor details
#include<iostream>
#include<vector>
#include<string>
using namespace std;
// Copyright 2017, Anonymous, under the terms of the GPL (General Public License) https://www.gnu.org/licenses/gpl.html
string 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 << "Enter number-to sieve." << endl;
cin >> sieveSize;
//prompts user for highest number they want the algorithm to evaluate
vector<int > 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 << kerning(to_string(sieveSize), to_string(p)) << p;
vectorSieve.erase(vectorSieve.begin());
//outputs and deletes last p from vector
while (vectorSieve.front() == 0)
vectorSieve.erase(vectorSieve.begin());
//erases non-primes at start of vector to find next p (prime)
p = vectorSieve.front();
//sets the next prime to p
}
cout << "\nEnter any positive integer to end the program.\nEntering a negative integer will restart the program.\n";
cin >> sieveSize;
}
//(so the application doesn't immediately close)
return 0;
}
string kerning(string maxchar, string pchar)
{
string spacing = " ";
int psize = pchar.length();
for (psize; psize + 1< maxchar.length(); psize++)
spacing = spacing + (" ");
return string(spacing);
}
pure autism, although the spacing thing was a personal challenge
▶ No.813721
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)))))
▶ No.813724>>813744 >>813755
>>813672
>elegant solution
lmfao stop paying attention to the retard "programming" in mathematica.
▶ No.813744>>813762
>>813724
> Being this butthurt.
▶ No.813755>>813762 >>813790
>>813724
> It's only programming if it's low level!
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.
▶ No.813762
>>813744
whatever helps you sleep at night
>>813755
>algorithms are low level
lol
▶ No.813790>>813797
>>813755
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.813797>>813813 >>813830
>>813790
No. The point is to show that Mathematica is programming master race, and to trigger idiots like you into getting upset about it.
▶ No.813813>>813840
>>813797
>I-I was only pretending to be retarded
▶ No.813830>>813840 >>814963
>>813797
>HAHH U TRIGGERED? MATHEMEATICAL MUSTARD RACE! U MAD?
pathetic
▶ No.813840>>813843 >>813870
>>813830
>>813813
> Biting bate this hard
Did something happen at 4/g/? We seem to have a lot of newfags all of a sudden.
▶ No.813843
>>813840
Didn't you realize that we're in the 8chan subreddit?
▶ No.813849>>814016
>>813441
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/null
real 0m2.838s
user 0m2.740s
sys 0m0.096s
▶ No.813870>>813880
>>813840
>stupid people don't exist on image boards because we're too smart
>all idiots are just ebin trolls
no
▶ No.813880
>>813870
>not taking bait
if you add a name and a tripcode to your posts we'll all know who the big-brain adult is around here :)
▶ No.814016>>814028
>>813849
>Forth takes 72% as long to run the sieve and then to print out all the primes
I read this wrong but it reminded me.
>>813561
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.
▶ No.814028>>814052
>>814016
It's probably the speed of the terminal. redirect to a file instead and see if it's faster.
▶ No.814052
>>814028
time ./a.out 100000000 > results
real 0m6.453s
user 0m6.276s
sys 0m0.176s
time ./a.out 100000000
real 0m12.137s
user 0m6.448s
sys 0m0.380s
time ./a.out 10000000 > results
real 0m0.485s
user 0m0.472s
sys 0m0.012s
time ./a.out 10000000
real 0m0.991s
user 0m0.432s
sys 0m0.048s
it looks like it takes almost exactly as long to print the results to terminal as it does to run the seive.
▶ No.814329
▶ No.814436
▶ No.814484>>814487
▶ No.814487>>815899
>>814484
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.
▶ No.814571>>814963
▶ No.814947>>814990
▶ No.814963>>814971
>>814571
Here's the Mathematica version for this one. I do it for the fans, I will never let you down. >>813830 >>813724
▶ No.814990
>>814947
matrix = [[1,2],[3,4]]
matrix.transpose
▶ No.815031>>815034 >>815041
If its something 2hard4me I'm not going to do it.
▶ No.815034
▶ No.815041>>815066 >>815093
>>815031
>find mode in array
nigger... is u srs?
▶ No.815066>>815078
>>815041
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.
▶ No.815078>>815086 >>815113
>>815066
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.
▶ No.815086
>>815078
Yeah, it's a big hint, but can be done in O(nlogn) time.
▶ No.815093
>>815041
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.
>>815041
I've already done a Snake game a few months ago.
▶ No.815113>>815297
>>815078
example of a 'minimal hash table' for this problem:
#include <stdio.h>
#include <stdlib.h>
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 <n1> [<n2> ... <nn>]\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')
22
real 0m0.039s
user 0m0.026s
sys 0m0.016s
timing 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')
22
real 0m2.781s
user 0m2.767s
sys 0m0.016s
▶ No.815118>>815122
>>812872 (OP)
>dices
>dices
>dices
>dices
>dices
>dices
>dices
>dices
>dices
>dices
▶ No.815122>>815144 >>815146
>>815118
ANIME GET THE FUCK OUT OF MY BOARD
roll
▶ No.815144>>815146 >>815208
>>815122
>my board
uhmm no, sweetie
▶ No.815183
>>815146
perl
my @d = <DATA>;
print for (sort @d);
__DATA__
a300
a1
fgs
a2
fds
a10
dfs
a20
srt
▶ No.815208>>815243
>>815144
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*
▶ No.815243>>815291
>>815208
/tech/ is a Christian board. No false memeing and false witnessing allowed, unless you are not afraid of capital punishment by Our Lord.
▶ No.815291
>>815243
>our lord
>daring pronuncing its name ironically
>posting anime picture
>thinking he'll not end in fucking hell for posting nearly pornographic asian little girl drawing all other the web
▶ No.815297>>815324
>>815113
How well does http://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.
▶ No.815324>>815326 >>815329 >>815368
>>815297
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; done
sortmode
got 1 modes:
value = 24, count = 6304
real 0m0.601s
user 0m0.562s
sys 0m0.040s
getmode
24
real 0m0.078s
user 0m0.046s
sys 0m0.033s
$ for x in sortmode getmode; do echo $x; time ./${x} $(cat 6mil); done
sortmode
got 1 modes:
value = 49, count = 133
real 0m0.098s
user 0m0.059s
sys 0m0.039s
getmode
49
real 0m0.079s
user 0m0.058s
sys 0m0.022s
▶ No.815326>>815426
>>815324
(the '6mil' file there, without the .dat, only has 100k numbers in it.)
▶ No.815329
>>815324
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 = 9
real 0m1.007s
user 0m0.967s
sys 0m0.039s
getmode
254328
real 0m0.209s
user 0m0.169s
sys 0m0.040s
OTOH 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.
▶ No.815368
>>815324
Yeah that makes sense, as the sorting should be O(nlogn) vs O(n) for the hash table with (amortized O(1)).
▶ No.815371>>815378 >>815427
Wew, I'm terrible at programming. I'm already stuck at the second problem in project euler
▶ No.815378>>815393
>>815371
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?
▶ No.815393
>>815378
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 sumEven
print(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
▶ No.815426
▶ No.815427>>815428 >>815435
>>815371
project euler is really shitty for programming challenges, its just all math
▶ No.815428>>815432 >>815437
>>815427
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.
▶ No.815432
>>815428
>math
>joy
u wot m8
▶ No.815435
>>815427
>just all math
math isn't really going to help anons sort their hentai collection
▶ No.815437>>815439 >>815451 >>815524
>>815428
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
▶ No.815439
>>815437
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.815451
>>815437
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.
▶ No.815455>>815458
REMINDER
if your program doesn't pass valgrind with 0 memory leaks you have to rewrite it until it does
▶ No.815458>>815460 >>815461 >>815462
>>815455
speaking of valgrind, i'm still trying to get the hang of C
this code is valgrinds demonstration of a memory leak
#include <stdlib.h>
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.815460>>815466
>>815458
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.
▶ No.815461
>>815458
lol is this ironic
▶ No.815462>>815466
>>815458
Not in C.
Variables in the stack are released when their scope ends.
Variables in the heap must be explicitly freed.
▶ No.815466>>815469 >>815475
>>815460
>>815462
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 <stdlib.h>
#include <stdio.h>
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.
▶ No.815469>>815470
>>815466
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.
▶ No.815470>>815472
>>815469
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);
▶ No.815472>>815475
>>815470
Because %c expects a char and %s expects a char *. Try compiling with -Wall and -pedantic and see what warnings pop up.
▶ No.815475>>815477 >>815485
>>815472
gcc -Wall -pedantic still throws no errors or warnings with
>>815466
with the string "array" being a pointer to a single character
▶ No.815477>>815479 >>815481
>>815475
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.815479>>815481
>>815477
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.
▶ No.815481
>>815477
>>815479
unless gcc knows and it's fucking with the output to prevent reading memory it shouldn't be.
▶ No.815485>>815490
>>815475
it's called luck with your padding
▶ No.815490>>815493 >>815499
>>815485
you can definitely read into b's heap from a.
#include <stdlib.h>
#include <stdio.h>
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<100;i++)
{
printf("%c",a[i]);
}
printf("\n");
return 0;
}
printf doesn't though.
maybe it's this "A"? character. is that just random luck or is that some kind of separator. ?
▶ No.815493>>815499
>>815490
luck. malloc does nothing. use calloc instead.
▶ No.815499>>815504
>>815493
>>815490
literally zero difference in the output. the A is still there.
#include <stdlib.h>
#include <stdio.h>
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<100;i++)
{
printf("%c",a[i]);
}
printf("\n");
return 0;
}
▶ No.815504>>815505 >>815506 >>815762 >>815842 >>815847 >>815911
>>815499
this gets even more trippy
#include <stdlib.h>
#include <stdio.h>
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<100;i++)
{
printf("%c",a[i]);
}
printf("\n");
printf("b:%s\n",b);
return 0;
}
a is allocated 1 char, but i assign it 5 deep without any issues. calloc is overrated.
b is allocated 50 with calloc, immediately after I calloc a, but assignments to it (0-2) do not overwrite the shit i wrote un allocated to a.
trying to overrun a with print prints out both a and b, and the "A" separator is still fucking there, and printf still has no problems printing nothing but "abcdce" without a null terminator, and stopping there, even though all the answers I found to this say this is undefined behavior and/or there must be a null terminator in memory immediately after a, but there isn't, because b is immediately after a, and the first character isn't a null terminator.
▶ No.815505
>>815504
putting the callac for *b immediatly after a[0], a[1], etc, and before b[0]='d', doesn't change the output.
▶ No.815506>>815527
>>815504
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
▶ No.815524>>815637
>>815437
>verdict: its shit
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?
▶ No.815527
>>815506
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.
▶ No.815637>>815643 >>815848
>>815524
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.
▶ No.815643>>815646 >>815688 >>815697 >>815722 >>815775
>>815637
>Day to day programming doesn't have a lot to do with math.
▶ No.815646
▶ No.815688
>>815643
doesn't a have a lot to do with math beyond basic algebra.
▶ No.815697
▶ No.815722>>815762
>>815643
When you use C, most of your math is manually keeping track of lengths.
▶ No.815762
>>815722
keeping track of lengths is unnecessary
>>815504
▶ No.815775>>815845
>>815643
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.
▶ No.815842>>815901
>>815504
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?]
▶ No.815845
>>815775
>doesn't usually go past basic trig these days
Are game engines so advanced these days that blue hairs don't even need to know elementary linear algebra?
▶ No.815847>>815901 >>815911
>>815504
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.
▶ No.815848
>>815637
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.
▶ No.815849
▶ No.815850>>815901 >>815911 >>815919
>>813271
But I want to see the header file too
▶ No.815870>>815925
Rolling for short Mathematica.
▶ No.815899
>>814487
It's been Sunday for a while now. Post code, faggot.
▶ No.815901>>815908 >>815929
>>815842
>>815847
>>815850
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.
▶ No.815908
>>815901
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.
▶ No.815911
>>815504
>>815847
>>815850
changing from
for (int i=0;i<100;i++)
to look to overrun a, to
for (int i=-1;i<100;i++)
or anything less than zero segfaults.
▶ No.815918>>815948
▶ No.815919
>>815850
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 <stdlib.h>
#include <stdio.h>
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<200;i++)
{
printf("%c",a[0]-i);
}
printf("\n");
printf("b_underrun:");
for (int i=0;i<200;i++)
{
printf("%c",b[0]-i);
}
printf("\n");
return 0;
}
▶ No.815925
>>815870
I assume by "primordial" they meant "primorial".
▶ No.815929
>>815901
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.
https://en.wikipedia.org/wiki/SLOB
https://en.wikipedia.org/wiki/Slab_allocation
▶ No.815948>>815952 >>817184
>>815918
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.
▶ No.815952>>815958 >>817184
>>815948
>what makes them dynamic?
Automatically resizing.
▶ No.815953
>>815941
niggerlicious
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#ifndef BIG_ENDIAN
#define ascii_to_int16(s1, s2) s1 * 256 + s2
#else
#define ascii_to_int16(s1, s2) s2 * 256 + s1
#endif
int16_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] <= dec)
{
int roman_offset = i+13;
*(int16_t*)(romans + counter) = roman_table[roman_offset];
counter++;
if (! (roman_offset % 2))
{
counter++;
}
dec -= roman_table[i];
break;
}
}
}
puts(romans);
return 0;
}
$ gcc -O2 roman.c -o roman.run
$ roman.run 2017
MMXVII
▶ No.815958>>815962
>>815952
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.
▶ No.815962>>815970
>>815958
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.
▶ No.815964>>815978
▶ No.815970>>815977 >>815992
>>815962
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.
▶ No.815973
▶ No.815977>>815980
>>815970
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 <100 petabytes of garbage>".
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.
▶ No.815978
>>815964
im not doing that. re-rolling
▶ No.815980>>815984
>>815977
>Programming as if resources were infinite is appropriate for single-user desktop systems
lmao no it's not
>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;
This is only true for very specific types of programs and users.
▶ No.815984
>>815980
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.
▶ No.815992>>815995
>>815970
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.
▶ No.815995>>815998 >>815999
>>815992
is that an actual recommendation or are you just sharing that meme?
▶ No.815998
>>815995
Reading Knuth is next to Godliness, anon.
▶ No.815999>>816001 >>816006
>>815995
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:
https://news.ycombinator.com/item?id=10897460
https://www.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.
▶ No.816001>>816007 >>816515
>>815999
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.
▶ No.816003>>816004 >>816008
>If you think you're a really good programmer, read The Art of Computer Programming. You should definitely send me a résumé if you can read the whole thing." -Bill Gates
Has anyone ever taken him up on his autistic challenge?
▶ No.816004
>>816003
I can read the whole thing. I haven't started yet, but I can.
▶ No.816006
>>815999
This faggot deserves to be hung drawn and quartered. He epitomizes every fucking know it all dipshit I've encountered in the software industry.
▶ No.816007>>816009
>>816001
> I want to know how computers and programs really work from the bottom up
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.
▶ No.816008
>>816003
There's this Steve Jobs one too.
> Steve had managed to get Don Knuth, the legendary Stanford professor of computer science, to give a lunchtime lecture to the Mac team. Knuth is the author of at least a dozen books, including the massive and somewhat impenetrable trilogy "The Art of Computer Programming." (For an amusing look at Knuth's heady self image, and his $2.56 reward program, see http//www-cs-faculty.stanford.edu/~knuth/books.html)
> I was sitting in Steve's office when Lynn Takahashi, Steve's assistant, announced Knuth's arrival. Steve bounced out of his chair, bounded over to the door and extended a welcoming hand.
> "It's a pleasure to meet you, Professor Knuth," Steve said. "I've read all of your books."
< "You're full of shit," Knuth responded.
▶ No.816009
>>816007
No book is a book I can speed read. I tend to read so thoroughly finishing books at all becomes a real problem.
▶ No.816284>>816287
Rolling for easy and normal.
▶ No.816287>>816536
>>816284
>easiest shit on both
gno. Reroll.
▶ No.816515
▶ No.816518>>816519
>>816516
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.
▶ No.816519>>816521
>>816518
> the power inevitably goes out for no reason
Pajeet?
▶ No.816521
▶ No.816536
>>816287
For the easy challenges, https://gitgud.io/m712/palin/
Chip-8 emulator sounds cool, I'll try to do it.
▶ No.816906
▶ No.817005
▶ No.817008
binary search.... that's too easy
▶ No.817184>>817187
>>815948
Not trying to nitpick >>815952 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.
▶ No.817187
>>817184
>Not trying to nitpick
That's good, because you are wrong. You're confusing dynamic arrays with dynamically allocated arrays.
▶ No.817222>>817223
Rollan.
>inb4 complex shit
▶ No.817223>>817226
>>817222
>fucking animated sprite editor
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.
>pic 1
def fact(num, mult = 1):
if(num <= 1):
return mult
mult *= num
num -= 1
return fact(num, mult)
▶ No.817226>>817232
>>817223
>so someone will bully me
I was going to poke fun at your TCO envy.
▶ No.817232>>817351
>>817226
>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.
▶ No.817251
▶ No.817351
>>817232
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.
▶ No.817353
▶ No.817525
▶ No.817817
▶ No.817941>>817945
// Challenge 03
// Secure password generator
// Note: Unicode 0x00 to 0x20 is blank, and 0x7F is del,
// so we ignore those.
package main
import (
"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))
}
▶ No.817945>>817946
>>817941
>secure
>log2(95^8) = 52.6
you fucked up
▶ No.817946>>817948
▶ No.817948>>817952
>>817946
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.
▶ No.817952
>>817948
Oh, googled it. Just generate twice and concatenate them.
▶ No.818047>>818048
>>813301
Roling for another easy one liner.
▶ No.818048>>818051
>>818047
Reroll (already did)
▶ No.818051
>>818048
I am so fucking smart!
▶ No.820397>>821506 >>822000
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
▶ No.820740>>820887
▶ No.820887>>820893 >>820912 >>821828
>>820740
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 <stdio.h>
#include <string.h>
#include <stdlib.h>
// 1-19
char *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 (number<1 || number>99) {
appendtobuffer(&strbuf, "error");
// trim the buffer
realloc(strbuf.buffer, strbuf.contentsize+1);
return strbuf.buffer;
}
if (number<20) {
appendtobuffer(&strbuf, singles[number-1]);
realloc(strbuf.buffer, strbuf.contentsize+1);
return strbuf.buffer;
}
int count=0;
while (number>0) {
if (number<10) {
appendtobuffer(&strbuf,singles[number-1]);
number=0;
}
else if (number<100) {
count=number/10;
appendtobuffer(&strbuf,doubles[count-2]);
number=number-(count*10);
if (number!=0) {
appendtobuffer(&strbuf,"-");
}
}
}
// trim the buffer
realloc(strbuf.buffer, strbuf.contentsize+1);
return strbuf.buffer;
}
int main(int argc, char *argv[]) {
for (int i=99; i>=2; i-=1 ) {
printf("%s bottles of beer on the wall, %s bottles of beer.\n", numtostr(i),numtostr(i));
printf("take one down and pass it around, %s",numtostr(i-1));
if ((i-1)==1) {
printf(" bottle ");
}
else {
printf(" bottles ");
}
printf(" of beer on the wall.\n\n");
}
printf("one bottle of beer on the wall, one bottle of beer.\n");
printf("take one down and pass it around, no more bottles of beer on the wall.\n\n");
printf("no more bottles of beer on the wall, no more bottles of beer.\n");
printf("go to the store and buy some more, 99 bottles of beer on the wall.\n");
}
▶ No.820893
>>820887
fuck looking at this now it memory leaks the buffer.
▶ No.821353>>821403
>>820912
it was the end of the day lol
▶ No.821506>>822000
>>820397
Well, you learned a valuable lesson on something of little worth. Think about what could have made that process safer.
▶ No.821588
>>821403
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.
▶ No.821828>>822674
>>820887
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 <stdio.h>
#include <string.h>
#include <stdlib.h>
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_index<=str_length) {
test_length=2;
while(str_start_index+test_length<=str_length) {
//printf("start_index:%d test_length:%d\n",str_start_index,test_length);
strncpy(test_string,str+str_start_index,test_length);
//ensure last char is terminated
test_string[test_length+1]=0;
reverse_string(reverse_test_string,test_string,test_length);
//printf("testing:%s=%s\n",test_string,reverse_test_string);
// use memcmp instead of strcmp, junk data still in
// test/reverse string, or free/calloc everytime
if (memcmp(test_string,reverse_test_string,test_length)==0) {
if (test_length>p_length) {
p_length=test_length;
strcpy(palindrome, test_string);
}
}
test_length+=1;
}
str_start_index+=1;
}
free(test_string);
free(reverse_test_string);
return p_length;
}
int main(int argc, char *argv[]) {
char *str=argv[1];
char *palindrome=calloc(strlen(argv[1]+1),1);
if (find_palindrome(str,palindrome)>0) {
printf("largest palindrome:%s\n",palindrome);
}
else {
printf("no palindrome found\n");
}
}
▶ No.821978>>821987
▶ No.821987
>>821978
print eval $ARGV[0]
▶ No.822000>>822043
>>820397
This: >>821506
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.
▶ No.822043
>>822000 (checked)
Stallman BTFO!
▶ No.822105
▶ No.822455>>822476
▶ No.822476>>822515
>>822455
Simple account management in Mathematica.
▶ No.822515>>822532 >>822622
>>822476
What is even the point
▶ No.822532
>>822515
To complete the task.
▶ No.822622
>>822515
Of you trying to compete with me? Very little. Accept Wolfram as your Lord and Saviour.
▶ No.822637
▶ No.822674>>822676 >>822686
>>821828
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 <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ncurses.h>
/* 7-segment led, 5x7
000
1 2
1 2
333
4 5
4 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();
}
▶ No.822676>>822680
>>822674
i don't even know wtf that means, reroll
▶ No.822680>>822764
>>822676
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.
▶ No.822686>>822687 >>822764 >>824217
>>822674
not bad anon, but it could use a little polish.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ncurses.h>
/* 7-segment led, 5x7
000
1 2
1 2
333
4 5
4 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();
}
▶ No.822687
>>822686
ugh, you used hard tabs. and I used an editor that hid that from me. hence the odd indentation.
▶ No.822764>>822768
>>822680
thanks i'm sure i could figure it out, but i'm trying to learn the libraries and the language, not math atm.
>>822686
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.
▶ No.822768>>822775 >>824217
>>822764
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 initscr
fucking endwin
fucking cbreak
fucking refresh
proc 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 times
proc 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 1000
while 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
▶ No.822775
>>822768
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) ]
▶ No.822882>>822891 >>825421
▶ No.822891>>823147 >>825421
>>822882
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.
▶ No.823147>>823200 >>823214 >>825421
>>822891
you do realise that can be O(1) right?
▶ No.823198>>823200
>>812872 (OP)
Is this by order of difficulty?
Are we allowed to skip some?
▶ No.823200
>>823198
I don't think so. No, you cannot skip, the roll is the future you chose.
>>823147
This.
▶ No.823214>>823223
>>823147
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.
▶ No.823223>>823232 >>823323 >>825421
>>823214
Stop making a fool of yourself, there are no large constants in this case.
Arithmetic series: n*(n+1)/2.
▶ No.823232
>>823223
I was just speaking generally, not about that case.
▶ No.823323>>823357
>>823223
>current year
>using math
>not solving problems at compile time
proc sumUpTo(n: int): int =
for x in 0 .. n:
result += x
100_000_000.sum_up_to.echo
takes 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)
sum
100_000_000.sum_up_to_fast.echo
takes about a millisecond to run.
had to recompile nim itself though. can only have compiler/vmdef.nim:MaxLoopIterations iterations in compile-time loops
▶ No.823352>>823364
▶ No.823357>>823362
>>823323
>>current year
>>using math
TRIGGERD
>>not solving problems at compile time
That won't work because the n comes in at run time.
▶ No.823362
>>823357
... 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.
▶ No.823364>>823389
>>823352
#include <iostream>
int prime_after(int n)
{
if (n < 2)
return 2;
keep_it_up:
for (int i = 2, n2 = ++n / 2; i <= n2; ++i)
if (n % i == 0)
goto keep_it_up;
return n;
}
int main()
{
std::cout << prime_after(275936);
}
▶ No.823367
▶ No.823389>>823398 >>823431
>>823364
#include <iostream>
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 << reverse_num(4'123'456'789);
}
▶ No.823398
>>823389
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.reverseNum
echo 4_123_456_789'u32.reverseNum
▶ No.823424>>823426
▶ No.823431>>823817
>>823389
#include <iostream>
#include <string_view>
#include <cctype>
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 << shortest_word(R"(What the fuck did you just fucking say about me, you little bitch? I'll have you know I graduated top of my class in the Navy Seals, and I've been involved in numerous secret raids on Al-Quaeda, and I have over 300 confirmed kills. I am trained in gorilla warfare and I'm the top sniper in the entire US armed forces. You are nothing to me but just another target. I will wipe you the fuck out with precision the likes of which has never been seen before on this Earth, mark my fucking words. You think you can get away with saying that shit to me over the Internet? Think again, fucker. As we speak I am contacting my secret network of spies across the USA and your IP is being traced right now so you better prepare for the storm, maggot. The storm that wipes out the pathetic little thing you call your life. You're fucking dead, kid. I can be anywhere, anytime, and I can kill you in over seven hundred ways, and that's just with my bare hands. Not only am I extensively trained in unarmed combat, but I have access to the entire arsenal of the United States Marine Corps and I will use it to its full extent to wipe your miserable ass off the face of the continent, you little shit. If only you could have known what unholy retribution your little "clever" comment was about to bring down upon you, maybe you would have held your fucking tongue. But you couldn't, you didn't, and now you're paying the price, you goddamn idiot. I will shit fury all over you and you will drown in it. You're fucking dead, kiddo.)");
}
Truly, my greatest masterpiece.
▶ No.823817>>824122
>>823431
#include <iostream>
#include <unordered_map>
#include <algorithm>
template<typename T>
T mode_of(const T* arr, size_t sz)
{
std::unordered_map<T, size_t> 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<typename T, size_t sz> 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 << mode_of(arr);
}
▶ No.823935>>823941
Have to leave in four minutes. Quickest roll ever please.
▶ No.824026>>824029 >>824043
We don't have a cyclical blogposting thread so I'll just post this here, tangentially related. polite sage
>tfw you refactor your code and create new memory leaks
>tfw you will never git gud and prove your superiority to pajeet cs grad
I'm not in CS nor am I a programmer, but it still feels bad man.
▶ No.824029
>>824026
creating problems and fixing them is how learning occurs.
▶ No.824043>>824085
>>824026
stop using Cjeet and Cjeet++ and use rust intead
▶ No.824085>>824097
>>824043
>even the pajeets want nothing to do with the failure that is rust
▶ No.824097>>824121
>>824085
pajeets are too dumb for rust. What's your excuse, brainlet?
▶ No.824121>>824123
▶ No.824122>>824134
▶ No.824123>>824126 >>824127
>>824121
>two lines at the bottom of the page is prominent
Brainlet manchild goes to GitHub, Sees code of conduct, doesn't feel good and changes - AUTISM. Many such cases!
▶ No.824126
>>824123
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?
▶ No.824127>>824129
>>824123
this comment violates the rust code of conduct.
>brainlet manchild
-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.
▶ No.824130
>>824129
Good god. Can you imagine how disputes over pull requests go with those clowns.
>How dare you reject my request you fucking white male!!!!
Also roll.
▶ No.824134>>824140
>>824122
#include <iostream>
#include <algorithm>
void higher_lower_computer_guesses(int lower, int higher)
{
if (lower > higher)
std::swap(lower, higher);
std::cout << "Enter a number between " << lower << " and " << higher << " inclusive: ";
int n; std::cin >> n;
if (n < lower || n > higher)
return std::cout << "Get out.\n", void();
for (++higher;;){
int cur = lower + (higher - lower) / 2;
std::cout << "Is it " << cur << "?\n";
if (cur == n)
return std::cout << "Yep.\n", void();
else {
std::cout << "Nope, ";
if (cur < n){
std::cout << "higher!\n";
lower = cur + 1;
} else {
std::cout << "lower!\n";
higher = cur;
}
}
}
}
int main()
{
higher_lower_computer_guesses(0, 100);
}
Not sure if this is what is asked, but whatevs.
▶ No.824140>>824153 >>824159
>>824134
#include <iostream>
#include <string>
#include <unordered_set>
#include <algorithm>
void greet()
{
static const std::unordered_set<std::string> persona_non_grata = {
"Ajit Pai",
"Steve Klabnik",
"Bill Gates",
"Mark Zuckerberg",
"Larry Page",
"Sergey Brin",
"The AIDS-ridden corpse of Steve Jobs",
};
std::cout << "Hi, what's your name?\n";
std::string name; std::getline(std::cin, name);
if (std::all_of(name.begin(), name.end(), [](char c){ return std::isspace(c); }))
std::cout << "Cool name, loser.\n";
else if (persona_non_grata.count(name))
std::cout << "Fuck off.\n";
else
std::cout << "Greetings, " << name << ". How are you today?\n";
}
int main()
{
greet();
}
▶ No.824153>>824159 >>824178
>>824140
import sets, strutils
const persona_non_grata = [
"Ajit Pai",
"Steve Klabnik",
"Bill Gates",
"Mark Zuckerberg",
"Larry Page",
"Sergey Brin",
"The AIDS-ridden corpse of Steve Jobs",
].toSet
write 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.
▶ No.824159>>824160 >>824178
>>824140
#include <iostream>
#include <string>
#include <tuple>
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 << capitalized(cur) << " bottle" << s << " of beer on the wall, " << cur << " bottle" << s << " of beer.\n";
cur = to_text(--i);
if (i <= 1)
s = i ? "" : "s";
std::cout << "Take one down, pass it around, " << cur << " bottle" << s << " of beer on the wall...\n";
}
}
int main()
{
bottles_of_beer();
}
>>824153
I'll make an effort for my next one :^)
▶ No.824160>>824178
>>824159
>#include <tuple>
>not spending an hour implementing your own tuple in C
▶ No.824171
▶ No.824178>>824246 >>824599
>>824159
There you go, >>824153
#include <memory>
#include <iostream>
template<typename T>
class linked_list
{
class node
{
public:
node(std::unique_ptr<node> 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<node>(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<node> next_) : next_(std::move(next_)) {}
std::unique_ptr<node> next_;
};
int main()
{
linked_list<int> 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 << (*cur)->get() << ' ';
}
>>824160
Sounds like fun
▶ No.824180
▶ No.824200>>824201
▶ No.824201
>>824200
Another one, maybe something more challenging.
▶ No.824217>>824244
>>822686
needed experience with gtk, so i wrote this for gtk with
>>822768
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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <gtk/gtk.h>
/* 7-segment led, 5x7
000
1 2
1 2
333
4 5
4 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;i<7;i++) {
strcat(seg_str,row[i]);
}
return;
}
gboolean update_labels(void *data) {
GtkBuilder *builder=(GtkBuilder*)data;
GtkLabel *label;
time_t rawtime;
struct tm *local_tm;
time(&rawtime);
local_tm=localtime( &rawtime );
char seg_str[57];
label=GTK_LABEL(gtk_builder_get_object(builder,led_names[0]));
//gen_seg_str( (local_tm->tm_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();
}
▶ No.824244>>824419
>>824217
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/bash
gcc `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.
▶ No.824246
▶ No.824385
▶ No.824419>>824489 >>824765
>>824244
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
▶ No.824489>>824528
>>824419
Surely the linker could chase down all the requisite dependencies anyways?
▶ No.824515>>824823
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?
▶ No.824528>>824556
>>824489
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.
▶ No.824556
▶ No.824599
>>824178
Big ol' state + register machine with some recursion for good measure:
#include <string_view>
#include <cctype>
#include <utility>
#include <iostream>
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 << parse_arithmetic("34 * -2 + 8 / 3 * 5 - ((17 + 0) - (3 * 4 - 10)) / 4") << " == " << 34 * -2 + 8 / 3 * 5 - (17 - (3 * 4 - 10)) / 4;
}
▶ No.824615>>824637
Daily Mathematica quick roll.
▶ No.824765>>824800
>>824419
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 (https://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.
▶ No.824800>>824809
>>824765
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.
▶ No.824809>>824812
>>824800
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.
▶ No.824812
>>824809
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.
▶ No.824822
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.
▶ No.824823>>824843
▶ No.824843
>>824823
Need to learn it.
>mfw finally understood bezier curves and interpolation
▶ No.825421
>>822882
>>822891
#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 (<= fac 0) n (helper fac (random nb-el))))
)
(helper (random) (random nb-el))
)
(define (markov-string n first-i)
(define (helper n i)
(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
>>823147
>>823223
Oh yeah the Gauss trick... I'm too much of a mathlet to remember that kind of things tbh senpai
▶ No.825446>>825447 >>825483
>>825424
Nothing makes girls hornier than a closed-form solution anon. 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.
▶ No.825447
▶ No.825483>>825498
>>825446
>has bits of functional programming in it
>that means it's fp
wrong
▶ No.825498
>>825483
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.
▶ No.825514
>>825484
this version is far superior, rolling and i'm rounding down to the first medium.
▶ No.826286>>826287
▶ No.826287>>826290
>>826286
>design an esoteric language
I'm already doing that with Nlang. Reroll
▶ No.826290
>>826287
>C compiler
gno thank you I value my time
▶ No.826459>>827497
>>825484
Roll, see you soon when I have the time.
▶ No.826587
▶ No.826632
▶ No.827458
▶ No.827496
▶ No.827497
>>826459
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.