[ cyb / tech / λ / layer ] [ zzz / drg / lit / diy / art ] [ w / rpg / r ] [ q ] [ / ] [ popular / ???? / rules / radio / $$ / news ] [ volafile / uboa / sushi / LainTV / lewd ]

λ - programming

/lam/bda /lam/bda duck
Name
Email
Subject
Comment
File
Password (For file deletion.)

BUY LAINCHAN STICKERS HERE

STREAM » LainTV « STREAM

[Return][Go to bottom]

File: 1441525631604.png (525.62 KB, 600x600, a0b88990fb642934d816520503….png) ImgOps iqdb

 No.9154[Last 50 Posts]

The Programming Challenges thread is a thread where we'll try to post regular, simple challenges for everyone to give it a try and post their solutions.

>Which languages should I use?

Use whatever you want or feel the most comfortable with.

>For what purpose?

This thread is supposed to provide us the oppurtunity to improve our skills by both practicing and reading other peoples code.
In the spirit of everyone learning collectively, feel free to ask questions about anything in other peoples code you can't figure out yourself.

>But I don't know how to program.

No problem, get started with one of these excellent books:
Learn Python the hard Way: http://learnpythonthehardway.org/
Learn You a Haskell for Great Good: http://learnyouahaskell.com/
Structure and Interpretation of Computer Programs: https://github.com/sarabander/sicp-pdf

>You have an idea or want to help us come up with one?

That's great! Just post your idea in here or come hang out with us on #learnprog on freenode.
>>

 No.9155

This weeks challenge is finding prime numbers!
Write a function that calculates the n first prime numbers.

>>

 No.9157

File: 1441532197231.png (301.88 KB, 1920x1080, Program.png) ImgOps iqdb

>>9155
Alright. I'm game. Here's a few others for if you get bored.

>>

 No.9158

>>9155
Here's my solution in haskell:

-- | The function required by the challenge
genPrimes :: (Integral i) => Int -> [i]
genPrimes n = take n primes

-- | A lazy list of all prime numbers
primes :: (Integral i) => [i]
primes = 2:lazyPrimes [2] 3

lazyPrimes :: (Integral i) => [i] -> i -> [i]
lazyPrimes primes n
| n `divisibleBy` primes = lazyPrimes primes (n+1)
-- A number not divisible by any prime numbers is a prime number
| otherwise = n:lazyPrimes (primes++[n]) (n+1)

-- | Check wether n is divisible by a prime smaller or equal to n's square root
divisibleBy :: (Integral i) => i -> [i] -> Bool
divisibleBy n = foldr (\p b -> (p * p <= n) && n `mod` p == 0 || b) False


My main goal was to make the generation of the prime numbers lazy.
Any tips or improvements are welcome!

>>

 No.9163

Here's my try in python:

def primes(how_many):
primes = []
for i in range(1, how_many+1)
for x in range(1, int(sqrt(i)) ):
if i % x == 0:
continue
primes.append(i)
return primes

>>

 No.9165

>>9163
I don't realy get your program.
No matter how I arrange the indenting, it doesn't generate all the primes up to how_many.
Also, your seems like it would generate all primes uptill how_many instead of generating how_many.
No hard feelings, but maybe you should play around a little more with that snippet of code.

>>

 No.9166

Not really efficient, I might work on that later.

