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

Daily programming challange

This is a blue board which means that it's for everybody (Safe For Work content only). If you see any adult content, please report it.

Thread replies: 73
Thread images: 11

File: mx37.jpg (354KB, 886x1311px) Image search: [Google]
mx37.jpg
354KB, 886x1311px
Previously >>58894045

Write a function that generates Pascal's triangle.

$ main 3

should output
  1
1 1
1 2 1



$ main 5

should output
    1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
>>
https://runelm.io/c/5sc
>>
>>58934777
There aren't any spaces, m8. And you were so close...
>>
Am I a 3 star programmer yet?

void pascals_triangle(int iters)
{
iters += 1; /* 1 indexing */
unsigned i, j;
unsigned **arr = (unsigned **) malloc(iters * sizeof(unsigned *));
for (i = 0; i < iters; i++)
arr[i] = (unsigned *) calloc(iters, sizeof(unsigned));
**arr = 1; /* seed */
for (i = 1; i < iters; i++)
{
memcpy(arr[i], arr[i - 1], sizeof(unsigned) * iters);
for (j = 1; j < i; j++) /* add */
arr[i][j] = arr[i-1][j-1] + arr[i-1][j];

unsigned k = iters - i; /* pretty print */
while (k--)
printf("%c", ' ');
for (j = 0; j < iters; j++)
printf((!arr[i][j]) ? " " : "%u ", arr[i][j]);
printf("\n");
}
for (i = 0; i < iters; i++)
free(arr[i]);
free(arr);
}
>>
fac :: Int -> Int
fac n = product [1..n]

ncr :: Int -> Int -> Int
ncr n k = fac n `div` (fac k * fac (n - k))

zfill :: Int -> String -> String
zfill n s = concat $ replicate (n - length s) " " ++ [s]

pascalrow :: Int -> String
pascalrow n = unwords [zfill 2 $ show $ ncr n i | i <- [0..n]]

pascaltriangle :: Int -> String
pascaltriangle n = unlines [concat $ replicate (n-k) " " ++ [pascalrow k] | k <- [0..n]]

main :: IO()
main = do
print "N: "
n <- getLine
putStrLn $ pascaltriangle (read n::Int)


pascal
"N: "
6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
>>
>>58934460
function main(var: integer): integer;
begin
if (var == 3) then
writeln(" 1\n 1 1\n1 2 1");
else
writeln(" 1\n 1 1\n 1 2 1\n 1 3 3 1\n1 4 6 4 1");
end;
end


if i remember pascal correctly, function outputs right data for 3 and for 5
i wonder if you can write pascal's triangle in non-pascal language
>>
>>58935308
lol no. It's just unnecessary. You get true 3 stars when you start doing stuff to strings.
also fuck this captcha
>>
>>58934460
On the phone, untested

triangle :: Int -> [[Int]]
triangle 0 = [repeat 0]
triangle n =
let (r:rs) = triangle (n-1)
in zipWith (+) r (0:r) : r : rs

renderLines :: [[Int]] -> [String]
renderLines = map renderLine . zip [0..]
where
renderLine (i, r) = replicate i ' ' <> intercalate " " (takeWhile (/=0) $ dropWhile (==0) r)

printLines :: [String] -> IO ()
printLines [] = return ()
printLines (l:ls) = do
printLines ls
putStrLn l

main :: IO ()
main = printLines . renderLines . triangle <=< readLn
>>
>>58936859
Yep, missing a show and <=< should be =<<
>>
>>58935308
What a disgusting language
>>
Where are those ultra functional hasklel fags? I'm missing them.
>>
>>58936210
>i wonder if you can write pascal's triangle in non-pascal language
OH FOR FUCKS SAKE ANON
>>
>>58938036
>t. CSS engineer
>>
File: 1472387387923.png (4KB, 203x123px) Image search: [Google]
1472387387923.png
4KB, 203x123px
any ideas on how to make it not fuck up past the single digit?
>>
>>58939194
Ok, I have an idea.

