[ 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[View All]

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.
190 posts and 18 image replies omitted. Click reply to view.
>>

 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 ]