(defparameter *primes* '(2))

(defun isprime (n primes)
(cond
((null primes) t)
((> (car primes) (sqrt n)) t)
((zerop (mod n (car primes))) nil)
(t (isprime n (cdr primes)))))

(defun primes-up-to (n)
(do ((i 3 (+ i 2)))
((> i n) *primes*)
(when (isprime i *primes*)
(setf *primes* (append *primes* (list i))))))

>>

 No.9167

>>9154
Have you guys ever checked out project euler? Its a bunch of math puzzles that require programming to solve. For example: find the sum of all the even fibbonaci numbers up 4,000,000

>>

 No.9168

>>9165
Lol yeah, that code sucked.
Fix'd here: http://pastebin.com/sR2HZ0Ht

>>

 No.9170

woo, you only have to test new numbers against the primes you already got. Looking at your solution, it seems that you started with a range(1, i) loop, but that was too slow, so you added the square root stuff, is that right?

Also, you can use a for-else clause to eliminate those flags: http://book.pythontips.com/en/latest/for_-_else.html

Below is my solution, but you might want to try to solve it yourself first with the tips above.


def primes(n):
i = 2
primes = []
while i <= n:
for p in primes:
if i % p == 0:
break
else:
primes.append(i)
i += 1
return [1] + primes


Ideas to improve mine also welcome.

>>

 No.9171

>>9168
Looking pretty good, but shouldn't

if flag:
continue
i += 1
primes.append(i)

Rather be something along the lines of

if not flag:
primes.append(i)
i += 1

Because the way it is right now, the loop would hang upon encountering the first non-prime number, as it continues before updating i.
Also, I would rename flag to something more descriptive like is_not_prime or something.

>>

 No.9173

>>9170
Two little nitpicks with your solution:
1. 1 is not a prime, so no need to prepend it to the primes list before returning: https://primes.utm.edu/notes/faq/one.html
2. You could use

for i in range(2, n+1):

instead of your while loop. That would be more pythonic.

I realy like the way you use the primes list you're building up for the prime checking, though.
A clean and fast solution.

>>

 No.9174

>>9170
Yeah, actually, comparing against primes is much faster.
Oh, and that for-else thing is weird, but cool I guess.

>>9171
I think it was okay. If we rename flag to not_prime, it would be that if not_prime is true, it continues to the next number, while if it's not, it adds one to the ammount of primes so far, and appends it to our list.

Anyway, I made a new version:
http://pastebin.com/VzpsMHui

And just now I realized it looks almost exactly like acchan's, so I'm working on a different version.

>>

 No.9175

>>9173
1. My oversight. The definition I learned is "every number that's divisible by exactly 4 numbers". That excludes 1 and reminds that you can also divide by negative numbers. I wasn't even thinking of what's a prime when I tacked that [1] there.
2. Ah, much better. Thanks.

I think this is about as good as it gets:

def primes(n):
primes = []
for i in range(2, n+1):
for p in primes:
if i % p == 0:
break
else:
primes.append(i)
i += 1
return primes


For a generator object, I suppose there's no way to replace the while loop, is that right?

def genPrimes():
num = 2
primes = []
while True:
for p in primes:
if num % p == 0:
break
else:
primes.append(num)
yield num
num += 1

# a = genPrimes()
# a.next() # Python 2
# next(a) # Python 3

>>

 No.9178

opps bad formatting and extraneous code

include Math

def primes_list(range)
return 2 if range == 2
return "not a usable range" if range <= 1
collection = (0..range).to_a

collection[0] = collection[1] = nil

(2..sqrt(range)).each do |integer|
if collection[integer]
step = integer**2
while step <= range do
collection[step] = nil
step+=integer
end
end
end
return collection.compact
end

ruby https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

>>

 No.9180

>>9178
That is a realy cool algorithm!
Didn't know that one.

>>

 No.9185

me again
decided to implement it in python, gahhhh tabs to spaces junk here it is formatting finally fixed.

import math

def prime_list(rang):
if rang <= 1: return "not a usable range"
if rang == 2: return [2]
collection = range(0,rang+1)

collection[0] = collection[1] = None
for integer in range(2,int(math.sqrt(rang))+1):
if collection[integer] is not None:
step = integer**2
while step <= rang:
collection[step] = None
step+=integer
return [item for item in collection if item is not None]


>>9180
Ya its a cool one. Gotta implement it using wiki article or its cheating! Just Kidding.

>>

 No.9186

>>9178
>>9185
Cool. I made a version in python.

http://pastebin.com/uceKBHCG

>>

 No.9189

File: 1441583813087.webm (109.14 KB, 499x282, 1396643341457.webm)

lainchan can you not fuarrrk the formatting thanks

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include <errno.h>

#define MAX 100000
#define BLK 32
int main(int argc, char **argv)
{
long long *sieve = malloc(BLK * sizeof(long long)), *sievep = sieve, *end;
long long c, i, p;

if(argc != 2) {
fprintf(stderr, "Not enough arguments\nUsage: %s n\n"
"Where `n' is a value from 0 to %lld", argv[0], (long long)MAX);
}

p = strtoll(argv[1], argv + 1 + strnlen(argv[1], 32), 10);

if(errno || p < 0) {
fprintf(stderr, "Argument `%s' out of range (0 - %lld) or system error.\n",
argv[1], (long long)MAX);
printf("%lld\n", p);
return 1;
}

if(p > MAX) {
puts("Don't bother...");
return 0;
}

sieve[0] = 2;
sieve[1] = 3;
for(i = 2, c = 3; i < p; c+=2) {
for(sieve = sievep, end = sievep+i-1; sieve < end; sieve++) {
if(c % *sieve == 0)
break;
}
if(sieve == end && c % *sieve != 0) {
if(i % (BLK-1) == 0) {
*(sievep+i) = '\0';
if((sievep = realloc(sievep, (i+BLK)*sizeof(sievep)))
== NULL) {
fprintf(stderr, "realloc failed\n");
return 1;
}
}

*(sievep+i) = c;
i++;
printf("New prime: %lld [%lld]\n", c, i);
}
}

return 0;
}

>>

 No.9191


#include<stdio.h>

void prime(int amount);

int main(void)
{
int amount;

printf("Enter the amount of prime numbers you want to calculate: ");
scanf("%d", &amount);

prime(amount);
}

void prime(int amount)
{
int prime[amount], number = 3, i = 0, found = 1;
prime[0] = 2;

while (found < amount)
{
for (i = 0; number % prime[i] != 0 && i < found; ++i);

if (i == found)
prime[found++] = number++;
else
++number;
}
for (i = 0; i <= amount-1; ++i)
printf("%2d: %d\n", i+1, prime[i]);
}


I got this but it gives a floating point exception (core dumped) error if I ask for more than 11 prime numbers on my linux laptop and if I ask for more than 12 prime numbers on OS X.

I have no idea why because I never divide by 0 and there are no floating points to be found.

>>

 No.9194

>>9191
I found it (with the help of glorious ncl)
here's the correct version: http://0x0.st/zbu.c
I haven't put any overflow protection in place but blahblah.

>>

 No.9196


#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>

void
die(char *msg)
{
fprintf(stderr, "error: %s\n", msg);
exit(1);
}

int
main(int argc, char *argv[])
{
long n, root_n, m, i, j;
char *sieve;

if(argc < 2)
die("not enough arguments");

n = strtol(argv[1], NULL, 0);
root_n = (long) sqrt(n);
sieve = calloc(n + 1, sizeof(*sieve));
if(!sieve)
die("could not allocate memory");

for(i = 1; i < root_n+1; i++) {
for(j = 1; j < root_n+1; j++) {
m = 4*i*i + j*j;
if(m <= n && (m % 12 == 1 || m % 12 == 5))
sieve[m] = !sieve[m];
m = 3*i*i + j*j;
if(m <= n && m % 12 == 7)
sieve[m] = !sieve[m];
m = 3*i*i - j*j;
if(i > j && m <= n && m % 12 == 11)
sieve[m] = !sieve[m];
}
}

for(i = 5; i < root_n; i++)
if(sieve[i])
for(j = i*i; j < n+1; j += i*i)
sieve[j] = false;

printf("2\n3\n");
for(i = 0; i < n+1; i++)
if(sieve[i])
printf("%ld\n", i);

free(sieve);

return 0;
}

>>

 No.9205

>>9189
Very nice!
Took some time to wrap my head around it, because I don't use C that much, but it looks like a realy fast solution.

>>

 No.9207

Even after 10-15 years of coding, I find these small challenges the most fun to work on.
Perhaps because they are so well defined.

gforth: https://0x0.st/zcu.txt

...posting a link only because I have finally noticed that at the absolute bottom
of the page I get the message that the post body is too long when trying to code tag it.
Hm. or I could try condense it by removing the comments, or the whitespace...

>>

 No.9209

>>9205
There's some needless complexity there from doing reallocing when the final size is known; realized that after I posted it, it's from when I thought we were to find all primes up to a certain number (and thus the size of the array would not be known)

Too lazy to remove it now, but it would probably make it noticeably faster, and a bit easier to read.

>>

 No.9215

>>9178

include Math

def primes_list(limit)
range = 2
collection = (0..range).to_a

collection[0] = collection[1] = nil

loop do
range+=1
collection.push range
(2..sqrt(range)).each do |integer|
if collection[integer]
step = integer**2
while step <= range do
collection[step] = nil
step+=integer
end
end
end
return collection.compact if collection.compact.size == limit
end
end

my bad realized I had specification wrong. Fixed it returns n prime numbers.

>>

 No.9217

>>9215

import math

def prime_list(limit):
rang = 2
collection = range(0,rang+1)
collection[0] = collection[1] = None
while True:
rang+=1
collection.append(rang)
for integer in range(2,int(math.sqrt(rang))+1):
if collection[integer] is not None:
step = integer**2
while step <= rang:
collection[step] = None
step+=integer
primes = [item for item in collection if item is not None]
if len(primes) == limit: return primes

fixed python implementation as well

>>

 No.9220

This version stores only the primes in the sieve, while shorter, and easier to understand, it is much slower than the previous (>>9207) one.
$ time gforth nprimes.fs -e '500000 n-first-primes bye' > /dev/null
real0m2.444s
user0m2.437s
sys0m0.003s
$ time gforth pprimes.fs -e '500000 primes bye' > /dev/null
real0m9.573s
user0m9.553s
sys0m0.010s


...probably because every odd integer has to be individually checked for primality

: fill-with-primes ( addr sz -- )
\ special cases
\ and initialization
dup 1 < if 2drop exit then
>r 2 over ! r>
dup 2 < if 2drop exit then
>r 3 over cell+ ! r>

\ store initial pc (pc: prime-candidate)
\ iterate over i1 = [2,sieve-size) ...index 0 and 1 have been precalculated
\ until pf == true (pf: prime-found)
\ set assumption pf = true
\ iterate over i2 = [0,i1)
\ if sieve[i2] divides pc
\ set pf = false
\ break innermost loop
\ if sieve[i2]^2 > pc
\ break innermost loop
\ if pf == true
\ store pc at sieve[i1]
\ pc += 2

0 rot 5 \ sz pf addr pc=5
3 pick 2 ?do
begin
rot drop 1 -rot \ sz pf=1 addr pc
i 0 ?do
over i cells + @ \ sz pf addr pc addr[i2]
2dup swap mod 0= \ sz pf addr pc addr[i2] divides?
if
drop rot drop 0 -rot \ sz pf=0 addr pc
leave
then
dup * over > \ sz pf addr pc squarebigger?
if
leave
then
loop
2 pick if
2dup swap i cells + !
then
2 + \ sz pf addr pc+2
dup 0< if -11 throw then \ crash on pc overflow
2 pick until
loop
2drop 2drop
;

\ print the contents of an array
: print-array ( addr sz -- )
0 ?do
dup i cells + @ .
loop
drop
;

\ print the n first primes
: primes ( n -- )
dup cells allocate throw \ n addr
swap
2dup fill-with-primes
2dup print-array
drop free throw
;

\ example:
\ 100 primes cr

>>

 No.9222

File: 1441665869754.jpg (107.15 KB, 824x1000, serveimage.jpg) ImgOps Exif iqdb

>>9207
Forth: the final frontier.

>>

 No.9223



(ql:quickload :iterate)
(defpackage #:primes (:use :iterate :cl))
(in-package :primes)

(defun prime? (number)
(when (> number 1)
(iterate (for factor from 2 to (isqrt number))
(never (zerop (mod number factor))))))

(defun primes-upto (number)
(when (>= number 2)
(iterate (for i from 2 to number)
(when (prime? i)
(collect i)))))



PRIMES> (primes-upto 100)
(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)

>>

 No.9233

In racket;


#lang racket

(define (prime-sieve n)
(define (whole-sqrt x)
(inexact->exact (truncate (sqrt x))))
(define table (make-vector (add1 n) #t))
(define (prime? x) (vector-ref table x))
(define (remove-multiples x)
(define multiples
(map (lambda (y) (* x y))
(filter prime? (range x n))))
(for ([i multiples])
#:break (> i n)
(vector-set! table i #f)))
(let sieve ([x 2])
(cond
[(> x (whole-sqrt n)) table]
[(prime? x)
(remove-multiples x)
(sieve (add1 x))]
[else
(sieve (add1 x))])))

(define (primes-up-to n)
(define tab (prime-sieve n))
(filter (lambda (i) (vector-ref tab i))
(range (add1 n))))


Not too elegant, unfortunately, but fairly quick at generating primes.

>>

 No.9237

>>9233
Looks pretty good to me. For what it's worth, primes-up-to could look like this:
(define (primes-up-to n)
(for/list ((p (prime-sieve n) #:when p) p))

>>

 No.9239

>>9220
I'm pretty sure that the program worked when I tested it, nevertheless the version posted here does not work, at all...
For it to work the swap word needs to be removed from this line:
2dup swap mod 0=     \ sz pf addr pc addr[i2] divides?

¬_¬

>>

 No.9246

>>9158
I made it an order of magnitude faster:
-- fast-primes.hs
-- Using the Integral type class instead of just saying Integer might result in
-- the list being calculated multiple times, which is really bad.

-- Every prime above 3 is of the form 6*n+1 or 6*n-1, so we only test those
-- primes
testNums :: [Integer]
testNums = genList [1..]
where genList (n:ns) = 6*n-1:6*n+1:genList ns

primes :: [Integer]
primes = 2 : 3 : accum [3,2] testNums
where accum ps (n:ns) = if testP ps n
then n : accum (ps ++ [n]) ns
else accum ps ns

-- Test if a number is prime given a list of the prime numbers below it in
-- order
testP :: [Integer] -> Integer -> Bool
testP ps n = not $ any (== 0) $
map (n `mod`) $
takeWhile ((<= sqrt (fromIntegral n)) . fromIntegral) ps

-- required by the challenge, I guess
genPrimes = flip take primes


-- used for benchmarking
main = putStrLn $ "The 10000th prime number is " ++ show (primes !! 10000)


Benchmarks:

[alex@jupiter scratch]$ time ./fast-primes
The 10000th prime number is 104743

real0m0.199s
user0m0.197s
sys0m0.000s
[alex@jupiter scratch]$ time ./primes
The 10000th prime number is 104743

real0m3.639s
user0m3.613s
sys0m0.020s

>>

 No.9250

>>9246
Cool, the 6*n+1 and 6*n-1 trick is realy nice. Impressive how a few changes can speed it up by so much.

> Using the Integral type class instead of just saying Integer might result in the list being calculated multiple times, which is really bad.

Could you explain this a little further?

>>

 No.9252

>>9222
The high elves in the ancient forests sing sing their trees and branches into beautiful tools of lisp. But there are other languages, deep down under the mountains, where the walls ar hot to the touch and the smelters never stop glowing.

---

>>9246
It threw me for quite a loop when I compared my output with yours, but then I noticed that you're using zero based indexing, whew.

---

Improved: https://0x0.st/zAn.txt
$ time gforth-fast nprimes.fs -e '10000000 nthprime bye'
179424673

real0m12.363s
user0m12.240s
sys0m0.110s

>>

 No.9256

>>9250
>Could you explain this a little further?
I thought that it would mean that the list might be calculated twice, once as Integer and once as Int, but some testing reveals that that doesn't actually happen, so your way is actually better. Sorry for the inaccuracy.

>>

 No.9260

Pretty simple sieve using Erlang. Maybe I'll try and do the Nth prime number using the 6*n±1 trick.

get_primes(N) -> filter(lists:seq(2, N), []).

filter([], Acc) -> lists:reverse(Acc);
filter(L, Acc) ->
FL = [N || N<-L, N rem hd(L) =/= 0 orelse N =:= hd(L)],
filter(tl(FL), [hd(FL)] ++ Acc).

>>

 No.9262

>>9260
Thinking about it, it's probably better to write the filtering function like:

filter([], Acc) -> lists:reverse(Acc);
filter(L, Acc) ->
[H|T] = [N || N<-L, N rem hd(L) =/= 0 orelse N =:= hd(L)],
filter(T, [H] ++ Acc).

>>

 No.9267

>>9256
Ah OK, I thought it was about some strange internal quirk I didn't know about.

>>

 No.9336

File: 1442041866654.jpg (268.46 KB, 800x800, 226f7d29788bdf96ea2b75be44….jpg) ImgOps Exif iqdb

Good morning lainons. Last weeks challengc already went pretty well, let's try to keep it up.

This week, we'll write a brainfuck interpreter.

> What is brainfuck?

Brainfuck is an esoteric programming language created in 1993 by Urban Müller, and notable for its extreme minimalism.
The language consists of only eight simple commands and an instruction pointer. While it is fully Turing-complete, it is not intended for practical use, but to challenge and amuse programmers.
https://en.wikipedia.org/wiki/Brainfuck

Here's a brainfuck interpreter that runs in your browser, for you to play around with: http://brainfuck.tk/

Also: Let's share cool brainfuck programs we came up with!

>>

 No.9337

>>9336
Here's my implementation in haskell:
http://lpaste.net/140738

Not all that happy with it, as it turned out to be longer than expected.
I'll probably write one in C later today, just so I can compare the length.

>>

 No.9338

>>9336
I'm really high so this is probably garbage but it works.
(define (brainfuck program)
(let ((data (make-vector 150 0)))
(let loop ((inst 0) (data-ptr 0))
(when (< inst (string-length program))
(case (string-ref program inst)
((#\>) (loop (+ inst 1) (+ data-ptr 1)))
((#\<) (loop (+ inst 1) (- data-ptr 1)))
((#\+)
(vector-set! data data-ptr (+ (vector-ref data data-ptr) 1))
(loop (+ inst 1) data-ptr))
((#\-)
(vector-set! data data-ptr (- (vector-ref data data-ptr) 1))
(loop (+ inst 1) data-ptr))
((#\.)
(write-char (integer->char (vector-ref data data-ptr)))
(loop (+ inst 1) data-ptr))
((#\,)
(vector-set! data data-ptr (read))
(loop (+ inst 1) data-ptr))
((#\[)
(loop (if (zero? (vector-ref data data-ptr))
(+ (matching-paren program inst 1 #\[ #\]) 1)
(+ inst 1))
data-ptr))
((#\])
(loop (if (zero? (vector-ref data data-ptr))
(+ inst 1)
(+ (matching-paren program inst -1 #\] #\[) 1))
data-ptr))
(else (loop (+ inst 1) data-ptr)))))
(newline)
(print data)))

(define (matching-paren s i step add sub)
(let loop ((i (+ i step)) (n 0))
(let ((c (string-ref s i)))
(cond
((eq? c add)
(loop (+ i step) (+ n 1)))
((eq? c sub)
(if (zero? n)
i
(loop (+ i step) (- n 1))))
(else (loop (+ i step) n))))))

(brainfuck "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.") ; Hello World!

Holy soykaf I'm sorry it's completely un-DRY and ugly. I'm really sorry about how big `brainfuck` the function is, I hate huge functions especially in Lisps (if only because Lisps are especially guilty of it).

>>

 No.9339

>>9338
    (newline)
(print data)

Delete these lines btw it was just for debugging in Chicken. Code should then be R5RS and R7RS compatible. Change the first value of make-vector to make the buffer size reasonable (from 150 to like 3000 or so I dunno).

>>

 No.9343

>>9336
https://gist.github.com/pjanouch/11c471eec793b24b5c4b
So here's one in C. Would have boated it even more to make it safer and produce useful error messages but whatever.

What I'm partially interested in is making a compiler of a higher level language to BF. But I guess I've got better things to do.

>>

 No.9346

>>9336
let jump_forward program ip =
let rec iter ip depth =
match program.[ip], depth with
| ']', 0 -> ip + 1
| ']', _ -> iter (ip + 1) (depth - 1)
| '[', _ -> iter (ip + 1) (depth + 1)
| _, _ -> iter (ip + 1) depth
in iter (ip + 1) 0

let jump_back program ip =
let rec iter ip depth =
match program.[ip], depth with
| '[', 0 -> ip
| '[', _ -> iter (ip - 1) (depth - 1)
| ']', _ -> iter (ip - 1) (depth + 1)
| _, _ -> iter (ip - 1) depth
in iter (ip - 1) 0

let run program =
let memory = Array.make 256 '\x00' in
let rec execute ip dp =
if ip < String.length program then
match program.[ip] with
| '+' -> memory.(dp) <- Char.chr (Char.code memory.(dp) + 1);
execute (ip + 1) dp
| '-' -> memory.(dp) <- Char.chr (Char.code memory.(dp) - 1);
execute (ip + 1) dp
| '>' -> execute (ip + 1) (dp + 1)
| '<' -> execute (ip + 1) (dp - 1)
| '[' -> if ((Char.code memory.(dp)) = 0) then
execute (jump_forward program ip) dp
else
execute (ip + 1) dp
| ']' -> execute (jump_back program ip) dp
| '.' -> print_char memory.(dp);
execute (ip + 1) dp
| ',' -> memory.(dp) <- (input_char stdin);
execute (ip + 1) dp
| _ -> execute (ip + 1) dp
in
execute 0 0

let () =
run "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."

>>

 No.9347

>>9346
What language is that? ML?

>>

 No.9348

>>9347
ocaml

>>

 No.9349

>>9336
So here's mine in python, I didn't implement the output completely, but that's not very important:
http://pastebin.com/LmGAJEuv

>>

 No.9353

>>9349
Change print `tape[ptr],` to something like `sys.stdout.write(chr(tape[ptr]))` then add `import sys` at the top and it's correct (I think).

>>

 No.9357

>>9353
It works! Thanks!

>>

 No.9363


$location = 0
$buffers = [0]
script_location = 0
file = File.new(ARGF.argv[0], 'r')
$script = (file.read).split("")
loop_end = 0

def run_command(cmd,script_location)
case cmd
when ">"
$location+=1
$buffers.push 0 if $location > $buffers.size-1
script_location+=1
when "<"
$location=$location-1
script_location+=1
when "+"
$buffers[$location]=$buffers[$location]+1
script_location+=1
when "-"
$buffers[$location]=$buffers[$location]-1
script_location+=1
when "."
print ($buffers[$location]).chr
script_location+=1
when ","
a = IO.read '/dev/stdin', 1
print a
if a == nil
$buffers[$location] = 0
else
$buffers[$location] = a.ord
end
script_location+=1
when "["
script_location = run_loop script_location
else script_location+=1 end
return script_location
end

def run_loop(location)
location+=1
loop_start = location
loop do
if $buffers[$location] == 0
until $script[location] == "]"
location+=1
end
return location+1
else
until $script[location] == "]"
location = run_command $script[location],location
end
if $buffers[$location] != 0
location = loop_start
else
return location+1
end
end
end
end

while script_location+1 < $script.size do
cmd = $script[script_location]
script_location = run_command cmd,script_location
end

weird issues with EOF me using OS X and apparently ruby stores EOF as nil at least on OS X, but I believe it works now

>>

 No.9365

>>9363
notice some extraneous code in that
(i authored)
print a
is uneeded, at first i tryed taking control of tty, thats why it was there, but that was a bad idea.
loop_end = 0
is a left over from when i wasnt using methods.

>>

 No.9368

>>9337
Finally finished my C version:
http://pastebin.com/EQa81wDz

I'm not that used to writing C, so the code may be a bit ugly, but it was definetly fun to write.

>>

 No.9502

1024 constant dn \ size of memory consant
variable d0 \ address of first memory unit
variable di \ memory index
variable cn \ size of code
variable c0 \ address of first code unit
variable ci \ code index

: init-mem
dn chars allocate throw d0 ! \ allocate
d0 @ dn 0 fill \ set zero
0 ci ! 0 di !
;
: free-mem d0 @ free throw ;

: ooc? ci @ dup 0 < swap cn @ >= or ; \ out of code?

: ci@ ooc? throw c0 @ ci @ chars + c@ ; \ get instruction
: cii ci dup @ 1+ swap ! ; \ go to next instruction
: cid ci dup @ 1- swap ! ; \ go to previous instruction
: di@ d0 @ di @ chars + c@ ; \ read at data+index
: di! d0 @ di @ chars + c! ; \ store at data+index
: dii di @ 1+ dn 1- and di ! ; \ increase data index
: did di @ 1- dn 1- and di ! ; \ decrease data index

: _ postpone postpone ; immediate
: compile-bracerunner
>r _ begin
r> compile, _ ci@
_ dup '[ _ literal _ = _ if _ swap _ 1+ _ swap _ else
_ dup '] _ literal _ = _ if _ swap _ 1- _ swap _ then _ then _ drop
_ dup _ 0= _ until
_ drop
;

: interpretchar ( c -- )
dup '< = if did else
dup '> = if dii else
dup '+ = if di@ 1+ di! else
dup '- = if di@ 1- di! else
dup '. = if di@ emit else
dup ', = if key di! else
dup '[ = if di@ 0= if 1 [ ' cii compile-bracerunner ] then else
dup '] = if di@ 0<> if -1 [ ' cid compile-bracerunner ] then then
then then then then then then then drop
;

: runinterpreter ( -- )
init-mem
begin
ci@ interpretchar cii
ooc? until
free-mem
;

: runstring ( addr n -- )
cn ! c0 !
runinterpreter
;

\ Hello World! found on wikipedia
s" ++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."
runstring
bye


gforth - now with macro!

>>

 No.9503

>r _ begin
> implying return stack opperations
¬_¬

>>

 No.9506

I have a bf interpreter in C i was working on a while ago. It's almost finished, maybe I'll work on it tomorrow if I have time.

>>

 No.9513

>>9502
Good job Lainon. Would you like some pointers to improve your program?

>>

 No.9516

>>9513
By all means if you have any suggestions/comments I'd be happy to hear them.

FWIW I have pondered e.g. that
di@ 1+ di!

expands to
d0 @ di @ chars + c@ 1+ d0 @ di @ chars + c!

which is not very efficient (I assume, I have no actual bench data) and could be written better as
d0 @ di @ chars + dup c@ 1+ swap !

but writing it out like that would mean losing some of the clarity in interpretchar which I wanted to keep.

The >r...r> hack in compile-bracerunner is something that I'm not entirely
happy with, but I glanced some 'locals considered harmful' headline somewhere and usually avoid them, but postponing stuff puts junk on the stack.

I usually avoid variables and push everything around on the stack as well, and the code could be commented better...

>>

 No.9517

>>9516
! in the last example should be c! of course

>>

 No.9518

>>9502
>>9516
You have almost no stack comments. You commented single line words, but didn't comment compile-bracerunner at all. This word is long and confusing and I haven't been able to step through it yet. I am pretty tired right now though. Refactoring that is still important.
Interpretchar would benefit from a case instead of nested if else thens.
0 fill in init-mem should be erase.
I don't believe I noticed any memory protection to stop a program from travelling outside of the data array. You probably knew this already. What I would do is add a mod on every memory access. Not only would this make things safe, but it would cause memory to wrap around, which is what many implementations do.
The only other thing I would try to change that I can think of right now is the naming convention leading to names like cii, cid, did, and dii.

I think I may try my hand at a Forth implementation here at some point. This thread is interesting. I'll certainly keep it up from now on.

>>

 No.9527

>>9518

> no stack comments

A valid point. They're not there because a lot of operations are similar (read-modify-store), so I managed to keep it all in my head. I can see how that would be difficult for people who do not possess my head though, or when my head has forgotten what it thought of.

> the cf that is compile-bracerunner

I'm pretty new wrt forth macros
di@ 0=  if  1 [ ' cii compile-bracerunner ] then 

which is run when the current instruction is '[', becomes

di@ 0= if \ if the current memory cell is 0, skip until matching closing brace
1 begin \ ctr=1 seed the counter with 1, since we begin on a '['
cii ci@ \ ctr instr go to the next instruction and read it
dup '[ = if \ check what the instruction is - probably be case of should be using case
swap 1+ swap \ ctr+1 instr '[' - increase the counter
else \
dup '] = if \
swap 1- swap \ ctr-1 instr ']' - decrease the counter
then \
then \
drop \ ctr instruction testing done, drop it from the stack
dup 0= until \ ctr loop until the counter reaches 0 = we have reached '['-']'-balance
then

The act of putting it in a macro like that is so that it can be done with both cii and cid as the word that changes
code position, depending on if we want to walk forwards or backwards in the code. A non-macro variant could be putting everything except cii that's inside the begin-until loop into a regular word and have the line in interpretchar look like
di@ 0= if 1 begin cii runtime-bracerunner until then 

...but that's less fun, also I didn't think of it before. Actually, during development I initially planned on macrofying even more
so that the line would be something like
[ ' cii 1 ' 0= compiletime-evenmoreconvoluted-bracerunner ]

but I gave up that when I noticed how postponing stuff polluted the data stack.

I see now also that the instruction testing and counter modifying could have been written as

dup '[ = if \ ctr instr
drop 1+ \ ctr+1
else \ ctr instr
dup '] = if \ ctr instr
drop 1- \ ctr-1
else \ ctr instr
drop \ ctr
then \ ctr
then


> case, erase

I need to read more, instead of just plodding along with the words I already know.

> memory protection

It does actually exist, although not in the access words di@/!, but in the words that change the pointer (dii/d) in which after increasing or decreasing the pointer value, the result is and-ed with the size of the array (dn) - 1, which is the same as doing the modulo action as long as the array size is kept to a power of two.

> more descriptive word names

b-but isn't it obvious that it means code/data - index - increase/decrease ...hm perhaps it isn't

>>

 No.9533

>>9527
Okay. Your compile-bracerunner description is nice.

>I need to read more, instead of just plodding along with the words I already know.

You're doing great so far. Those words are in the core extension word set though. It's strange to not be familiar with the core and core-ext word sets before using other words from optional word sets, like free.

>It does actually exist, although not in the access words di@/!, but in the words that change the pointer (dii/d) in which after increasing or decreasing the pointer value, the result is and-ed with the size of the array (dn) - 1, which is the same as doing the modulo action as long as the array size is kept to a power of two.

Okay. I didn't notice that. I was actually very confused with those words because I read dn as di.

>b-but isn't it obvious that it means code/data - index - increase/decrease ...hm perhaps it isn't

You should choose better names. It was very easy for me to misread your program because of how similar they are, as you can see above.

>>

 No.9542

>>9533
>It's strange to not be familiar with the core and core-ext word sets before using other words from optional word sets, like free.
Depends on how one learns, I read until I got the basics more or less, and then started doing e.g. project euler stuff, which quickly lead me to looking after ways get hold of heap memory to store data in.
Also, my note about word names was meant to be taken in jest. (I'm behind the forth based prime sieves earlier in the thread as well, the words in them are a bit better named)

>>

 No.9544

>>9542
>Depends on how one learns, I read until I got the basics more or less, and then started doing e.g. project euler stuff, which quickly lead me to looking after ways get hold of heap memory to store data in.
That's fair enough. I wasn't trying to be rude or anything like that.
>Also, my note about word names was meant to be taken in jest. (I'm behind the forth based prime sieves earlier in the thread as well, the words in them are a bit better named)
Yeah. The stuttering gave that away. I just responded seriously anyway.

Something you may want to know that I forgot to mention earlier: Forth systems typically perform no optimizations. As of right now, I only see a few points in your program that could be optimized with the idiom I was going to show.

When you're doing arithmetic or anything else that results in constant data, you have to fold them explicitly.
: dii di @ 1+ dn 1- and di ! ;          \ increase data index
Here, dn is a constant. Unless you fold it, 1- will always be performed. Here's the optimized version:
: dii di @ 1+ [ dn 1- ] literal and di ! ;
Now 1023, or whatever dn 1- is will be compiled directly into the definition, instead of needing to be generated each time.

Here's one more example:
: init-mem
[ dn chars ] literal allocate throw d0 ! \ allocate
d0 @ dn 0 fill \ set zero
0 ci ! 0 di !
;
This removes a multiplication every time init-mem is called.

These are just small optimizations, but they can give much larger yields depending on what's being done.

>>

 No.9545

>>9363
I want some one to harshly judge my implementation this is making me jealous. I know their were more rubyesque ways to do this, but I kinda forget them. Any rubyist here to slam me?
>>9365
I already corrected my extraneous code here ^

>>

 No.9559

I started learning C, so I made a prime finder for it. Don't go easy on me because I just started, just keep in mind that there are some things I might not know existd (But want to know!):

http://pastebin.com/mAUJ3Gww

>>

 No.9564

>>9559
I'm not all that proficient at C myself, but I still tried to correct what I could.
I wrote a comment for every change I made.

http://pastebin.com/kwbvn5Nd

Feel free to ask questions, if my explanations aren't clear / I forgot to comment a change.

>>

 No.9565

>>9564
That's really nice of you! I understood all of it!

I tried initializing it as int primes[];, but it said it didn't know how long it was so I just put a random number in there.

Thanks for your help again.

>>

 No.9566

>>9565
Have you tried running it?
The program running as you expect it to would mean the array is properly allocated.

>>

 No.9567

>>9566
Yup, that's what I mean, apparently running it as int primes[]; gives an error while int primes[50]; doesn't.

>>

 No.9574

>>9567
Thats because C only supports arrays where the size is known ahead of time. A C array must have either an implied length or an explicitly stated length

int primes[] = {2,3,5,7,11};
int primes[5]
int primes[] // This is an error, length neither stated nor implied

>>

 No.9578

>>9574
Hey, thanks for your help.

>>

 No.9582

File: 1442648613970.jpg (59.96 KB, 706x706, 1430097620146.jpg) ImgOps Exif iqdb

>>9157
Let's do this.

>>

 No.9585

Scheme (bad but works)

(define (rep n s l)
(if (= n 0)
l
(rep (- n 1) s (cons s l))))

(define bfvector (list->vector (rep 100 0 '())))

(define pos 0)

(define spos 0)

(define loop-stack '())

(define (reset)
(begin (set! pos 0)
(set! spos 0)
(set! loop-stack '())
(set! bfvector (list->vector (rep 100 0 '())))))

(define (ev x) (case x ((43) (begin (set! spos (+ spos 1))
(vector-set! bfvector pos (+ (vector-ref bfvector pos) 1)))) ; +
((45) (begin (set! spos (+ spos 1))
(vector-set! bfvector pos (- (vector-ref bfvector pos) 1)))) ; -
((62) (begin (set! spos (+ spos 1))
(set! pos (+ pos 1)))) ; >
((60) (begin (set! spos (+ spos 1))
(set! pos (- pos 1)))) ; <
((91) (begin (set! spos (+ spos 1))
(set! loop-stack (cons spos loop-stack)))) ; [
((93) (if (= (vector-ref bfvector pos) 0)
(begin (set! loop-stack (cdr loop-stack))
(set! spos (+ spos 1)))
(set! spos (car loop-stack)))) ; ]
((46) (begin (set! spos (+ spos 1))
(display (integer->char (vector-ref bfvector pos))))) ; .
((44) (begin (set! spos (+ spos 1))
(vector-set! bfvector pos (char->integer (read-char))))) ; ,
))

(define (evaluate xs)
(define (iter len xs)
(if (= spos len)
(newline)
(begin (ev (list-ref xs spos)) (iter len xs))))
(iter (length xs) xs))

(define (bf x) (evaluate (map char->integer (string->list x))))


output:

> (bf "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.")
Hello World!




Also never really used vectors before

>>

 No.9586

alright, poasting to try a challenge.

>>

 No.9588

File: 1442687699542.jpg (277.19 KB, 615x517, 1438292013731.jpg) ImgOps Exif iqdb

Alright guys, now I made a brainfuck interpreter for C, I'm catching up with you guys. I don't know how to implement the special output in C either, and I don't know how to turn a string into a integer for the input, but here it is:
http://pastebin.com/bQ64FHkF

>>9586
Please don't roll here, use random.org

>>

 No.9593

File: 1442692069469.jpg (324.57 KB, 600x849, ed4732713eda321fa69ff38002….jpg) ImgOps Exif iqdb

Hello again, I'm a little late today, but better late than never, right?

This week, we'll write a program that simply sorts the lines of a file.

> That's way too easy, give me something harder.

Sure, make it, so that the program can sort files bigger than your RAM.

>>

 No.9599

>>9593
perl -we 'print sort <>'

>>

 No.9601

>>9588
Overall realy good, but here a few improvements I would make.

Rename ptr to index, as it's not actualy a pointer.
Move the declaration of the jump variable into the cases where it is used.

Also, there's no reason to have this default case in place. If you leave it out, people can have whitespace etc in their source code.

>>

 No.9602

>>9593
Can I sort based on the lines' position in the file? Present Day, Present Time! AHAHAHAHAHA!

>>

 No.9604

Just noticed how easily you can implement the Sieve of Eratosthenes in Haskell.

primes :: Integral i => [i]
primes = go [2..]
where go (p:rest) = let next = go . filter (`notDivisibleBy` p) $ rest
in p:next
notDivisibleBy a b = a `mod` b /= 0

That's literally it. All hail lazyness!

>>

 No.9605

>>9604
Unfortunately that's not the Sieve of Eratosthenes, it just looks like it.

See "The Genuine Sieve of Erastothenes", https://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf

>>

 No.9606

>>9588
This looks really good. I teach a little bit of programming to totally new students and I've used this task as an exercise before. All in all this is a nice clean implementation.

To point out a few problems though.

First, you've made a mistake everyone makes when they write a brainfuck interpreter, but it's a mistake in understanding brainfuck rather than in your coding. When it hits a "[" and array[ptr] is 0 it should skip to the corresponding "]". So brainfucks brackets work more like a while(){} loop than a do{}while() loop, but that's something everyone misunderstands about brainfuck and shouldn't be too hard to fix. Also, in this vein when it gets unrecognised input it should just ignore it rather than complaining. This may seem pedantic, because it is, but computers are pedantic and it's very important to do everything exactly as the spec says. For instance, in this case, if I were to try and run a brainfuck program I downloaded, there's a good chance it wouldn't work because people often use this behaviour to add comments.

You really, really need to be careful when using arrays (i.e. 90+% of the time). Going beyond the bounds of your arrays is incredibly dangerous, some languages have protection, C does not. If you declare array[50] and then use array[70]. C will not crash or complain that you went out of bounds it will just do it and go 20 units of memory past the end of the array. Of course this memory is being used by other parts of your program. This is the cause of so many problems and is one of the big points everyone brings up when they criticise C (quite fairly). If you want to write good, safe C you need to be really careful about this and it shows up everywhere.

Your program maintains a special data structure called the stack, I won't go into detail but local variables such as your array are stored there. Also stored there is information regarding what code should be executed and by going just the right amount outside of the bounds of your array, I can modify that information. Obviously this is a big security risk.

As it stands if I were to write a program that had 30000+ ">" symbols then a + it would add one to whatever random data was there and you need to check for that. But that prompts the question of what should the interpreter do when it gets 30000 ">" symbols as genuine input? Like the answer to any "what should it do" question it should be in the spec. If it isn't it needs adding, ambiguity is always bad in specs. If I recall correctly it's supposed to wrap back round to 0 at some point.

There are another two instances of your code going outside of the bounds of an array, besides the one I mentioned (see what I mean about being everywhere?). In the interests of learning, I won't tell you where. The harder of the two to spot is really quite hard to just notice, though every experienced programmer knows about it because this exact mistake is probably the single biggest cause of security vulnerabilities in history. If you'd rather I just told you just ask, but being able to see these problems is a part of writing good C that needs hammering into heads as early as possible.

Anyway, I've nitpicked and slammed on about bounds checking for an age (it's genuinely that important) but really, overall this is very good. You noticed that nested brackets were going to be something that needed handling, that's a good sign. If you noticed it without seeing it break first, that's an even better sign. Keep at it and you'll make a good programmer.

If you want to extend your interpreter you could add caching for bracket finding, so that the first time it encounters a bracket it does the search as usual then saves the result, after that it just looks the result up. It's a good exercise to follow up because while there's a good amount of logic to brainfuck there's not much in the way of data structure at all and this is a nice simple thing in that regard.

>>

 No.9607

>>9605
Realy interesting read.
It kind of reminds me of this article: http://augustss.blogspot.de/2007/08/quicksort-in-haskell-quicksort-is.html

>>

 No.9608

>>9607
Yeah, there are a load of simple Haskell functions we like to trot out and say to beginners "look how elegant quicksort/sieving/whatever is in Haskell!", but it's not quite true.

>>

 No.9609

>>9601
>>9606
Thank you very much guys, all your advice has been noted, and I will fix them all, and try to protect those bounds.
I won't let you down.

>>

 No.9610

>>9157

Rolling in the table

>>

 No.9611

>>9585
fixed a few problems and added two modes: https://gitgud.io/cryptokitty/sbf/blob/master/sbf.scm

>>

 No.9625

>>9593
Like what are we sorting the lines by? Length, alpha, numeric ?

>>

 No.9626

>>9625
Easy mode: Whatever method you like, it doesn't really matter.

Hard mode: Whatever method the user likes. By this I mean that your sorting function should also accept a comparison function as an argument that tells it how to sort things.

>>

 No.9627

>>9626
Super hard mode: the sorting function isn't required to be transitive, however each adjacent pair of lines in the output must compare as sorted consistently.

>>

 No.9628


file = File.new(ARGF.argv[0], 'r')
tosort = file.readlines()
file.close()
file = File.new(ARGF.argv[0], 'w')
(tosort.sort).each{ |line| file.write(line) }
file.close()

lazy af

>>

 No.9652

>>9593
How about some D

import std.algorithm, std.array, std.stdio;
void main() { foreach (l; stdin.byLineCopy().array().sort()) writeln(l); }

>bigger than your RAM
That's what a swap is for no?

>>

 No.9653

>>9652
Fine, bigger than your RAM+swap.

>>

 No.9660

Partial solution, I don't currently have the willpower to go through with loading files into arrays of strings
...that's the kind of stuff I use perl for, on the other hand this pretty much the first time I've implemented
a sorting algorithm that's not some variant of bubblesort.
\ print array contents
: .array ( A n -- ) '( emit space cells 0 ?do dup i + @ . cell +loop ') emit cr drop ;

\ allocate space and stuff a number of stack items onto the heap
\ note that the array is top-loaded
: >array ( d0 ... dn-1 n -- A )
dup cells allocate throw \ dn-1 ... d0 n A
over cells -1 swap \ -1 nc
do \ dn-1 ... d0 A
tuck i + !
cell -loop
;

\ swaps two elements of an array
: array-swap ( i j A -- )
>r \ r:A i j
cells r@ + dup @ \ r:A i A+j A[j]
rot \ r:A A+j A[j] i
cells r> + dup @ \ A+j A[j] A+i A[i]
-rot ! \ A+j A[i]
swap !
;

: _ postpone postpone ; immediate
\ compiles a function that does something with data
\ fetched from two positions in an array
: compile-array-binf ( compile-time: xt -- ) ( run-time: i j A -- ? )
_ rot _ cells _ over _ + _ @ \ j A A[i]
_ rot _ cells _ rot _ + _ @ \ A[i] A[j]
compile, \ ?
;

\ Hoare partitioning with the first element as pivot
: partition ( A n -- )
0 swap \ A left=0 right=n
begin
\ count down the right counter
\ A left right
begin
1- \ A left right-=1
dup 0 4 pick \ A left right right 0
[ ' <= compile-array-binf ] \ A left right f
until

\ count up the left counter
swap \ A right left
begin
1+ \ A right left+=1
dup 0 4 pick \ A right left left 0
[ ' >= compile-array-binf ] \ A right left f
until
swap \ A left right

\ swap as necessary and possibly return
2dup < if
2dup 4 pick array-swap
else
nip \ A right
dup rot 0 swap \ right right 0 A
array-swap
exit \ right
then
again
;

: quicksort ( A n -- )
dup 1 > if
2dup partition \ A n p

2 pick over \ A n p A p
recurse
1+ tuck \ A p+1 n p+1
- swap cells rot + swap \ A+p+1 n-p-1
recurse
else
2drop
then
;

." EXAMPLE ( numbers chosen by fair dice roll ) :" cr

3 19 9 16 20 6 7 4 5 14 10 8 18 2 15 13 1 12 11 17
20 >array

4 spaces ." unsorted:" cr
8 spaces dup 20 .array
dup 20 quicksort

4 spaces ." sorted:" cr
8 spaces dup 20 .array

free throw

cr cr

92 60 7 74 43 68 48 66 87 27 11 9 3 51 10 42 62 85 30 45
33 26 17 1 8 91 84 99 37 21 86 56 98 76 71 20 95 4 24 70
13 6 82 88 77 55 23 41 75 94 34 36 12 35 96 100 2 25 38 28
32 15 47 61 14 54 69 93 19 22 81 59 72 97 53 18 40 78 63 50
52 46 39 5 90 64 57 16 79 31 89 73 44 83 80 58 65 29 67 49
100 >array

4 spaces ." unsorted:" cr
8 spaces dup 100 .array
dup 100 quicksort

4 spaces ." sorted:" cr
8 spaces dup 100 .array

free throw

bye

>>

 No.9710

>>9660
Would you point me to the documentation for the Gforth extension that lets you use words like '( and ')?

>>

 No.9751

>>9710
It took me a while to find, since I didn't know where I got it from.
Apparently it's not words either (hinted at by e.g. "see 'x" failing) but in the number conversion:
http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Number-Conversion.html

>>

 No.9762

>>9157
Rolo

>>

 No.9763

>>9157

Rolling... :)

>>

 No.9774

>>9157
roll

>>

 No.9776

Dice rollRolled 1, 3, 3, 2, 3, 4 + 2 = 18

>>9762
>>9763
>>9774
We aren't THAT fast at getting new posts for that kind of rolling to work.

Use dice. dice 6d4+2 For example, is 6 rolls on a four-sided dice, with a modifier of +2.

>>

 No.9825

In a post Snowden age these would be good to learn.
http://cryptopals.com/sets/1/

>>

 No.9832

Here's my solution to this weeks problem in C.

http://pastebin.com/XC4VpG9Q

It can sort files larger than your RAM and swap, as it sorts using the mergesort algorithm.
This way, there are only two lines in RAM at any time.

There is only one known problem with the code, which is that lines might exceed MAX_LINE_SIZE in length and therefore mess up the whole program.

>>

 No.9835

So I had this idea that it should be possible to compile bf code into forth words. Finally got it working and posted here, only to find out that there was a lot of improvements to make, the comments were all wrong etc etc, so I deleted it. But now I'm back:
implementation: https://0x0.st/z3Q.txt
example use: https://0x0.st/z31.txt
even smaller example use:
: small-example
\ will print an '@'
cr
[bf-setup]
[bf]" ++++[->++++<]>[-<++++>]<."
[bf-teardown]
cr
;
small-example
@

see small-example
: small-example
cr bf-setup 4 bf+-
BEGIN 2dup + c@
WHILE -1 bf+- 1 bf<> 4 bf+- -1 bf<>
REPEAT
1 bf<>
BEGIN 2dup + c@
WHILE -1 bf+- -1 bf<> 4 bf+- 1 bf<>
REPEAT
-1 bf<> bf. bf-teardown cr ;

>>

 No.9858

>>9825
Thanks for posting this, I had forgotten the address.

>>

 No.9867

File: 1443312550508.png (90.23 KB, 200x200, Nefquinteroselfshot - Copy.png) ImgOps iqdb

__ CHALLENGE __
Make a better and 31337:er script than this:


# -*- coding: utf-8 -*-
import random
import time
import os

os.system("color a")
def newline():
chars = "1234567890+/\\"
space = " " * random.randint(0, 2)
line = random.choice(chars) + space
return line
while True:
stringlist = list()
for i in range(0, 81):
matrixline = list()
matrixline.append(newline())
if len(matrixline) >= 80:
break
string = "".join(matrixline)
if string not in stringlist:
stringlist.append(string)
print string,
time.sleep(0.001)

>>

 No.9870

File: 1443320340040.jpg (90.82 KB, 703x563, 1423517393204.jpg) ImgOps Exif iqdb

compsci freshman here, did I do good lain? Am I gonna make it?

#include <stdio.h>

void main(){

for(int i = 2; i <= 100; i++){
if((((((i % 2 == 0 && i != 2)|| i % 3 == 0 && i != 3)
|| i % 5 == 0 && i != 5) ||
i % 7 == 0 && i != 7 )||
i % 11 == 0 && i!= 11) ) {
printf("");
}else
printf("%d ", i);
}
}

>>

 No.9871

>>9870
start with code tags
then get a montage going and work your way to the top

>>

 No.9873

>>9870
I bet you could get a job at red hat easy.

>>

 No.9874

>>9870
>((((((
:)))

>>

 No.9875

>>9867
what is that bash script named color?

>>

 No.9876

>>9874
Anon is combining C and lisp for this one

>>

 No.9878

>>9875
It submeshes the processing plateau and turns your text green.

>>

 No.9879

File: 1443338058497.gif (2.52 MB, 306x352, 1418464973128.gif) ImgOps iqdb

You shazbots better turn it up a gear because im leaving you in the dust

<HACKING SIMULATOR V.2000>
CHANGELOG:
NOW WITH PROPER UNIQUE LINES, POORFAGS WONT BE ABLE TO KEEP THIS UP FOR LONG

# -*- coding: utf-8 -*-
import random
import time
import os
os.system("color a") # turns font colour into a more 37331 one, lincucks will never get this


def matrixline():
xlist = list()
for i in range(0, 81):
chars = "1234567890+/\\"
space = " " * random.randint(0, 3)
line = random.choice(chars) + space
xlist.append(line)
if len(("".join(xlist))) >= 80:
break
xstring = "".join(xlist)
return xstring

onetime = 1
while True:
if onetime == 1:
onetime -= 1
matrixlist = list()
string = matrixline()
if string not in matrixlist:
matrixlist.append(string)
print string
time.sleep(0.04)

>>

 No.9880

>>9870
Remove those parentheses from your if clause and put them only around the ands.
Not only will it make it more readable, but it'll speed it up quite a bit.
https://en.wikipedia.org/wiki/Short-circuit_evaluation

Also, look at some of the examples further up the thread for examples on how to improve, especially >>9189

>>

 No.9882

>>9870
Reuse

#include <stdio.h>

int test(int I, int t_num) {
if(test_1(I, t_num) && test_2(I, t_num))
return 1;
return 0;
}

int test_1(int I, int t_num) {
if(I % t_num == 0) return 1; return 0;
}

int test_2(int I, int t_num) {
if(I != t_num) return 1; return 0;
}

int main() {
int I;
for(I = 2; I <= 100; I++) {
if(test(I, 2) || \
test(I, 3) || \
test(I, 5) || \
test(I, 7) || \
test(I, 11))
{ printf(""); } else printf("%d ", I);} return 0;
}


>>

 No.9884


>>

 No.9888

Just started learning Python as my first language. Don't know how to make any of the challenges, so I thought I'd show my tip calculator. It's really simple, but I thought I'd just post it anyways.



# Revision to Version 0.2
# Change log
# *subtotal, tax, and tip variables changed from string to integers.
# **Reasoning: Strings cannot have arithmetic performed on them.
# *"%s" Changed to "%f"
# **Reasoning:"%s" is for strings. The printed result contains decimal values, and therefore it is a float, and same with the variables. Therefore, "%f" is used.
#
# Original code left for example of not what to do.

print "Python Tip Calculator Version 0.2"

print "Tip Calculator"

subtotal = 15.85
tax = .08
gratuity = .15

meal = subtotal * tax + subtotal
tip = subtotal * gratuity
total = meal + tip

print("%f" % tip)
print("%f" % total)


>>

 No.9889

>>9888
use .format() instead
price = 10
product = "banana"
print "the {1} costs {0} dollars but he only has {0} dollars and 9 cents to pay for the {1}".format(price, product)

>>

 No.9890

>>9888
could use input() to have the user enter variables

>>

 No.9891

>>9890
I would have done that, but I haven't learned it yet. Let me look it up and then I'll change it in Version 0.3.

Would it just be like:



subtotal = input()
tax = input()
gratuity = input()



?

>>

 No.9893

>>9157
rolling

>>

 No.9934

File: 1443468133851.jpg (67.14 KB, 392x440, sample_afd2d97da1d761f3a2d….jpg) ImgOps Exif iqdb

Good evening guys.
This week, we'll implement an enigma.
Do any setup you like or even a generic one, allowing you to compose different enigmas.

>An Enigma machine was a series of electro-mechanical rotor cipher machines developed and used in the early to early-mid twentieth century for commercial and military usage.

https://en.wikipedia.org/wiki/Enigma_machine

Here's a nice series on the enigma:
https://www.youtube.com/watch?v=d2NWPG2gB_A&list=PLzH6n4zXuckodsatCTEuxaygCHizMS0_I

>>

 No.9936

>>9934
are you OP? Have you been taking care of this thread since you started it?

Do you have some contact you dont mind sharing?

>>

 No.9937

>>9936
Yeah, I'm desugusting on #learnprog and #lainchan, just hit me up there.

PM me if I don't respond, I have a bouncer and see your messages as soon as I come back.

>>

 No.9987

Just banged this out. This is one I saw in the undergrad programmer maymay thread.
It prints a big X made up of '*'s.


#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
if(argc != 2)
{
printf("Requires length arg.\n");
return 0;
}
int lines = atoi(argv[1]);
char *line = (char *)malloc(sizeof(char)*lines);
int i;
for(i =0; i<lines; i++)
line[i] = ' ';
int a, b, x, y, z;
a=0;
b=lines-1;
for(z=0; z<lines; z++)
{
for(y=0; y<lines; y++)
{
line[a] = '*';
line[b] = '*';
}
if(a<lines && b>-1)
{
a++;
b--;
}
for(x=0; x<lines; x++)
{
printf("%c", line[x]);
line[x] = ' ';
}
printf("\n");
}
return 0;
}

>>

 No.9990

>>9987
These are the kind of shitty tasks that fuarrrk up your job interview.
You'll always want to make them as simple and elegant as possible and never finish on time.

>>

 No.10021

>>9987


#include<stdio.h>
#include<math.h>

int size = 10;

void main(int argc, char* argv[])
{
if(argc == 2) { size = atoi(argv[2]); }
int x,y;
for(y=0;y<size;y++, printf("\n"))
for(x=0;x<size;x++)
{
printf(abs(y/x)==1?"X":" ");
}
}


Someone tell me if this works im on my phone rn

>>

 No.10022

>>10021
soykaf y and x need to be floats and i meant abs(floor(y/x))

>>

 No.10029

>>10021
Doesn't this code divide by 0 in the first iteration of the x-loop?
Also, if I get it right, it only draws one diagonal line instead of an X.

Shouldn't this print do the same in this situation?

printf(x==y?"X":" ");

>>

 No.10033

>>10029
yeah i totally messed that up lol. home now i fixed it. not happy with it though. anyone can figure out how to make this C code shorter?


#include<stdio.h>
#include<math.h>

void main(int argc, char* argv[])
{
float size = 10;
if(argc == 2) size = atof(argv[2]);

float mid = size/2;

float x,y;
for(y=1;y<size;y++, printf("\n"))
for(x=1;x<size;x++)
printf(mid-x+mid-y==0 || fabs( (mid-y)/(mid-x) )==1 ? "x":"_");
}

>>

 No.10035

>>10033
ok here we go. i dare anyone to make a more concise solution than this

#include<stdio.h>
void main(int argc, char* argv[])
{
int x, y, size = 10;
if(argc == 2) size = atoi(argv[1]);
for(y=0; y<size; printf("\n"), y++)
for(x=0; x<size; printf(x==y||y==size-1-x?"X":"_"), x++);
}

>>

 No.10036

>>10035
int x, y, size = argc==2 ? atoi(argv[1]) : 10;

>>

 No.10044

>>10021
if you're checking for argv==2, shouldn't the index used be 1?

>>10035
: x dup 0 do dup 0 do i j <> over i - 1- j <> -88 * * 120 + emit loop cr loop drop ;


somewhat equivalent to

void x(int n) {
for (int j=0; j<n; ++j) {
for (int i=0; i<n; ++i) {
fputc((i!=j)*(n-i-1!=j)*-88 + 120, stdout);
}
fputc(10, stdout);
}
}

>>

 No.10048

>>10044
yeah i messed that up lol
>>10035 is my final in C

let me know if anyone can do smaller in C I wanna see

>>

 No.10097

old one but yea




#include <stdio.h>
#include <stdbool.h>

bool isPrime(int n){

int divisor;

if(n <= 1)
return false;
for(divisor = 2; divisor * divisor <= n; divisor++){
if(n % divisor == 0)
return false;
else
return true;
}
}
void main(){
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(isPrime(num))
printf("%d is a prime.\n", num);
else
printf("%d is not a prime.\n", num);

}

>>

 No.10101

>>9157
rollin

>>

 No.10110

>>10097

for(divisor = 2; divisor * divisor <= n; divisor++){
if(n % divisor == 0)
return false;
else
return true;
}

This code doesn't seem right.
By returning true in the else-clause, you effectively only test wether n is divisible by two.
The code should actualy be

for(divisor = 2; divisor * divisor <= n; divisor++){
if(n % divisor == 0)
return false;
}
return false;

Props on the style of your code, though. It's nice and readable.

Also please wrap your code in code tags like these [ code] [ /code]. (without the spaces after the brackets)

>>

 No.10111

>>10110
Oops, I meant to write
return true;

after the for-loop.

>>

 No.10114

>>9582
>>9610
>>9762
>>9763
>>9774
>>9776
>>9893
>>9884
>>10101

Please don't roll in here.
Here's a handy script you can use instead:

#!/usr/bin/env python3
import random

print("You rolled %s." %
random.randint(0, int(input("What number do you want to roll to? "))))

>>

 No.10119

>>10048
#include <stdio.h>
#include <stdlib.h>
void main(int c, char** v) {
for(int n=c==2?atoi(v[1]):10, j=n; j--; puts(""))
for (c=n; c-=printf(c==j+1||j==n-c?"X":" "););
}

>>

 No.10120

>>9155



import math

def allPrimes(n):

numPrimos = 0

for i in range(2, n + 1):
primo = True;

for j in range(2, int(math.sqrt(i)) + 1):
if i % j == 0:
primo = False

if(primo == True):
print("The number", i, "is prime.\n")
numPrimos += 1

print("Total number of prime numbers is", numPrimos, ".\n")


>>

 No.10121

>>9157
Rolling in the deep

>>

 No.10130

projecteuler.net

>>

 No.10153

>>9934
I actualy got off my ass and did the enigma.
This time, it's in scheme, as I'm working through the SICP right now.
I don't know how to manipulate strings, yet, so the message has to be a list of lowercase, one character symbols.
Also, this is just a generic enigma, I couldn't be assed to hardcode the original rotors and reflectors.

http://pastebin.com/zMbXc9nc

Any tips from you scheme masters out there is very welcome.

>>

 No.10179

File: 1444085072835.jpg (64.55 KB, 479x478, sample_3f5775508ba3838e0cf….jpg) ImgOps Exif iqdb

Seems like I kinda got away from the idea that the challenges should be simple with the last one.
Let's try to go back to the roots on this one.

This week we'll write a fuzzy string matcher.
There are realy complicated ones out there, but this one is quite simple.
It basicly checks wether the characters are present in that order in the string, so
# True, because "_l_ove _l_ain"
fuzzy_match("ll", "love lain")

# False, because there's no a between the l's
fuzzy_match("lal", "love lain")


I hope this is a challenge everyone feels confident to participate in.

>>

 No.10180

>>10179
It's pretty simple to do in haskell.

fuzzyMatch :: Eq a => [a] -> [a] -> Bool
fuzzyMatch _ [] = False
fuzzyMatch [] _ = True
fuzzyMatch (p:ps) (x:xs)
| p == x = fuzzyMatch ps xs
| otherwise = fuzzyMatch (p:ps) xs

>>

 No.10182

>>10180

You've got an edge case there:

Prelude> fuzzyMatch "ll" "love lain"
True
Prelude> fuzzyMatch "lal" "love lain"
False
Prelude> fuzzyMatch "ll" "ll"
False

>>

 No.10183

>>10182
Oh shit, you're right.
It should be

fuzzyMatch :: Eq a => [a] -> [a] -> Bool
fuzzyMatch [] _ = True
fuzzyMatch _ [] = False
fuzzyMatch (p:ps) (x:xs)
| p == x = fuzzyMatch ps xs
| otherwise = fuzzyMatch (p:ps) xs

Thanks for noticing it.

>>

 No.10193

>>10179
format ELF64
section '.text' executable

publicfuzzy_match

; extern bool fuzzy_match(const char *needle, const char *hay)
; rdi = const char *needle
; rsi = const char *hay
; rax = ret
fuzzy_match:
movecx, [rdi]
top:
moveax, [rsi]
testal, al
jeexit

incrsi
cmpcl, al
jnetop

incrdi
movecx, [rdi]
jmptop
exit:
testcl, cl
seteal
ret

>>

 No.10194

>>10193
Okay, apparently soft tabs don't work.
format ELF64
section '.text' executable

public fuzzy_match

; extern bool fuzzy_match(const char *needle, const char *hay)
; rdi = const char *needle
; rsi = const char *hay
; rax = ret
fuzzy_match:
mov ecx, [rdi]
top:
mov eax, [rsi]
test al, al
je exit

inc rsi
cmp cl, al
jne top

inc rdi
mov ecx, [rdi]
jmp top
exit:
test cl, cl
sete al
ret

>>

 No.10201

>>10179
Erlang:
fuzzy_match([], _) ->
true;
fuzzy_match(_, []) ->
false;
fuzzy_match([A|R],[A|T]) ->
fuzzy_match(R, T);
fuzzy_match(R, [_|T]) ->
fuzzy_match(R, T).

>>

 No.10206

>>10201
Man, I love how you can use a variable in two places in a pattern match in Erlang and it enforces structural equality. I really wish Haskell had that.

>>

 No.10243

File: 1444207228456.png (74.39 KB, 400x400, elixir.png) ImgOps iqdb

>>9157
Nice, nice. I'm going to be on an extended business trip for a month or so. Going to use these as ways to get more familiar with pic related.

>>

 No.10265

>>10179
In Python, done with lambdas for amusement.

1. reducing the data to consume the key:


>>> import functools
>>> fuzzy = lambda data, key: functools.reduce (lambda left, ch: "" if left == "" else left if left [0] != ch else left [1:], data, key) == ""
>>> fuzzy ("alice in wonderland", "lol")
True
>>> fuzzy ("alice in wonderland", "cider")
True
>>> fuzzy ("alice in wonderland", "lain")
False


2. reducing the key to scan the data:


>>> import functools
>>> fuzzy2 = lambda data, key: functools.reduce (lambda t, ch: t if t [1] == False else (lambda s, i: (s [i+1:], True) if i >= 0 else (s, False)) (t [0], t [0].find (ch)), key, (data, True)) [1]
>>> fuzzy2 ("alice in wonderland", "a wand")
True
>>> fuzzy2 ("alice in wonderland", "anon")
True
>>> fuzzy2 ("alice in wonderland", "lain")
False

>>

 No.10276

>>10265
you are not checking for order

>>

 No.10277

>>10179
Checking out Perl 6. It feels like overkill, but here's my solution:

sub fuzzy($chars, $string) {
return True unless $chars;
my $regex = $chars.comb(/./).join('.*');
$string ~~ /<$regex>/;
}

>>

 No.10286

>>10276
You can notice the ordered check in "left if left [0] != ch else left [1:]" in fuzzy, and in "s, i: (s [i+1:], True) ... (t [0], t [0].find (ch))" in fuzzy2. Also, even if you have trouble following the function definitions, you can still test your assertion:

>>> fuzzy ("12345", "24")
True
>>> fuzzy ("12345", "42")
False
>>> fuzzy2 ("12345", "24")
True
>>> fuzzy2 ("12345", "42")
False
>>> fuzzy ("alice in wonderland", "red")
False
>>> fuzzy2 ("alice in wonderland", "red")
False
>>> fuzzy ("alice in wonderland", "icen")
True
>>> fuzzy ("alice in wonderland", "nice")
False
>>> fuzzy2 ("alice in wonderland", "icen")
True
>>> fuzzy2 ("alice in wonderland", "nice")
False

>>

 No.10288

>>10286
Oh, I just assumed both 1 and 2 were different codes and that the first one didn't really work, based on the examples. It was not really clear.

For procastination, in Idris. I didn't know that Idris managed string differently from Haskell, that was useful in the end.

fuzzyMatch : String -> String -> Bool
fuzzyMatch s1 s2 = fuzzyMatch' (unpack s1) (unpack s2)
where
fuzzyMatch' : List Char -> List Char -> Bool
fuzzyMatch' [] _ = True
fuzzyMatch' _ [] = False
fuzzyMatch' (x::xs) (y::ys) = if x == y then fuzzyMatch' xs ys
else fuzzyMatch' (x::xs) ys

>>

 No.10297

>>10179
Some JavaScript


function fuzzy(exp, str) {
return !!str.match( new RegExp(exp.split('').join('.*')) );
}
fuzzy('ll', 'lolin'); // true

>>

 No.10384

>>9157
rollan

>>

 No.10399

>>10179
Didn't write a lot of Rust, but it looks like it works.


fn fuzzy_match (matcher: &str, text: &str) -> bool
{
let mut iter = text.chars();
for c in matcher.chars()
{
loop
{
match iter.next()
{
None => return false,
Some(tc) => if tc == c {break;}
};
}
}
true
}

>>

 No.10401

>>10179
C:
int fuzz(char* pat, char* str) {
while(*pat && *str)
if (*pat == *(str++))
pat++;
return *pat ? 0 : 1;
}

Test output:
"ll" matches with "love lain"
"lal" does not match with "love lain"
"" matches with "love lain"
"n" matches with "love lain"
"l" matches with "love lain"
"llove lain" does not match with "love lain"

>>

 No.10416

File: 1444520124512.png (289.99 KB, 900x642, 1424997310908.png) ImgOps iqdb

So Lain, I've been working through the K&R in an attempt to git gud at C. The only issue is that for some of the problems i find myself looking up the answers just to figure out how some of the soykaf is working. Is this natural? Is this a terrible habit? I feel like I understand whats going on once I see it, and most of it is just due to unfamiliarity of how the I/O system works at some points. I understand how the program works after, but is this the way I should be learning?

>>

 No.10417

>>10416
Reading code is a good thing. Give the answers a shot; if you don't think you can solve the entire problem, try just solving part of it. If you can't figure it out, reread a bit of the chapter, and if you still can't then skip to reading how they do it. Even after you get something right, looking at their code is usually good.

tl;dr don't worry about it

>>

 No.10418

>>10417
Thanks anon, polite sage since i probably should've made another thread for this.

>>

 No.10433

>>9155
How does this not work?

primes = eval(input("Enter number of prime numbers desired: "))
soykaf = 0
number = 1
factors = 0
while soykaf < primes:
for i in range(1, number+1):
if i == number:
continue
elif number/i == number//i:
factors +=1
if factors == 0:
print(number)
shit+=1
else:
factors = 0
number+=1

>>

 No.10435

>>10434
I'm so lost, I'm new to lainchan. I'm sorry, but i don't know why my code isn't displaying right and whi it's changing soykaf to soykaf

>>

 No.10437

>>10433
number/i == number//i
will always be true when i = 1, hence you will always have one factor, soykaf (there are language enhancers on this site) won't increment, infinite loop.

use modulus instead of working with floats too.

>>

 No.10438

more comments in code would be good to see.

>>

 No.10453

>>10437
I completely overlooked that infinite for loop, thanks! I was able to jjust change the range and it works now.

primes = eval(input("Enter number of prime numbers desired: "))
soykaf = 0
number = 1
factors = 0
while soykaf < primes:
for i in range(2, number+1):
if i == number:
continue
elif number/i == number//i:
factors +=1
if factors == 0:
print(number)
shit+=1
else:
factors = 0
number+=1

>>

 No.10488

File: 1444673865216.jpg (176.44 KB, 577x684, 1307927574069.jpg) ImgOps Exif iqdb

Here's another simple one for this week.
Write a function to that detects palindromes.

> What are palindromes?

A palindrome is a word or expression, that is the same spelled backwards.

Some examples:
Dr. Awkward
Gnu dung
Kayak


Try to make it, so that the function accepts all of these examples.

>>

 No.10490

>>10488

import Data.Char (toLower)

palindrome = test . filter criteria . map toLower
where criteria = flip elem $ ['a'..'z'] ++ ['0'..'9']
test xs = all (==True) $ zipWith (==) (start xs) (reverse $ end xs)
start xs = take (length xs `div` 2) xs
end xs = drop (length xs `div` 2) xs

main = (return . palindrome =<< getLine) >>= print


Not the prettiest, I feel like there's a better way to write it.

>>

 No.10491

>>10488


def p(s):
def r(s): return ''.join([i.strip(' .').lower() for i in s.split()])
return r(s) == r(s[::-1])


You could probably oneline this

>>

 No.10493

>>10488
Here's my implementation in haskell:
import Data.Char (isAlpha, toLower)

isPalindrome :: String -> Bool
isPalindrome l = let raw = map toLower . filter isAlpha $ l
in raw == reverse raw


>>10490
I'll just point out a few you could improve things, if you don't mind.

criteria would've been a little more idiomatic haskell in this form:
criterie = (`elem` ['a'..'z'] ++ ['0'..'9'])

You actualy don't have to write criteria at all, though, as it is equivalent to isAlphaNum from Data.Char.
You could replace also the all (== True) with and in test.

>>

 No.10494

>>10493
>criterie = (`elem` ['a'..'z'] ++ ['0'..'9'])
Thanks
>You could replace also the all (== True) with and in test.
And thanks, that's the function I was looking for but I couldn't remember it.

>You actualy don't have to write criteria at all, though, as it is equivalent to isAlphaNum from Data.Char.

Yeah, in this case it is, but I would want it to be an arbitrary set more generally.

>>

 No.10495

>>10488
int ispalindrome(const char *str)
{
const char *s = str, *t = str;

while (*(t++) != '\0');

--t;
while (s < t) {
if ((!isalpha(*s) && ++s) || (!isalpha(*t) && --t))
continue;
if (tolower(*s++) != tolower(*t--))
return 0;
}

return 1;
}

>>

 No.10497

>>10488
lambda reporting

>>> palindromedary = lambda t: (lambda s: s == s [::-1]) ("".join (map (str.lower, filter (str.isalpha, t))))
>>> palindromedary ("Dr. Awkward")
True
>>> palindromedary ("Gnu dung")
True
>>> palindromedary ("Kayak")
True
>>> palindromedary ("bopqod")
False
>>> palindromedary ("shush")
False
>>> palindromedary ("A Santa dog lived as a devil god at NASA.")
True

>>

 No.10506

File: 1444726335416.jpg (44.51 KB, 291x291, 1438860793432.jpg) ImgOps Exif iqdb

>>10497
that's pretty neat

>>

 No.10507


>>

 No.10512

>>10497

$ node
> function isPalindrome(s) {
... s=s.replace(/\W/g,"").toLowerCase();
... return s.split("").reverse().join("") === s;
... };
undefined
>
undefined
> isPalindrome ("Dr. Awkward")
true
> isPalindrome("Gnu dung")
true
> isPalindrome("Kayak")
true
> isPalindrome("bopqod")
false
> isPalindrome("shush")
false
> isPalindrome("A Santa dog lived as a devil god at NASA.")
true
>

Yours is cut and the task was a nice challenge actually! i could not fit mine on one line tho :'( Well actually i could but it was ugly af.

>>

 No.10513

File: 1444739113238.gif (1.91 MB, 250x360, 5517_caba.gif) ImgOps iqdb

>>10512
>cut
i meant cute

>>

 No.10618

>>9157
Rolla

>>

 No.10630


(define (findprime n)
(let ([one-to-n (foldr (lambda (x y) (cons (- (first y) x) y)) `(,n) (make-list (- n 2) 1))])
(foldr (lambda (x y) (if (empty? (filter (lambda (z) (equal? 0 (remainder x z))) (remove x one-to-n))) (cons x y) y)) empty one-to-n)))

racket solution
pretty inefficient, but hey it was a good exercise. new to funcitonal programming and all that. this is the n primes problem.

>>

 No.10631

>>9233
wow this is cool thanks.
didnt know racket was a language people actually used.

>>

 No.10649

File: 1445124810420.jpg (115.35 KB, 599x676, no_bully_pls1.jpg) ImgOps Exif iqdb

>>10631
Go skim the Racket Con schedules. Off the top of my head, I can remember Naughty Dog and some startup that generates quilt patterns using Racket.

>>

 No.10665

>>10488
Tried to do it in Rust with the functional operators. I didn't find a way however how to duplicate the iterator, so I had to do the operation twice.


fn main ()
{
let t1 = "Dr. Awkward";
let t2 = "Gnu dung";
let t3 = "Kayak";

if !palindrome(t1)
{
panic!("Dr. Awkward isn't a palindrome ?");
}

if !palindrome(t2)
{
panic!("Gnu dung isn't a palindrome ?");
}

if !palindrome(t3)
{
panic!("Kayak isn't a palindrome ?");
}
}

fn palindrome(text: &str) -> bool
{
let filtered = text.chars()
.filter_map(|c: char| if c.is_alphanumeric() {c.to_lowercase().next()} else {None});
let reversed = text.chars()
.filter_map(|c: char| if c.is_alphanumeric() {c.to_lowercase().next()} else {None}).rev();
filtered.zip(filtered.rev()).all(|(x,y)| x == y)
}

>>

 No.10667

>>10665
Why didn't you define a function that calls panic and dynamically generates the string used?
I'm seeing a lot of redundancy.

>>

 No.10692


(define (isPali lst)
(equal? (foldr (λ(x y) `(,@y ,x)) null lst) lst))


I dont know anything about strings or characters in Racket. Kinda lame, but hey, returns if the list is a palindrome.

>>

 No.10694

A little math tip to make the prime situation a bit more interesting:
Remember that all primes are odd numbers, with this said, you can make the series with the odd number definition (2n-1), and you only need to compare it to 3, 5 and 7.

>>

 No.10696

>>10694
I just realised this is stupid, I'm not writing sleepy again.

>>

 No.10716

>>10667
Inside the main ? Because I didn't care mostly.

>>

 No.10731

What tags do I use for code?

>>

 No.10732

>>10731
[code]

>>

 No.10734

>>10488

In Elixir:



defmodule Lainchan do
def anagram?(word) do
x = word |> cleanup |> String.downcase
x == String.reverse(x)
end

def cleanup(word) do
Regex.replace(~r/\W/, word, "")
end
end

>>

 No.10744

>>10734
how would you call this to test the given examples? Elixir has it's own shell environment yes? I know nothing about the language.

>>

 No.10746

>>10744
I am new to Elixir (started yesterday). This is what I did:

1. Saved file as 'lainchan.exs'

2. Open terminal in the same directory as the file, enter 'iex'—Elixir REPL.

3. Enter 'c "./lainchan.exs"', which compiles the file and adds it to the REPL

Then I just did 'Lainchan.anagram?("Dr. Awkward")'

>>

 No.10748

>>10746
got it. thanks for the thorough explanation.

>>

 No.10749

File: 1445310729973-0.epub (4.05 MB, Programming Elixir.epub)

File: 1445310729973-1.pdf (5.07 MB, Elixir_in_Action.pdf)

>>10748
If you want to learn more Elixir, check out these books. Start with Programming Elixir!

>>

 No.10750

>>10749
But the most important thing about Elixer: will I get paid to program in it?

>>

 No.10752

>>10750
If you just want money go learn Java or .NET.

Elixir is still small and new but IMO thanks to its expressiveness, easy concurrency, and Phoenix framework it will get big. But I'm learning it for fun so I don't care lol.

>>

 No.10782

>>9157
Well, here goes nothing

>>

 No.10812

Well, I hope that it displays with the format, I´m a newfag in programming and this IB

Ah, and for the j, it's just i - 1, and is in java
    public void nPrimes (int i, int j){


if (i == 1){
return;
}
if (j == 1){
//---------If it's prime
System.out.println( i);
nPrimes(i - 1, i - 2);
}
else{
if (i % j == 0){
//System.out.println(i +" Isn't prime");
//--------------------If isn't prime
nPrimes(i - 1, i - 2);
}
else
{
nPrimes(i, j - 1);
}
}


}

>>

 No.11394

>>9157
rolling for conway please

>>

 No.11707

File: 1446992794789.jpg (767.22 KB, 1300x1244, 1434766558476.jpg) ImgOps Exif iqdb

I'm finally back and came up with a fun exercise.

Write a function that can find the nth smallest element in a list.
f(3,[1, 2, 3, 4, 5, 6]) -> 3

>>

 No.11708

>>9157
Rolling.

>>

 No.11709

>>11707
(define (f n l) (list-ref (sort l <) (- n 1)))

>>

 No.11710

>>11707
So, I could've just written:
smallest :: Ord a => Int -> [a] -> a
smallest n xs = sort xs !! (n - 1)

But I wanted to do it by hand instead.
This should also run faster than the first snippet, as this one is O(n) and the first one isn't.
smallest :: Ord a => Int -> [a] -> a
smallest n xs
| n < 1 = error "n needs to be at lest 1"
| length xs < n = error $ "List need to be at least " ++ show n ++ " elements long"
| otherwise = let x = head xs in go (x, x, 1) . tail $ xs
where go (_, solution, _) [] = solution
go p@(lowerBound, current, c) (x:xs)
| current == x = go p xs
| c < n =
if current < x
then go (current, x, c + 1) xs
else go (nextLowerBound, current, c + 1) xs
| otherwise =
if current < x
then go p xs
else go (nextLowerBound, next, c) xs
where nextLowerBound = min x lowerBound
next = max x lowerBound

>>

 No.11714

>>11707

#include <vector>
#include <limits>
#include <stdexcept>
using namespace std;

double nthSmallest(unsigned int n, vector<double> numbers)
{
if (n==0) throw out_of_range("Pick a non-zero n");
else if (n>numbers.size()) throw out_of_range("Pick n smaller than vector size");
double lastValue = numeric_limits<double>::lowest();
double* toBeDiscarded = 0;
for (unsigned int i = 0; i<n; ++i)
{
double currentLow = numeric_limits<double>::max();
for (double& num : numbers)
if (num>=lastValue && num<currentLow)
{
currentLow = num;
toBeDiscarded = &num;
}
lastValue = currentLow;
*toBeDiscarded = numeric_limits<double>::lowest();
}
return lastValue;
}


oh man C++

>>

 No.11716

>>11714
Now that I think about it, I should have used numeric_limits<double>::infinity() instead. Oh well.

>>

 No.11718

A bit late, here's my attempt in Python:


# assuming we don't want to consider punctuation or whitespace chars
from string import whitespace as w
from string import punctuation as p

strip = w + p

def p(word):
alphaNum = ''.join(c for c in word if c not in strip)
alphaNum = alphaNum.lower() # caps aren't important if order flips
n = 0
while n <= (len(alphaNum) // 2):
if alphaNum[n] != alphaNum[len(alphaNum) - (n + 1)]:
return False
n += 1
return True


output:
> p('Dr. Awkward')
True
> p('Gnu dung')
True
> p('Kayak')
True
> p('not a palindrome')
False

Comments/criticism are welcome.

>>

 No.11719

>>11718
samefag, apparently the highlighting scheme here considers // to be a comment, but in python 3 it's the floor division operator.

>>

 No.11731

>>11707

learning go, this is brute force but works


package main
import "fmt"
func main(){
var n, temp int
list := [10] int {5,7,33,8,2,74,17,6,1,11}
fmt.Print("Enter a number n, in between 1-10 to find ")
fmt.Println("the nth smallest number on the list")
for _, value := range list {
fmt.Printf("%d ",value)
}
fmt.Println()
fmt.Scanf("%d", &n)
for i:=0; i < len(list); i++ {
for j:=0; j <len(list);j++ {
if list[i] < list[j] {
temp = list[i]
list[i] = list[j]
list[j] = temp
}
}
}
fmt.Printf("%d smallest number is %d\n", n, list[n-1])
}

>>

 No.11732

File: 1447032507777.jpg (30.32 KB, 530x370, 1426269851432.jpg) ImgOps Exif iqdb

>>11731
...forgot indention

>>

 No.11733

>>11732
Lainchan messes up when you indent with tabs. It's probably not your fault.

>>

 No.11737

>>11707
My attempt in C

#include <stdlib.h>
#include <stdio.h>
int min(int array[],size_t length){
int min = array[0];
for(int i=0; i < length; i++){
if(min > array[i]){
min = array[i];
}
}
return min;
}
int main(){
int test[] = {12,3,1,3,4,5,67,3,12,4,5,6,7,123,5,6,3,12,4,5,67,8,9,7,5,3,1,231,12,35,234,124,23452,2394,30,40,2,3,4,5,67,8};
printf("%d\n",min(test,(sizeof(test)/sizeof(int))));
return 0;
}

>>

 No.11739

>>11707
Python 3 solution:

def nthSmallest(nth, of):
for n in of:
while of.count(n) > 1:
of.remove(n)
of.sort()
return of[(nth - 1)]


Comments/criticism welcome.
Been drinking, pls no bully.

>>

 No.11742

>>11733
I'm fairly sure it only fuarrrks up tabs if you use the tab key, if you use spaces it works.

>>

 No.11745

>>11707
line separated

cat list | sort -un | sed -n $1p


space seperated

cat list | sed 's/ /\n/g' | sort -un | sed -n $1p

>>

 No.11759

>>11737
oops I misread the question

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
int min(int array[],size_t length,int nth){
for(;;){
bool swapped = false;
for(int i=0;i<(int)length-1;i++){
if(array[i] > array[i+1]){
printf("sorted\n");
swapped = true;
int temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}
}
if(!swapped){
return array[nth-1];
}
}
}
int main(){
int test[] = {12,3,1,3,4,5,67,3,12,4,5,6,7,123,5,6,3,12,4,5,67,8,9,7,5,3,1,231,12,35,234,124,23452,2394,30,40,2,3,4,5,67,8};
printf("%d\n",min(test,sizeof(test)/sizeof(int),3));
return 0;
}

>>

 No.11763

>>11710
Your second example failed on a test example
smallest 3 [3, 4, 5, 2, 1, 6]

which returned 2.

Can't offer a critique as I'm not sure what "go" is doing exactly.

>>

 No.11765

>>11763
Huh, that's strange. It returns 3 for me, as it should.

> Can't offer a critique as I'm not sure what "go" is doing exactly.

Yeah, it's not really clean code.
I mostly wrote it with O(n) in mind.

>>

 No.11779

>>11765
Oops, I just noticed that I tried your test with the first version of smallest.
So I made a third version, this one works as you'd expect it.
smallest' :: Ord a => Int -> [a] -> a
smallest' n xs
| n < 1 = error "n needs to be at lest 1"
| length xs < n = error $ "List need to be at least " ++ show n ++ " elements long"
| otherwise = let x = head xs in go ([], x, 1) . tail $ xs
where go (_, solution, _) [] = solution
go p@(lowerStack, current, c) (x:xs)
| current == x = go p xs
| c < n =
if current < x
then go (current:lowerStack , x , c + 1) xs
else go (insert x lowerStack, current, c + 1) xs
| otherwise =
if current < x
then go p xs
else let (next:nextLowerStack) = insert x lowerStack
in go (nextLowerStack, next, c) xs

insert x [] = [x]
insert x (y:ys)
| x == y = y:ys
| x > y = x:y:ys
| otherwise = y:insert x ys

>>

 No.11785

Sorting the entire list is wasteful, it runs in O(k log k). Keeping track of the n smallest elements suffices and runs in O(k log n), which becomes O(k) if n is fixed.

from itertools import islice
from bisect import insort_right

def nthsmallest (n, data):
if n < 1: return None
if n == 1: return min (data)

iterdata = iter (data)
cache = list (islice (iterdata, n))
if len (cache) < n: return None

cache = sorted (cache)
guard = cache [-1]

for x in iterdata:
if x < guard:
insort_right (cache, x)
del cache [-1]
guard = cache [-1]

return guard

Testing:

>>> nthsmallest (3, [3, 4, 5, 2, 1, 6])
3
>>> nthsmallest (3, 'nthsmallest')
'h'

However, this actually comes for free in heapq:

>>> import heapq
>>> nthsmallest = lambda n, data: heapq.nsmallest (n, data) [-1]
>>> nthsmallest (3, 'nthsmallest')
'h'
>>> nthsmallest (3, [3, 4, 5, 2, 1, 6])
3

except that heapq uses different fallback semantics.

>>

 No.11793

>>11785
interesting!

>>

 No.11843

so I'm pretty new to programming and I'm using java. so I made two versions of the primes>n challenge
one using
 
if(i%x==0){
not a prime
}


and another using an array list to store each prime and just checking numbers in the array

 
if(i%array.get(x)==0){
not a prime
}

the problem is it second one which I would have thought would be way faster is super slow I checked them up to n=500,000 the first one took about 40s and I stopped the second one after a minuet at ±50,000. I'm currently doing an over night tests up to 100,000,000 to see if it balances out but is there a better way I should have done it?

>>

 No.11861

>>11843
Could you maybe make pastes of both of the versions and link them here?
Chances are, the ArrayList isn't causing the slowdown, but some little mistake.

>>

 No.11887

>>11861
this http://pastebin.com/abQf5Hin is the one using i%x

this http://pastebin.com/LXYbGB6U is the one using the array list

>>

 No.11889

>>11887
The only thing I can think of causing that long wait is the for-loop.
Because you're comparing to primes.indexOf(last) and using the .get() method every iteration of the for-loop, which will take quite some time.
A better way would be to use the iterator syntactic sugar offered by ArrayList:
for(long prime : primes) {
if(i % x == 0) {
print = false;
break;
}
else {
print = true;
}
}

>>

 No.11890

>>11889
Oops, should be
for(long x : primes) {

>>

 No.11891

>>11890
>>11889
thanks that's fixed it right up

>>

 No.12098

File: 1447866559535.png (1.07 MB, 3840x2160, 1443785809023.png) ImgOps iqdb

giving this thread CPR in the form of the extended challenge sheet

>>

 No.12209

>>12098
Towers of Hanoi with 3 poles, in Perl 6:

sub hanoi(Int $n where $n>=0) {
sub formatted(@pos) {
my @conv;
{my @empty; @conv[$_] = @empty;} for 0..2;
@conv[@pos[$_]].push($_) for 0..$n-1;
gather for 0..2 -> $i {
take " ";
for 0..$n-1 -> $j {
if ($j < @conv[$i].elems) {
take ~@conv[$i][$j];
} else {
take " ";
}
}
take " |";
}.join("");
}
my @positions; @positions[$_-1] = 0 for 1..$n;
my @pows; @pows[$_] = 2**$_ for 0..$n;
for 0..2**$n-1 -> $t {
for 0..$n-1 -> $p {
@positions[$p] = (@positions[$p]-2*($p%2)+1)%3 if ($t-@pows[$p])%@pows[$p+1]==0;
}
say formatted(@positions);
}
}

The formatted(@pos) function is not necessary, but makes the output easier to check.
Output for 3 rings:

012 | | |
12 | 0 | |
2 | 0 | 1 |
2 | | 01 |
| 2 | 01 |
0 | 2 | 1 |
0 | 12 | |
| 012 | |

>>

 No.12232


>>

 No.12329

>>12098
Draw a circle using ASCII, in C++:

#include <fstream>
#include <string>
#include <cmath>

using namespace std;

void writeCircle(double r, char outside, char border, char inside)
{
ofstream out("circle.txt");
size_t rAbs = size_t(round(abs(r))),
diameter = 2*rAbs;
for (size_t i = 0; i<=diameter; ++i)
{
string circleLine;
for (size_t j = 0; j<=diameter; ++j)
{
double iDiff = double(i)-r,
jDiff = double(j)-r;
size_t ijRad = size_t(round(sqrt(iDiff*iDiff+jDiff*jDiff)));
circleLine.push_back(
(ijRad>r) ? outside :
(ijRad<r) ? inside :
border
);
}
out<<circleLine<<endl;
}
}


Output for writeCircle(5,'_','X','/'):

___XXXXX___
__X/////X__
_X///////X_
X/////////X
X/////////X
X/////////X
X/////////X
X/////////X
_X///////X_
__X/////X__
___XXXXX___

>>

 No.12434

>>9157
rolling

>>

 No.12452

>>9157
rollan

>>

 No.12453

File: 1449004051770.gif (1022.27 KB, 500x271, 1439409781080-0.gif) ImgOps iqdb

>>9157
I'm not gonna get something easy, am I?

>>

 No.12458

Dice rollRolled 5689 - 201

all of the newfriends ITT should see >>9776 for dice rolling help on this very slow board.

>>

 No.12459

>>12458
as should I it seems.



Delete Post [ ]
[ cyb / tech / λ / layer ] [ zzz / drg / lit / diy / art ] [ w / rpg / r ] [ q ] [ / ] [ popular / ???? / rules / radio / $$ / news ] [ volafile / uboa / sushi / LainTV / lewd ]