Your program should ask for the height of the tree, or how many levels to print. If the level is >5, print one space on the left side of each single digit number and no space for double digit. if >9, print two spaces on left of single digit, one space on left of double digit, and no space on left of triple digit.
>>
Somehow printing turned out to be more complicated than generating the triangle.
(import (ice-9 poe) (srfi srfi-26))

(define (pascals-triangle n)
(define (middle-subrow prev)
(if (or (null? prev) (null? (cdr prev)))
'()
(cons (+ (car prev) (cadr prev)) (middle-sum (cdr prev)))))
(define (row n)
(case n
((0) '(1))
(else `(1 ,@(middle-subrow (row (- n 1))) 1))))
(map (pure-funcq row) (iota n)))

(define (print-pascals-triangle triangle)
(define (string-center str width)
(let ((padding (quotient (- width (string-length str)) 2)))
(string-append (make-string padding #\ ) str)))
(define (show-row row)
(string-join (map number->string row)))
(define (print-row row width)
(format #t "~A\n" (string-center (show-row row) width)))
(let ((last-row-len (string-length (show-row (car (reverse triangle))))))
(for-each (cute print-row <> last-row-len) triangle)))

(print-pascals-triangle (pascals-triangle (read)))
>>
>>58939240
whoops, meant right hand side not left hand side.
>>
>>58939194
Your pyramid stops being centered after the numbers become >1digit.
You should put more spaces on the upper layers.
>>
>>58939241
Fixed a typo and converted 'case' to 'if'.
(import (ice-9 poe) (srfi srfi-26))

(define (pascals-triangle n)
(define (middle-subrow prev)
(if (or (null? prev) (null? (cdr prev)))
'()
(cons (+ (car prev) (cadr prev)) (middle-subrow (cdr prev)))))
(define (row n)
(if (= n 0) '(1) `(1 ,@(middle-subrow (row (- n 1))) 1)))
(map (pure-funcq row) (iota n)))

(define (print-pascals-triangle triangle)
(define (string-center str width)
(let ((padding (quotient (- width (string-length str)) 2)))
(string-append (make-string padding #\ ) str)))
(define (show-row row)
(string-join (map number->string row)))
(define (print-row row width)
(format #t "~A\n" (string-center (show-row row) width)))
(let ((last-row-len (string-length (show-row (car (reverse triangle))))))
(for-each (cute print-row <> last-row-len) triangle)))

(print-pascals-triangle (pascals-triangle (read)))
>>
>>58939194
While building the list of numbers (assuming you're doing that), keep track of the max length of the number. Make sure any time you print a number it takes up at least that number in length.

>>58939240
That isn't very generic. You'd have to program in every level where the length changes or mathematically derive the generic solution.

Of course if you don't want to store the numbers beyond a row or two (I'm unsure how this pyramid is constructed, I haven't done it myself), you'd need that generic solution.
>>
File: 1458691237294.png (46KB, 1200x1000px) Image search: [Google]
1458691237294.png
46KB, 1200x1000px
>>58939339
>>While building the list of numbers (assuming you're doing that), keep track of the max length of the number. Make sure any time you print a number it takes up at least that number in length.
I'll go with that, thanks.
>>
>>58939194

Calculate out the length of each string printed, without whitespace padding, before doing any printing. Use the length of line n+1 to figure out how much whitespace will be needed for line n.
>>
>>58939518
more like get the longest string in the set and then add whitespace to every string until they're all thes same
>>
its late. im tired. solution suffers from the same problem mentioned earlier in thread. I'll probably fix it later.

<?php

function givePascal($input) {
$rows[0][] = 1;

for ($i = 1; $i < $input; $i++) {
$rows[$i][] = 1;
foreach ($rows[$i - 1] as $key => $numbers) {
if ($key !== 0 || $key + 1 !== $i) {
$rows[$i][$key + 1] = $rows[$i - 1][$key] + ($rows[$i - 1][$key + 1] ?? 0);
}
}
$rows[$i][$i] = 1;
}
return $rows;
}

function printPascal($pascal) {
$triangle = '';
foreach ($pascal as $key => $row) {
if (next($pascal)) {
$length = count($pascal[(count($pascal) - 1) - $key]) - 1;
$triangle .= str_repeat(' ', $length) . implode(' ', $row) . PHP_EOL;
} else {
$triangle .= implode(' ', $row);
}
}
return $triangle;
}

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
>>
>>58939241
>(((lisp)))
>>
>>58934777
>>58935023
Ok, fixed it now.
I even made it interactive, just for fun:
https://runelm.io/c/c58
>>
>>58942881
Ok, you win.
>>
File: poop.png (17KB, 838x492px) Image search: [Google]
poop.png
17KB, 838x492px
>>58934460
@echo off
setlocal enabledelayedexpansion
cls


echo.
set row=15
call :trungal
echo.
pause
exit /b 0


:trungal
set /a prev=%row%-1


for /l %%I in (0,1,%prev%) do (


set c=1&set r=


for /l %%K in (0,1,%row%) do (


if not !c!==0 (


call :numstr !c!



set r=!r!!space!!c!


)
set /a c=!c!*^(%%I-%%K^)/^(%%K+1^)


)
echo !r!
)
goto :EOF


:numstr
set cnt=0&set proc=%1&set space=
:loop


set currchar=!proc:~%cnt%,1!
if not "!currchar!"=="" set /a cnt+=1&goto loop


set /a numspaces=5-!cnt!
for /l %%A in (1,1,%numspaces%) do set "space=!space! "


goto :EOF
>>
>>58944495
nice

but

do you


like

really need


all that whitespace?
>>
>>58944495

>Batch
>Not Powershell
REEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
>>
>>58944897
powershell is awful
>>
>>58945510

Batch is worse. If you need a shell scripting language in Windows, Powershell should be preferred over Batch every time.
>>
>>58945555
both are awful in comparison to a real shell.
>>
>>58934460
var pascalTriangle = function(num) {
if (num == 3) {
console.log(
" 1
1 1
1 2 1");
}
else if (num == 5) {
console.log(
" 1
1 1
1 2 1
1 3 3 1
1 4 6 4 1");
}
};


RATE MY CODE GEE
>>
>>58945591
your joke was done 17 hours ago.
>>58936210
>>
>>58945555
I am desperately in need of help. I have xml payloads in a clob in a db2 database. I need the entire payload, not any single bit of info from the thing. Is there some easy way for be to extract the entire thing in the format it went in using jdbc?
>>
You are all like little babies.
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings; use Ada.Strings;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Command_Line;

procedure Pascal is
type Line is array (1..Integer'Value(Ada.Command_Line.Argument(1))) of Natural;
X : array(1..Integer'Value(Ada.Command_Line.Argument(1))) of Line := (others=>(others=>0));
begin -- Pascal
X(Line'First)(Line'First) := 1;
for I in X'First .. X'Last-1 loop
for J in X(I)'Range loop
if J = Line'First then
X(I+1)(J) := X(I)(J);
elsif J = Line'Last then
X(I+1)(J) := X(I)(J-1);
else
X(I+1)(J) := X(I)(J) + X(I)(J-1);
end if;
end loop;
end loop;

declare
Mini_String : String(1 .. Integer'Image(X(Line'Last)(Line'Last/2))'Length) := (others=>' ');
S : String(1 .. Mini_String'Length * Line'Length) := (others=>' ');
Temp : Unbounded_String := To_Unbounded_String("");
begin
for I in X'Range loop
for J in X(I)'Range loop
if X(I)(J) /= 0 then
Mini_String := (others=>' ');
Move(Integer'Image(X(I)(J)), Mini_String, Justify=>Center);
Append(Temp, Mini_String);
end if;
end loop;
Move(To_String(Temp), S, Justify=>Center);
Put_Line(S);
S := (others=>' ');
Temp := To_Unbounded_String("");
end loop;
end;
end Pascal;
>>
> no pascal Pascal's Triangle
>>
>>58947854
Be the change you want to see in the thread.
>>
>>58934460
#include <stdio.h>

int function(int level, int pos){
if(pos==1||pos==level){
return 1;
} else{
return function(level-1, pos-1)+function(level-1,pos);
}
}

int main(int argc, char *argv[]){
for(int i = 1; i<=argv[1]; i++){
for(int e = 1; e<=i; e++){
printf("%d", function(i, e));
}
printf("\n");
}
}

//not tested as it was written on the phone but it works
>>
>>58950069
ups, should be atoi(argv[1]) instead of argv[1] in the for.
>>
>>58946867
Based, how can anyone hope to compete?
>>
>>58950069
Dumb phone poster
>>
would you guys consider this 'centered' or do the numbers themselves need to be centered as possible?

                                           1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
>>
System.exit(-1);
>>
>>58950069
>not counting from 0
you have been disqualified
>>
>>58953673
>>58955434
Why are you bumping me? I was going to make a new thread
>>
>>58939339
Thanks for the feedback anon
>>
>>58955444
this way, I can prevent you from making new threads
>>
>>58955457
Keep trying anon :)
>>
s._Ctor and should return true
});

var keys.length; i++) {
};
vm
}
}

altKey, prop.value
}
function tagName: 'keep-alive = true;
return
}
}
var newStartVnode(oldVnode, oldVnodeQueue, parentElm: parentVal.call(vm, 'create(null);


_assetTimeout(noop);
} else {
return output[methods =
strats[hookKey] = hook = {
} function () {};
} else {
vm._event.capture = getter = key.'
hydrating)
};Vue$2.config.mustUseProp: no,
var check failed from = children;

var isAndroid: isAndroid: isAndroid = UA && /msie|trident/.test(path)) {
var lower = globalValue, '__ob__) { return map[val]; }
render(i + 1, 0, l = argument = hash[key] = val.__ob__') && vnode.isStationObserver';
var i = 0, l = keys.length; i++) {
config.isReservedTag = function (hook) {

pruneCacheEntry(this.sync = true,
callback') {
} else if (expectedType._b = function (
options);
renderMixin(Vue$2.prototype.observer = false
}
subVue.prototype.toString(Ctor) {
var globalKeys = Object.creation (name in oldAttrs = listeners = options.abstractPropDefaultSlot.push(c);
if (v instance.app = new _Set = Super;
cloned
vnode, text) {
callbackId.toStringify(data, context
);
}
this.value;
documents[ len ]; output
}
if (opts.propsData, vm));
}
}function Vue$2) {
if (!ob) {
'makeMap(
vm.$el) {
);
}

var hyphenateRE, '$1-$2')
}
vm
) {
process.env.NODE_ENV !== 'productions = vm.$el) {
}


include (
>>
bump because I might want to try this later today
>>
>>58957838
have you tried it yet?
>>
>>58955444
Maybe don't have typos in the title next time
>>
import std.stdio;
import std.conv;

void main(string[] args)
{
uint rows;
uint[][] pascal;

rows = to!uint(args[1]);

pascal = new uint[][rows];
pascal[0] = new uint[1];
pascal[0][0] = 1;

foreach(int i; 1 .. rows)
{
uint rowLen = i + 1;

pascal[i] = new uint[rowLen];

pascal[i][0] = pascal[i][rowLen - 1] = 1;

foreach(int j; 1 .. rowLen - 1)
{
pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
}
}

int spaces = (rows * 2 - 1) * 3;

foreach(uint[] a; pascal)
{
foreach(i; 0 .. spaces)
{
write(" ");
}
writefln("%(%5s %)", a);
spaces -= 3;
}
}


20 is the best I get before it starts looking all wonky
>>
#!/bin/bash
firefox "http://m.wolframalpha.com/input/?i=$1+rows+of+Pascal%27s+triangle&x=0&y=0"
>>
>>58959259
I'm trying to make it go to row 2^16 with < 128k memory
don't ask why.
anyways it's not easy
>>
>>58960556
What are you using that won't overflow that far down?
>>
>>58960636
512000-bit integers
>>
>>58960272
>#!/bin/bash
just use #!/bin/sh your fucking retard
>>
>>58947854
This should be /g/'s equivalent of the tri force.
>>
>>58939194
Use something like "%3d" in the printf format string.
>>
>>58961869
That doesn't scale with the inputs anon.
>>
File: Screenshot_20170215_150719-1.png (19KB, 598x556px) Image search: [Google]
Screenshot_20170215_150719-1.png
19KB, 598x556px
Roast me.

import java.util.*;

public class PascalChallenge {
public static void main (String[] args) {
System.out.println("This program does not scale beyond 5 levels, sorry for being a Java pleb.");
System.out.println();
for (int i = 1; i <= 5; i++) {
System.out.println("Level " + i + ":");
System.out.println();
execute(i);
System.out.println();
}
}

public static void execute (int levels) {
Queue<int[]> pattern = generateLevelQueue(levels);
printPattern(pattern, levels);
}

public static Queue<int[]> generateLevelQueue (int levels) {
Queue<int[]> out = new LinkedList<int[]>();
int[] previous = new int[]{1};
out.add(previous);
for (int currentLevel = 1; currentLevel < levels; currentLevel++) {
int[] pattern = generateLevel(currentLevel, previous);
previous = pattern;
out.add(previous);
}
return out;
}

public static int[] generateLevel (int level, int[] above) {
int[] out = new int[level + 1];
out[0] = 1;
int index = 1;
while (above.length > 1 && index < level) {
out[index] = above[index - 1] + above[index];
index++;
}
out[level] = 1;
return out;
}

public static void printPattern (Queue<int[]> patterns, int levels) {
int currentLevel = 0;
while (!patterns.isEmpty()) {
for (int i = currentLevel; i < levels - 1; i++) {
System.out.print(" ");
}
int[] thisLevel = patterns.remove();
for (int i = 0; i < thisLevel.length; i++) {
System.out.print(thisLevel[i] + " ");
}
System.out.println();
currentLevel++;
}
}
}
>>
>>58963323
>java
you already roasted yourself.
>>
>>58963323
But does it scale past 1 character
>>
File: Screenshot_20170215_153450-1.png (18KB, 598x643px) Image search: [Google]
Screenshot_20170215_153450-1.png
18KB, 598x643px
>>58963595
I get the right numbers, but not the right spacing.
>>
>>58963646
Rewrite it
>>
File: 1392836986341.jpg (32KB, 500x375px) Image search: [Google]
1392836986341.jpg
32KB, 500x375px
Post a image to best represent a language, I will start.

>Haskell
>>
File: 1386985797693.jpg (208KB, 1520x1080px) Image search: [Google]
1386985797693.jpg
208KB, 1520x1080px
>>58963702
Lisp
>>
File: shit.png (48KB, 393x437px) Image search: [Google]
shit.png
48KB, 393x437px
>JS
>>
File: soldering-electronics.jpg (74KB, 1000x699px) Image search: [Google]
soldering-electronics.jpg
74KB, 1000x699px
>>58963702
>C
>>
>>58938036
t. pajeet
Thread posts: 73
Thread images: 11


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

I'm aware that Imgur.com will stop allowing adult images since 15th of May. I'm taking actions to backup as much data as possible.
Read more on this topic here - https://archived.moe/talk/thread/1694/


If you need a post removed click on it's [Report] button and follow the instruction.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com.
If you like this website please support us by donating with Bitcoins at 16mKtbZiwW52BLkibtCr8jUg2KVUMTxVQ5
All trademarks and copyrights on this page are owned by their respective parties.
Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
This is a 4chan archive - all of the content originated from that site.
This means that RandomArchive shows their content, archived.
If you need information for a Poster - contact them.