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

Quick, make a program that outputs an "ASCII art" cross

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: 235
Thread images: 40

File: maxresdefault.jpg (63KB, 1092x720px) Image search: [Google]
maxresdefault.jpg
63KB, 1092x720px
Quick, make a program that outputs an "ASCII art" cross of asterisks in your favourite language!
>>
>>61436178

---
org 0x7c00
bits 16

jmp 0x0000:fix_cs
fix_cs:
cli
xor ax, ax
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x7bf0
sti

mov si, cross
call print

jmp $

print:
push ax
push si
mov ah, 0x0e
.loop:
lodsb
test al, al
jz .done
int 0x10
jmp .loop
.done:
pop si
pop ax
ret

cross:
db '* *', 0x0d, 0x0a
db ' * * ', 0x0d, 0x0a
db ' * ', 0x0d, 0x0a
db ' * * ', 0x0d, 0x0a
db '* *', 0x0d, 0x0a, 0x00

times 510-($-$$) db 0
dw 0xaa55
---
>>
>>61436178
Eh I have already done this months ago...
"http://workplace.stackexchange.com/questions/39004/which-weak-algorithmic-strategies-i-have-that-lead-me-to-failing-coding-this-sim"
def drawX(n):
output = ""
for x in range(0,n):
line = list(n*' ')
line[x] = '*'
line[n-1-x] = '*'
output+="".join(line)
if x!=n-1:
output+= "\n"
return output
>>
>>61436283
v2

---
org 0x7c00
bits 16

jmp 0x0000:fix_cs
fix_cs:
cli
xor ax, ax
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x7bf0
sti

mov si, cross
call print

jmp $

print:
push ax
push si
mov ah, 0x0e
.loop:
lodsb
test al, al
jz .done
int 0x10
jmp .loop
.done:
pop si
pop ax
ret

cross:
db '*', 0x20, 0x20, 0x20, '*', 0x0d, 0x0a
db 0x20, '*', 0x20, '*', 0x20, 0x0d, 0x0a
db 0x20, 0x20, '*', 0x20, 0x20, 0x0d, 0x0a
db 0x20, '*', 0x20, '*', 0x20, 0x0d, 0x0a
db '*', 0x20, 0x20, 0x20, '*', 0x0d, 0x0a

times 510-($-$$) db 0
dw 0xaa55
---
>>
#include <stddef.h>
#include <stdio.h>

#define spc(x, xs, c) \
((x) % (xs) == 0 ? (c) : ' ')

#define ch(m, i, c) \
(*((m) + (i)) != 0 ? (c) : ' ')

#define pc(c) putchar(c)


void character(size_t xw, size_t xl, size_t space, char c, const int* matrix)
{
size_t x;

for (x = 0; x < xw; ++x)
pc(spc(x, space, ch(matrix, 0, c)));

for (; x < xl; ++x)
pc(spc(x, space, ch(matrix, 1, c)));

for (; x < xl + xw; ++x)
pc(spc(x, space, ch(matrix, 2, c)));

for (; x < xl * 2; ++x)
pc(spc(x, space, ch(matrix, 3, c)));

for (; x < xl * 2 + xw; ++x)
pc(spc(x, space, ch(matrix, 4, c)));
}


void line(size_t xw, size_t xl, size_t space, const char* str, const int* matrix)
{
size_t x;

while (1) {
character(xw, xl, space, *str++, matrix);

if (*str == '\0')
break;

for (x = 0; x < space; ++x)
pc(' ');
}

pc('\n');
}


void draw(size_t size, size_t thick, size_t space, const char* str)
{
int matrix[] = {
1, 0, 1, 1, 1,
1, 0, 1, 0, 0,
1, 1, 1, 1, 1,
0, 0, 1, 0, 1,
1, 1, 1, 0, 1
};

size_t xw = thick * space;
size_t xl = size * space;
size_t yw = thick;
size_t yl = size;
size_t y;

for (y = 0; y < yw; ++y)
line(xw, xl, space, str, matrix);

for (; y < yl; ++y)
line(xw, xl, space, str, matrix + 5);

for (; y < yl + yw; ++y)
line(xw, xl, space, str, matrix + 10);

for (; y < yl * 2; ++y)
line(xw, xl, space, str, matrix + 15);

for (; y < yl * 2 + yw; ++y)
line(xw, xl, space, str, matrix + 20);
}


int main()
{
draw(3, 2, 2, "*");
return 0;
}
>>
File: bleh.jpg (109KB, 1580x591px) Image search: [Google]
bleh.jpg
109KB, 1580x591px
Only works properly for odd inputs but idgaf
>>
First attempt
#include <iostream>
#include <cmath>
#include <string>

using namespace std;


void starCross(int n) {
float half = (float)n * 0.5;

for (int i = 1; i <= floor(half); i++) {
for (int j = 1; j < i; j++) {
cout << " ";
}
cout << "*";

for (int j = 1; j < (n + 1) - 2*i; j++) {
cout << " ";
}
cout << "*" << endl;
}


if (n % 2 == 1) {
for (int i = 0; i < floor(half); i++) {
cout << " ";
}
cout << "*" << endl;
}


for (int i = floor(half); i >= 1; i--) {
for (int j = 1; j < i; j++) {
cout << " ";
}
cout << "*";
for (int j = 1; j < (n + 1) - 2*i; j++) {
cout << " ";
}
cout << "*\n";
}
}


int main(int argc, char** argv) {
if (argc < 2) {
cout << "Please supply a size for the cross." << endl;
return 1;
}

int size = stoi(argv[1]);
starCross(size);

return 0;
}
>>
>>61436361
Not what was asked

plus it's not even angled correctly
>>
File: Yume25.jpg (68KB, 956x720px) Image search: [Google]
Yume25.jpg
68KB, 956x720px
>>61436178
[CODE]
PROGRAM DRAWTHING
IMPLICIT NONE
CHARACTER(LEN=1), PARAMETER :: SYMBOL="#"
CHARACTER(LEN=1), PARAMETER :: PADDING=" "
CHARACTER(LEN=1), DIMENSION(:,:), ALLOCATABLE :: THINGY
CHARACTER(LEN=30) :: FMT
INTEGER :: XSIZE,I
WRITE(*,"(A15)") "SIZE OF THINGY:"
READ(*,*) XSIZE
ALLOCATE(THINGY(XSIZE,XSIZE))
THINGY=PADDING
FORALL(I=1:XSIZE); THINGY(I,I)=SYMBOL; THINGY(XSIZE-I+1,I)=SYMBOL; ENDFORALL
WRITE(FMT,"('('I0'('I0,'A/))')") XSIZE,XSIZE
WRITE(*,FMT) THINGY
DEALLOCATE(THINGY)
ENDPROGRAM DRAWTHING
[/CODE]
>>
>>61436587
oh ok
PROGRAM DRAWTHING
IMPLICIT NONE
CHARACTER(LEN=1), PARAMETER :: SYMBOL="#"
CHARACTER(LEN=1), PARAMETER :: PADDING=" "
CHARACTER(LEN=1), DIMENSION(:,:), ALLOCATABLE :: THINGY
CHARACTER(LEN=30) :: FMT
INTEGER :: XSIZE,I
WRITE(*,"(A15)") "SIZE OF THINGY:"
READ(*,*) XSIZE
ALLOCATE(THINGY(XSIZE,XSIZE))
THINGY=PADDING
FORALL(I=1:XSIZE); THINGY(I,I)=SYMBOL; THINGY(XSIZE-I+1,I)=SYMBOL; ENDFORALL
WRITE(FMT,"('('I0'('I0,'A/))')") XSIZE,XSIZE
WRITE(*,FMT) THINGY
DEALLOCATE(THINGY)
ENDPROGRAM DRAWTHING
>>
File: 1311939629801.jpg (49KB, 192x174px) Image search: [Google]
1311939629801.jpg
49KB, 192x174px
>>61436603
>>
>>61436603
what lang is dis
>>
>>61436654
fortran
>>
i had one but i fucked up
>>
>>61436798
what do you mean
>>
genx = function(xx){
for(v=0;v<(xx);v++){
row=""
for(h=0;h<(xx);h++){
if(h==v||h==xx-v){row+="x"}
if(h!=v){row+=" "}
}
print(row)
}
}
genx(10)

>x
> x x
> x x
> x x
> x x
> x
> x x
> x x
> x x
> x x

Somethings wrong but whatever
>>
>>61436964
tsk tsk
>>
This is really basic geometry. You've got a line that goes up linearly with a slop of one and a normal line to it that we want to intersect at the [(n-1)/2,(n-1)/2] point.

So y - (n-1)/2 = -(x-(n-1)/2)

Solving for y we get the other equation as y = n-1-x

#include <stdio.h>

int main() {
int size;
scanf("%d",&size);

for(int y = .5;y<size;y++) {
for(int x = .5;x<size;x++)
if(y == x || y == size-x-1)
putchar('*');
else putchar(' ');
putchar('\n');

}
return 0;
}
>>
>>61436178
(defn print-cross [a]
(let [x (range a) y (dec a)]
(doseq [row x col x]
(print (if (or (= col row) (= col (- y row))) "*" " ")
(if (= y col) "\n" "")))))
(print-cross 10)
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
=> nil
(print-cross 9)
* *
* *
* *
* *
*
* *
* *
* *
* *

For brainlets: This is a list comprehension in clojure. May be even shorter, but fuck it, I'm supposed to work now
>>
>>61436178
lol whats an asskey xD
>>
>>61436283
You're going to continue to post in threads without using code tags?
>>
My code is awful :<
>>
>>61436178
Quick and dirty.
#!/bin/sh

char='*'
frst=1
scnd=$1

for line in `seq $1`; do
for col in `seq $1`; do
if [ $col -eq $frst ]; then
echo -n "$char"
elif [ $col -eq $scnd ]; then
echo -n "$char"
else
echo -n ' '
fi
done
echo
(( frst += 1 ))
(( scnd -= 1 ))
done
>>
import strutils

let size = stdin.readLine.parseInt

for i in 1..size:
for j in 1..size:
if i == j or i - 1 == size - j: stdout.write '*'
else: stdout.write ' '
echo ""
>>
>>61437668
Yes.
>>
>>61436361
18/88
>>
File: graduate.png (233KB, 2104x2064px) Image search: [Google]
graduate.png
233KB, 2104x2064px
print '*     *'
print ' * * '
print ' * * '
print ' * '
print ' * * '
print ' * * '
print '* *'
>>
>>61438196
v1.0 when?
>>
File: c.png (77KB, 1200x1276px) Image search: [Google]
c.png
77KB, 1200x1276px
>>61436178
C
#include <stdio.h>

#define N 5
#define WALL '*'
#define HOLE ' '

int main(void) {
for (int y = N - 1; y >= 0; --y) {
for (int x = 0; x < N; ++x) {
putchar(x == y || x == (N - y - 1) ? WALL : HOLE);
}
putchar('\n');
}
}
>>
File: lua.png (72KB, 1200x1200px) Image search: [Google]
lua.png
72KB, 1200x1200px
>>61441368
#!/usr/bin/env lua5.3

local N = 5
local WALL = '*'
local HOLE = ' '

local s = {}
for y = N, 1, -1 do
for x = 1, N do
if x == y or x == N - y + 1 then
s[#s + 1] = WALL
else
s[#s + 1] = HOLE
end
end
s[#s + 1] = '\n'
end
print(table.concat(s, "", 1, #s - 1))

Lua
>>
File: python.png (8KB, 512x512px) Image search: [Google]
python.png
8KB, 512x512px
>>61441477
Python
#!/usr/bin/env python3

N = 5
WALL = '*'
HOLE = ' '

for y in range(N - 1, -1, -1):
for x in range(N):
print(WALL if x == y or x == (N - y - 1) else HOLE, end='')
print()
>>
>>61436178
>>61441368
>>61441477
>>61441569

Also, for stuff like this please use my thread >>61435322

I can do stuff in C, Python and Lua.
>>
 printf "  *  \n  *  \n*****\n  *  \n  *  \n" | cowsay -n
>>
>>61436619
I can't understand the reference, what does Wikipedia founder has to do with FORTRAN?
>>61436674
Are you a scientist anon?
>>
>>61441820
Forgot I uninstalled that useless shit.
The program 'cowsay' is currently not installed. You can install it by typing:
sudo apt install cowsay
>>
>>61441826
noo
at least not yet
>>
>>61441848
>>
File: 1496766092936.jpg (15KB, 291x326px) Image search: [Google]
1496766092936.jpg
15KB, 291x326px
>>61441104
absolute madman
>>
>>61436654
Autism
>>
>>61437786
Use the ISE lol
>>
File: 34534545.jpg (28KB, 163x429px) Image search: [Google]
34534545.jpg
28KB, 163x429px
>>61441104
fixed
>>
>>61441192
https://github.com/nim-lang/Nim/blob/devel/todo.txt#L1-L10
>>
>>61441104
if(Integer.parseInt(args[0])==5){
System.out.println("* *");
System.out.println(" * * ");
System.out.println(" * * ");
System.out.println(" * ");
System.out.println(" * * ");
System.out.println(" * * ");
System.out.println("* *");
}
else {
System.out.println("size is not within parameter restrictions");
}


Stay sharp!
>>
File: ruby.png (192KB, 995x996px) Image search: [Google]
ruby.png
192KB, 995x996px
m=ARGV[0].to_i-1;for n in 0..m;o=" "*m;o[n]='*';o[m-n]='*';puts o;end
>>
>>61436178
C
#include <stdio.h>
#include <stdlib.h>
#define z (h+1)
#define a [
#define ka ]
#define x(x) x,x
int main(int b, char **y) {if(b) {int c a 43 ka = {3,4,2,0,5,x(x(x(x(0)))),x(x(x(6))),x(0),0,6}; c a 42 ka = 1;int k a] = {x(x(4)),x(b),0}; for (int j=0;j<43;j++){k[c a j ] ka=j;}long int h = strtol(y a--b],NULL,k a k a 5 ] - 1 ]);char* u = calloc(h*z,k a k a 5 ]]);int i = -k a 4 ka;for (;!(++i>=h);) {u a i*z+i ka = k a k[ k a 5]ka];u[i*z+h ka = 6 + k a 5 ka;k a 5 ka;u a i*z+h-i-k [ k [5 ka]ka = k a k [ k a 5 ]] ka;}for (i=-1;++i<h*z;) {putchar(u[i]?u[i]:k[6]);}}}
>>
>>61443450
Why have you done this
>>
>>61443464
getting ready for ioccc this year.
>>
>>61443450
too much readable
try harder.
>>
Code:
#!/usr/bin/env bash

a='1'
b=${1}
c=${a}
d=${b}

until [[ "${a}" -gt "${b}" ]]; do
pos='1'
until [[ "${pos}" -gt "${b}" ]]; do
if [[ ( "${pos}" == "${c}" ) || ( "${pos}" == "${d}" ) ]]; then
echo -n '*'
else
echo -n ' '
fi
((pos++))
done
((a++))
((c++))
((d--))
echo ''
done


Output
$ xshape 5
* *
* *
*
* *
* *
$ xshape 15
* *
* *
* *
* *
* *
* *
* *
*
* *
* *
* *
* *
* *
* *
* *
>>
defmodule X do
def x(n) do
blank = List.duplicate(' ', n)
0..n - 1
|> Enum.map(fn x ->
blank
|> List.replace_at(x, '*')
|> List.replace_at(n - 1 - x, '*')
end)
|> Enum.join("\n")
end
end

Enum.each(3..10, fn x ->
x
|> X.x()
|> (& &1 <> "\n").()
|> IO.puts()
end)
>>
File: 2017-07-19-023343_840x1028_scrot.png (132KB, 920x1108px) Image search: [Google]
2017-07-19-023343_840x1028_scrot.png
132KB, 920x1108px
>>61446105
use std::io;
use std::io::Write;

fn main() {
print!("Enter the size: ");
io::stdout().flush().unwrap();

let mut buf = String::new();
io::stdin().read_line(&mut buf).unwrap();

match buf.trim().parse::<i32>() {
Ok(n) if n > 2 => {
println!();
draw_cross(n);
}
Ok(_) => println!("Size must be larger than 2"),
Err(_) => println!("Size must be a number"),
}
}

fn draw_cross(n: i32) {
for i in 0..n {
for j in 0..n {
print!("{}", if j == i || j == n - 1 - i { '*' } else { ' ' })
}

println!();
}
}
>>
>>61446144

> io::stdin().read_line(&mut buf).unwrap();

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

void draw_even_x(int size)
{
for (int i = 0; i < size / 2; i++) {
for (int j = 0; j < i; j++) putchar(' ');
putchar('x');
for (int j = 0; j < (size - (2 + (i * 2))); j++) putchar(' ');
printf("x\n");
}

for (int i = (size / 2) - 1; i >= 0; i--) {
for (int j = 0; j < i; j++) putchar(' ');
putchar('x');
for (int j = 0; j < (size - (2 + (i * 2))); j++) putchar(' ');
printf("x\n");
}
}

void draw_odd_x(int size)
{
for (int i = 0; i < size / 2; i++) {
for (int j = 0; j < i; j++) putchar(' ');
putchar('x');
for (int j = 0; j < (size - (2+ (i * 2))); j++) putchar(' ');
printf("x\n");
}

for (int i = 0; i < size / 2; i++) putchar(' ');
printf("x\n");

for (int i = (size / 2) - 1; i >= 0; i--) {
for (int j = 0; j < i; j++) putchar(' ');
putchar('x');
for (int j = 0; j < (size - (2+ (i * 2))); j++) putchar(' ');
printf("x\n");
}
}

int main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "error: no argument provided\n");
exit(EXIT_FAILURE);
}

int size = atoi(argv[1]);
if (size < 1) {
fprintf(stderr, "error: argument must be a positive integer\n");
exit(EXIT_FAILURE);
}

if (size % 2) draw_odd_x(size);
else draw_even_x(size);

return EXIT_SUCCESS;
}


Does not draw additional unnecessary spaces at the end of the second asterisk. Behavior for even and odd sized cross must therefore be slightly different. General strategy for either is: draw top half, then draw bottom half with reverse process.
>>
Shorter:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "error: no argument provided\n");
exit(EXIT_FAILURE);
}

int size = atoi(argv[1]);
if (size < 1) {
fprintf(stderr, "error: argument must be a positive integer\n");
exit(EXIT_FAILURE);
}

/* Draw top half */
for (int i = 0; i < size / 2; i++) {
for (int j = 0; j < i; j++) putchar(' ');
putchar('x');
for (int j = 0; j < (size - (2+ (i * 2))); j++) putchar(' ');
printf("x\n");
}

/* Draw middle (for odd sized crosses) */
if (size % 2) {
for (int i = 0; i < size / 2; i++) putchar(' ');
printf("x\n");
}

/* Draw bottom half */
for (int i = (size / 2) - 1; i >= 0; i--) {
for (int j = 0; j < i; j++) putchar(' ');
putchar('x');
for (int j = 0; j < (size - (2+ (i * 2))); j++) putchar(' ');
printf("x\n");
}

return EXIT_SUCCESS;
}
>>
fun n x y = if x == y || x == (n - y) then 'X' else ' '
cross n = unlines [ [ fun n x y | x <- [0..n] ] | y <- [0..n] ]
main = readLn >>= putStr . cross
>>
#!/bin/sh
#!/bin/sh
x() {
n=$1
odd=$(expr $n % 2)
half=$(expr $n / 2)
for i in $(seq 0 $n); do
a=$i
if [ $i -gt $half ]; then
a=$(expr $n - $i)
fi
b=$(expr $n - $a \* 2 - 1)
printf "%${a}s*" ''
if [ $i -ne $half -o $odd -eq 1 ]; then
printf "%${b}s*" ''
fi
printf "\n"
done
}

for i in $(seq 2 10); do
x $i
done
>>
>>61446714
prettified edition
fun n x y = 
if x == y || x == (n - y)
then 'X'
else ' '

cross n = unlines
[ [ fun n x y |
x <- [0..n]
] | y <- [0..n] ]

main = readLn >>= putStr . cross
>>
x(N) :- xdraw(1,N,N,N), !.

xdraw(_,_,0,_).
xdraw(L,H,C,N) :- row(L,H,N),
L1 is L+1,
H1 is H-1,
C1 is C-1,
xdraw(L1,H1,C1,N).

row(_,_,0) :- nl.
row(L,H,C) :- C = H,
write('*'),
C1 is C-1,
row(L,H,C1).
row(L,H,C) :- C = L,
write('*'),
C1 is C-1,
row(L,H,C1).
row(L,H,C) :- write(' '),
C1 is C-1,
row(L,H,C1).
>>
File: output.png (38KB, 1670x1032px) Image search: [Google]
output.png
38KB, 1670x1032px
>>61446802
>>
>>61446834
>>61446802
Nice
>>
File: 1494435659533.jpg (47KB, 497x442px) Image search: [Google]
1494435659533.jpg
47KB, 497x442px
>>61446802
>side effects
>>
>>61446863
I don't see any asserts. Do you?
>>
>>61446849
Thanks :)
>>
>>61436178
gee must think I am homosexual because there is no way I am doing that bullshit
>>
#!/usr/bin/env python3

import sys

num = int(sys.argv[1])

for i in range(num):
lst = [" "] * num
lst[i] = lst[num-i-1] = "*"
print("".join(lst))
>>
>>61446802
Well done anon, very clean.
As someone going through Bratko's book it's nice to know there's at least one other person still holding the torch for prolog.
>>
>>61448127
Thanks! I actually learned it in uni, believe it or not, in a course that covered prolog and scheme. Glad I had to take it, it really blew my mind. I've been looking for something fun to do with it.

Is this the book?
https://www.amazon.com/Programming-Artificial-Intelligence-International-Computer/dp/0321417461

Do you need any existing AI knowledge to read it?
>>
>>61442426
Hahaha
>>
File: 1485651963652.png (395KB, 507x1040px) Image search: [Google]
1485651963652.png
395KB, 507x1040px
>>61436178
#include <stdio.h>
#include <stdlib.h>

void print_cross(int scale) {
for (int i=0; i<scale; i++) {
for (int j=0; j<scale; j++) {
if (j == i || j == scale-i-1) {
printf("*");
} else {
printf(" ");
}
}
printf("\n");
}
return;
}

int main(int argc, char **argv) {
print_cross(atoi(argv[1]));
return 0;
}
>>
>>61442426
Now just wrap it up in an XFactory and it's enterprise ready!
>>
#!/usr/bin/env ruby

def draw_half_cross size, iter
iter.each do |i|
puts "#{' ' * i}x#{' ' * (size - (2 + i * 2))}x"
end
end

abort "error: no argument provided" if ARGV.empty?

size = ARGV[0].to_i
half = size / 2
abort "error: argument must be a positive integer" if size < 1

draw_half_cross size, 0.upto(half - 1)
puts "#{' ' * half}x" if size.odd?
draw_half_cross size, (half - 1).downto(0)
>>
>>61448828
What a disgusting language
>>
>>61448839

What part do you find disgusting?
>>
>>61448872
Which parts DON'T I find disgusting?
>>
Haskell:
main = putStr "Enter size: " >> getLine >>= star
star s = putStr $ unlines $ map line [0..n]
where n = read s - 1
line k = [if elem i [k,n-k] then '*' else ' ' | i<-[0..n]]

In action:
$ runghc star.hs
Enter size: 5
* *
* *
*
* *
* *
>>
not really a programmer, how did I do?
#include<stdio.h>
int main(){
int size, loops = 1;
printf("? ");
scanf("%d", &size);
for(int i = 1; i <= size; i++){
for(int j = 1; j <= size; j++){
if(j == loops || j == size-loops){
printf("*");
}
else{
printf(" ");
}
}
printf("\n");
loops++;
}
return 0;
}
>>
>>61449058
Looks mostly good. People will probably shit on your code but they basically make it into a code golf competition here. Only real issue imo is you could just use i instead of loops. Haven't checked for off by one errors though.
>>
File: 1493707565961.png (17KB, 882x758px) Image search: [Google]
1493707565961.png
17KB, 882x758px
I can't do it, am I a brainlet? Do you guys start with a template or lookup the first step?

I'm talking about from scratch.
>>
>>61449127
That's true. I'd 'optimize' it but it would just end up looking like >>61448580
>>
def x n
(0...n).map do |i|
(0...n).map do |j|
if i == j || n - i - 1 == j
"*"
else
" "
end
end.join
end.join "\n"
end
>>
>>61449058
Your second comparison is fucked. See this post >>61437139
>>
>>61437139
int y = .5 I stopped reading there
>>
>>61449258
lmao
>>
>>61449388
That's cause I was trying to fuck around with a different method of doing it using floats and forgot to change my initializer back to zero.

Guess what? This is C and it automatically turned them back to zero because that's how integers work.
>>
>>61449270
Yeah, I see what you mean.
>>61449258
What do you mean by template/lookup?
>>61449281
That's Ruby, right? How does the precedence work here? As in, how does it know not do bind the join to that do block... thing? Not sure if it's a real lambda or not.
>>61449388
Yeah, he's fucking with you anon, 0.5 just truncates to 0 for ints. I just checked your code, and it renders the second diagonal wrong. The easiest solution is to just replace the second conditional with
1+size-loops
. If you counted from 0 to n-1 like he did, your offset would be slightly different since j is lower but size and loops cancel out.
>>
>>61449258
These programming problems are like math problems you did in school. First they taught you how to solve for x, then they gave you problems like x - 7 = 8. Except the tool you use to solve the problem are the programming language. So, first, it helps to know a programming language. Not saying you need to be a master. As an example, you should know the syntax for a "for" loop (or a given language's equivalent) without looking it up. The next step I usually take is thinking how I would "manually" code the solution. For this problem, it would be like this: >>61441104 Whenever there's repetitions, you can use a loop of some kind. You can also try looking at it like this: >>61437139 Another good trick to use is to look for a pattern and figure out the pattern. In this problem, the number of spaces between the * decreases by two each time, and then increases by 2 starting from 1 after the center *. Another one that applies more to problems with sets of data is to sort the data in some meaningful way. That's all I can think of for now, but basically you just need to learn a programming language and then things start to become obvious.


t. learning programming through solving challenges
>>
>>61448996
no types yet more type safe than all the other solutions in this thread
>>
>>61449456
Haskell niggers go home.
>>
>>61449468
why
>>
In beautiful Javascript:

<html>
<body>

<script>

function makeStar(size){

var x, y, z, str;

for(x = 0, y = size; x < size; x++, y--){
str = [];

for(z = 0; z < size; z++){
str.push(' ');
}
str[x] = '*';
str[y] = '*';
document.write(str.join('&nbsp;') + '<br/>');
}
}

makeStar(10);

</script>

</body>
</html>
>>
>>61449545
That's HTML
>>
>>61449545
If you're going to omit the head tag, you can just go all the way in modern html and just put a script tag.
>>
>>61449590
Need to do that in order to run in my browser.
>>
File: 1476811327277.jpg (38KB, 640x480px) Image search: [Google]
1476811327277.jpg
38KB, 640x480px
>>61449617
>claim to have done it in javascript
>but post html solution
lying is rude
>>
File: 1498793762179.gif (285KB, 361x393px) Image search: [Google]
1498793762179.gif
285KB, 361x393px
>>61436178
    ORG    $1000

MOVE.B #$04,D0 ;get number
TRAP #$0F
MOVE.L D1,D2

LOOP_R:
MOVE.L #0,D4 ;reset column
MOVE.L D2,D5 ;scale-row-1
SUB.L D3,D5
SUB.L #1,D5

LOOP_C:
CMP.L D3,D4 ;column==row
SEQ D0
CMP.L D4,D5 ;column==scale-row-1
SEQ D1
OR.B D0, D1
CMPI.B #$FF, D1
BNE ELSE

MOVE.B #$2A,D1 ;print '*'
MOVE.B #$06,D0
TRAP #$0F
BRA IF_END
ELSE:
MOVE.B #$20,D1 ;print ' '
MOVE.B #$06,D0
TRAP #$0F
IF_END:

ADD.L #1,D4
CMP.L D2,D4
BLT LOOP_C

MOVE.B #$0A,D1 ;print CR, LF
MOVE.B #$06,D0
TRAP #$0F
MOVE.B #$0D,D1
MOVE.B #$06,D0
TRAP #$0F

ADD.L #1,D3
CMP.L D2,D3
BLT LOOP_R
STOP #$2700

END $1000

It's shit and I didn't bother optimizing it, but it works.
>>
>>61450018
>ST-TOS
>not the TV show
Absolute madman.
>>
>>61449258
Still haven't solved it yet but I would start by doing it small (3x3) and by hand first.
>>
$ cat cross.coffee
size = +process.argv[2]
for y in [1..size]
for x in [1..size]
process.stdout.write (if x in [y, (1 + size - y)] then '*' else ' ')
process.stdout.write '\n'
>>
>>61450255
$ coffee cross.coffee 7
*     *
* *
* *
*
* *
* *
* *
>>
>>61449545
Your loop terminates when x hits the size but your y initializes on size.
>>
>>61449680
But ECMAScript itself doesn't come with bindings to standard input/output. Passable b/c anime pic though.
>>
>>61442280
I use ISE, copypasted just for screenshot
>>
colnum = int(input("enter the size"))

grid = [[' ' for i in range(colnum)] for i in range(colnum)]

for row in grid:
row[grid.index(row)] = 'x'
row[colnum-grid.index(row)-1] = 'x'

for row in grid:
''.join(row)
print row
>>
>>61449545
w e w
>>
if your solution has to compare anything you're a brainlet pajeet

just sayin
>>
>ctrl+f forth
>no results

VARIABLE SIZE
16 PAD SWAP ACCEPT PAD SWAP SNUMBER? DROP SIZE !
: star [CHAR] * EMIT ;
: PRINTSTARS
SIZE @ 0 DO
SIZE @ 0 DO
I J = IF star
ELSE SIZE @ 1 - J - I = IF star
ELSE space THEN THEN
LOOP CR
LOOP ;
CR
PRINTSTARS
BYE


$ gforth x.forth
5
* *
* *
*
* *
* *
>>
>>61451046
>ctrl+f forth
>4 results
what are you talking about anon
>>
>>61451082
You're right. Don't know how I missed that
>>
File: 1485457590568.jpg (80KB, 1024x768px) Image search: [Google]
1485457590568.jpg
80KB, 1024x768px
>>61451340
don't worry senpai, i gotchu
>>
File: 1498482571360.jpg (2MB, 1750x1080px) Image search: [Google]
1498482571360.jpg
2MB, 1750x1080px
static void printX(int size){
StringBuilder string = new StringBuilder("");
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
if(j == size/2-Math.abs(i-size/2) || j == size/2+Math.abs(i-size/2)){
string.append("*");
} else if (j < size-1) {
string.append(" ");
}
}
string.append("\n");
}
System.out.println(string.toString());
}

Java is comfy for me, pls no bully
>>
>>61451046
VARIABLE SIZE
PAD PAD 16 ACCEPT SNUMBER? DROP SIZE ! CR
: star [CHAR] * EMIT ;
: PRINTSTARS
SIZE @ 0 DO
SIZE @ 0 DO
I J = IF star
ELSE SIZE @ 1 - J - I = IF star
ELSE space THEN THEN
LOOP CR
LOOP ;
PRINTSTARS
BYE


Got rid of some unnecessary swaps
>>
>>61451504
>>61451046
does forth really require you to put "bye" at the end of a program

that's cute
>>
>>61451678
BYE just exits the interpreter. It's definitely no INTERCAL.
>>
File: cruise_monster_keks.jpg (304KB, 1920x1080px) Image search: [Google]
cruise_monster_keks.jpg
304KB, 1920x1080px
>>61436178
>his name is Edgar
Haha what a faggot name OP
>>
>>61451504
PAD, PAD, one-time pad.
>>
File: progLanguages.jpg (92KB, 581x371px) Image search: [Google]
progLanguages.jpg
92KB, 581x371px
ascii = """
* *
* *
*
* *
* *
"""
puts ascii
---
kek
>>
>>61451823
w-what's intercal
>>
File: 23-twin-peaks-ep-4.w710.h473.2x.jpg (88KB, 1420x946px) Image search: [Google]
23-twin-peaks-ep-4.w710.h473.2x.jpg
88KB, 1420x946px
for i in ['*     *',' *   * ','  * *  ','   *   ','  * *  ',' *   * ','*     *']: print(i)


Brainlets ITT stuck in 2017 when I'm up here in 4017
>>
where the brainfuck at you plebes
>>
>>61450018
disgusting spacing. properly spaced assembly is beautiful. columns, my dude. otherwise good work.
>>
>>61452170
Congrats, you did the case when n = 7. Now give us a proper answer.
>>
print "".join("".join("*" if i == j or i+j == n-1 else " " for i in range(n))+"\n" for j in range(n))
>>
$ ghci
GHCi, version 8.0.2: http://www.haskell.org/ghc/ :? for help
Prelude> f x y w h = if x == y || x == w-y then '*' else ' '
Prelude> import Data.List
Prelude Data.List> g d = intercalate "\n" [ [ f i j d d | i <- [0..d] ] | j <- [0..d] ]
Prelude Data.List> putStrLn $ g 10
* *
* *
* *
* *
* *
*
* *
* *
* *
* *
* *
Prelude Data.List>
>>
>>61436479
#include <stdio.h>
#include <stddef.h>
#include <stdbool.h>

static bool default_map[] = {
0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0,
0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0,
1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1,
0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0,
0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0
};


void print_row(bool* map, size_t width, size_t xspc, char symbol)
{
for (size_t col = 0; col < width; ++col)
{
printf("%c", map[col] ? symbol : ' ');

for (size_t x = 0; x < (width - col) && x < xspc; ++x)
{
printf(" ");
}
}
}


void print_rows(bool* map, size_t width, size_t height, size_t xspc, size_t yspc, char symbol)
{
for (size_t row = 0; row < height; ++row)
{
print_row(map + width * row, width, xspc, symbol);

for (size_t y = 0; y < (height - row) && y < yspc; ++y)
{
printf("\n");
}
}
}


int main()
{
print_rows(default_map, 13, 13, 2, 1, '*');
return 0;
}
>>
>>61452401
Excuse me that was not in the requirements

You'll need to put a ticket in because we are in the middle of a sprint and couldn't possibly be asked to do anything

t. engineering
>>
python
size = 5
print "\n".join(["".join(map(lambda (x,y,s): 'x' if x == y or (x+y) == s-1 else ' ' , [(x, y, size) for x in range(0, size)])) for y in range(0, size)])
>>
>>61449258
look at what you want to achieve and split it up into separate easier steps. so in this example:

1) I want to draw a grid. a grid consists of rows and columns. So you start to write a program that outputs a bunch of rows and columns, can be just spaces or . or whatever char.

2) Certain cells of the grid have different values then others. now this is probably the step that gives you trouble? Here you want to try to figure out a formula that produces the desired output. Here's how I did it. I just wrote one sample output out like this:

  0 1 2 3 4
0 x . . . x
1 . x . x .
2 . . x . .
3 . x . x .
4 x . . . x


Looking at it like this, I noticed:
- that the first line always produces an x when row == column.
- that the second line produces an x when row + column == size -1
>>
>>61452765
this disgusts me.
>>
>>61452259
legit this
>>
>>61441104
>program that outputs an "ASCII art" cross of asterisks in your favourite language!
Hired, the rest of you failed to the complexity meme and chose a much harder and expensive implementation of somthing that can be made with 1 printf.
>>
>>61453989
nice, this is a win-win, you took the idiot out of the hiring pool and filled the last vacant position at moron inc.
>>
#include <stdio.h>
#define u putchar

h,e,l,p;main(){
scanf("%d",&h);
a:if(p==2)return;
for(int l=0;l<h/2;l++){
for(e=0;e<(h/2)*p-l+(l*2)*!p;e++)
u(0[" ""#""\n"]);
u(1[" ""#""\n"]);
for(e=0;e<((h/2)*!p-l+l*2*p)*2;e++)
u(0[" ""#""\n"]);
u(1[" ""#""\n"]);
u(2[" ""#""\n"]);
}p++;goto a;
}
>>
File: f.png (839B, 92x160px) Image search: [Google]
f.png
839B, 92x160px
>>61441104
>>
>>61454590
wrote it in c
what do you think?
#include <stdio.h>
#define u putchar

h,e,l,p;main(){
scanf("%d",&h);
a:if(p==2)return;
for(int l=0;l<h/2;l++){
for(e=0;e<(h/2)*p-l+(l*2)*!p;e++)
u(0[" ""#""\n"]);
u(1[" ""#""\n"]);
for(e=0;e<((h/2)*!p-l+l*2*p)*2;e++)
u(0[" ""#""\n"]);
u(1[" ""#""\n"]);
u(2[" ""#""\n"]);
}p++;goto a;
}
>>
File: yuiehhh.jpg (33KB, 388x377px) Image search: [Google]
yuiehhh.jpg
33KB, 388x377px
>search malloc
>0 results
#include <stdio.h>
#include <stdlib.h>

void initialize(char *a, int n){
char *b = a; int i;
for (i = 0; i < n; ++i) *a = 32, ++a;
*a = *b = 42;
}

void swap(char *a, int m, int n){
char *x, *y; int i;
x = y = a; y += m;
for (i = 0; i < n; ++i) ++x, --y;
*x = *y = 32;
*++x = *--y = 42;
}

void main (){
int i,n = 0;
scanf("%d", &n); --n;
char *a = malloc((n + 1)* sizeof(char));
initialize(a, n);
for (i = 0; i < n + 1; ++i){
printf("%s\n", a);
swap(a, n, i);
}
}
>>
File: wow.png (118KB, 1365x768px) Image search: [Google]
wow.png
118KB, 1365x768px
Isn't Haskell pretty boys
>>
>>61456242
it may be concise but it's not pretty
>>
>>61454703
>using goto
are you retarded?
>>
>>61456403
what's wrong with using goto?
>>
>>61451678
>does forth really require you to put "bye" at the end of a program
No. "BYE" isn't a word in CORE or CORE-EXT forth, it's just a thing gforth and some other forth interpreters use to return control to the host operating system. The vast majority of the time, forth code operates on an embedded system without a host operating system and as a compiled binary that terminates at its end without special instruction. If there is a host OS at that point, control will automatically be returned to it.
But for interpreters on complex consumer systems (where this kind of code would run), you need a way to tell them you're done.
>>
>>61454948
>using malloc for a problem this simple
>>
>>61453291
are you some sort of a programming god ?
where is your shrine, i want ro bring you tribute
>>
>>61448887
In all fairness, it's not the language, it's written awfully. I think it's a false flag.
>>
File: Screenshot_1.png (61KB, 1762x516px) Image search: [Google]
Screenshot_1.png
61KB, 1762x516px
>>61436178

3 lines in C# (2 of which are just an intro text and an end-of-program enter-to-continue), making it 1 "actual" line

This code is absolutely disgusting and I regret every moment of it. Have fun

Console.Write("Enter size: ");
Enumerable.Repeat(int.Parse(Console.ReadLine()), 1).SelectMany(size => Enumerable.Repeat(size, size)).Select((size, index) => Tuple.Create(size, index)).ToList().ForEach(tuple => Console.WriteLine((Math.Pow(10, tuple.Item2) + Math.Pow(10, tuple.Item1 - tuple.Item2 - 1)).ToString(new string(Enumerable.Repeat('0', tuple.Item1).ToArray())).Replace('0', ' ').Replace('1', 'x').Replace('2', 'x')));
Console.ReadLine();
>>
>>61456452
while (p < 2)
{

p++;
}
return;
>>
$ cmatrix
>>
>>61458068
C# truly is the greatest language of all time
>>
File: ruby.png (2KB, 212x262px) Image search: [Google]
ruby.png
2KB, 212x262px
>>61443103
Was able to shave a little more off.
m=ARGV[0].to_i;m.times{|n|o=' '*m;o[n]=o[m-n-1]='*';puts o}
>>
File: 1474652315138.gif (2MB, 200x187px) Image search: [Google]
1474652315138.gif
2MB, 200x187px
>>61452144
>he doesn't know INTERCAL.
>The INTERCAL programming language was designed the morning of May 26, 1972 by Donald R. Woods and James M. Lyon, at Princeton University. Exactly when in the morning will become apparent in the course of this manual.
No way in hell am I doing the challenge for it.
>>
code code star cross dir
sudo asterisk cross
htop
ls
screenfetch
>>
main = do
putStrLn "X X\n X X \n X \n X X \nX X"
>>
>>61452765
my nigger
>>
>>61457960

>it's written awfully
And what about what I have written do you find awful?
>>
This is too hard
>>
>>61461951

How is it hard?
>>
File: ew.jpg (13KB, 350x350px) Image search: [Google]
ew.jpg
13KB, 350x350px
>>61461926
I'm quite sure you're baiting, but I'll give you a free nibble.

puts "#{' ' * i}x#{' ' * (size - (2 + i * 2))}x"

>the core functionality all written within string placeholders.
>>
>>61462339

You would prefer a longer program, rather than using string interpolation for its intended purpose?
>>
>>61449449
what they didn't teach you in school was how to format your fucking post
>>
>>61462394
>intended purposes
get that hook away from me.

>longer program
What's a few bytes in the name of readability. The ridiculous length of your solution is already an embarrassment to the language.
>>
File: 1311691187756.jpg (82KB, 436x348px) Image search: [Google]
1311691187756.jpg
82KB, 436x348px
>>61436603
Not bad in principle, but I prefer my fortran in a more .. genuinely fortran kinda style.
      program drawthing
implicit none
character symbol
character padding
character*2 newline
integer xsize,xpos(2)
integer xstart,xend
integer j,k

parameter (symbol='*',padding=' ',newline='()')

write(*,"(A15)") "size of thingy:"
read(*,*) xsize

xpos(1)=1
xpos(2)=xsize
do j=1,xsize
xstart=minval(xpos)
xend=maxval(xpos)
do k=1,xstart-1
write(6,fmt='(A)',advance='NO') padding
enddo
write(6,fmt='(A)',advance='NO') symbol
do k=xstart+1,xend-1
write(6,fmt='(A)',advance='NO') padding
enddo
if (xstart.ne.xend) then
write(6,'(A)') symbol
else
write(6,newline)
endif
xpos(1)=xpos(1)+1
xpos(2)=xpos(2)-1
enddo
end
>>
>>61436964
>can't solve a simple problem
why try
>>
>>61462616

>The ridiculous length of your solution
To be fair, part of that is producing readable error messages, and the other part of it is trying to ensure no spaces are printed after the last x. I could use the same approach of "treat it as a grid and print an x if it matches one of two conditions" that every other program posted here is using, but I am placing additional restrictions onto myself to make this an actual challenge.

If you want a more readable function, I could always do it like this:
def draw_half_cross size, iter
iter.each do |i|
front = ' ' * i
middle = ' ' * (size - (2 + i * 2))
puts "#{front}x#{middle}x"
end
end


But you might consider that length even more ridiculous.
>>
File: prog.png (3KB, 384x272px) Image search: [Google]
prog.png
3KB, 384x272px
>>61436178
10 rem having no 'else' on c64 is pretty lulzy
20 print "enter size:"
30 input s
33 l=0
36 r=s-1
40 for i=0 to s-1
45 for j=0 to s-1
50 if j=l or j=r then print "*";
55 rem amazing:
60 if j<>l and j<>r then print " ";
70 next j
73 l=l+1
76 r=r-1
80 print ""
90 next i

it's super slow but oh fucking well
dunno why I keep doing these threads in c64 basic
someone tried to argue with me that c64 basic wasn't shit compared to msx basic, I hope that person fucking dies
>>
>>61436178
5i <Esc>0r*qqYpxpl@qq@q0qar*lk@aq@a

vim. replace the 5 with whatever you want. 31 keystrokes
>>
n = gets.chomp.to_i

(0...n).each do |i|
row = ' '*n
row[i] = row[-(i + 1)] = '*'
puts row
end
>>
>>61458068
as much as I like C#, this syntax makes me want to fucking die

>>61456242
your c implementation is way too long
like, literally twice as long as it needs to be
>>
I did it in Rust too!
use std::env;
use std::iter::Iterator;
use std::str::FromStr;

fn draw_half_cross<T>(size: usize, iter: T)
where T: Iterator<Item=usize> {
for i in iter {
for _ in 0..i { print!(" "); }
print!("x");
for _ in 0..(size - (2 + i * 2)) { print!(" "); }
println!("x");
}
}

fn main() {
let args = env::args().collect::<Vec<String>>();
let size = usize::from_str(&args[1]).unwrap();
let half = size / 2;

draw_half_cross(size, 0..half);
if size % 2 == 1 {
for _ in 0..half { print!(" "); }
println!("x");
}
draw_half_cross(size, (0..half).rev());
}
>>
File: 08.jpg (75KB, 277x270px) Image search: [Google]
08.jpg
75KB, 277x270px
>>61457818
ok then.
#include <stdio.h>
#define ____ putchar
_____(int _,int __,int ___){!___?scanf("%d",&___),++___:_>=___?_=0,++__,____(10):(_-__)&&(_+__-___)?____(32):____(42);__==___?_:_____(++_,__,___);}
main(){_____(0,0,0);}
>>
>>61464074
>
let args = env::args().collect::<Vec<String>>();

What an absolutely disgusting language
>>
File: lisp.jpg (56KB, 600x900px) Image search: [Google]
lisp.jpg
56KB, 600x900px
(defun cross (n)
(let ((left 0)
(right (- n 1))
(result nil))

(dotimes (i n)
(let ((line (make-string n :initial-element #\space)))
(setf (char line left) #\*)
(setf (char line right) #\*)
(incf left)
(decf right)
(setf result (concatenate 'string result (format nil "~a~%" line)))))
result))

(write-string "Enter Number: ")
(finish-output)
(write-string (cross (read)))


$ sbcl --script ./cross.lisp
Enter Number: 15
* *
* *
* *
* *
* *
* *
* *
*
* *
* *
* *
* *
* *
* *
* *
>>
curl https://pastebin.com/raw/FaYDizZv
>>
>>61439108
for what purpose?
>>
>>61449492
Because Haskell niggers creates elegant solutions and deserve to spend time with their loving families.
>>
>>61436178
((n,a,b)=>{for(let l=[],i=0;i<n;i++){for(let j=0;j<n;j++)l.push(i===j||n-j-1===i?b:a);console.log(l.splice(0,n).join(""))}})(5," ","*")
>>
>>61436178
Asterisks are the same in every language
>>
>>61448179
Sorry for the delay in replying.

Yeah my exposure to prolog was from the same place: advanced programming subject from the usual khaki wearing long grey beard prof.

The bratko book is quite good, I'd say having exposure to prolog is required more than exposure to AI. I guess the only problem so far is that some of it is more for implementations of AI that have fallen out of favor (expert systems seem to have died in the AI winter).
>>
>>61436178
#include <stdio.h>

int main () {
int size, i, j;

do {
printf("Enter the size: ");
scanf("%d", &size);
if (!(size%2))
printf("The size must be odd! \n");
}while(!(size%2));

char cross[size][size];

for (i=0;i<size;i++)
for (j=0;j<size;j++)
cross[i][j]=' ';

for (i=0;i<size;i++) {
cross[i][i]='*';
cross[size-i-1][i]='*';
}

for (i=0;i<size;i++) {
for (j=0;j<size;j++)
printf("%c", cross[i][j]);
printf("\n");
}
return 0;
}
>>
>>61464074
>all those needless allocations
>all those statements and calls to print
>.unwrap(), possibility of panic
Pitiful. Here, watch
fn main() {
let n = std::env::args()
.nth(1)
.and_then(|a| a.parse().ok())
.unwrap_or(5);

print!("{}", (0..n)
.flat_map(|i| {
(0..n).map(move |j| {
if i == j || (n - i - 1) == j {
'*'
} else {
' '
}
}).chain("\n".chars())
}).collect::<String>())
}
>>
>>61436178
int main(int argc, char **argv){
int s = atoi(argv[1]-1);
for(int y = 0; y<=s;y++){
for(int x = 0; x<= s;x++)
putchar(x==y || x==s - y ? '*' : ' ');
putchar('\n');
}
}
>>
for each customer:
display customer.
end.
>>
Inferior-to-haskell OCaml solution coming through
let rec iota = function
| 0 -> []
| n -> 0 :: List.map succ (iota (n - 1))

let _ =
let n = int_of_string (Array.get Sys.argv 1) in
let rec line i =
if i != n then
(String.make n '_' |>
String.mapi (fun j _ ->
if (j == i) || (j == n - i - 1)
then '*'
else ' ') |>
print_endline ;
line (i + 1))
in
line 0
>>
>>61467765

>Needless allocations
Erm... technically it's only allocating memory once, at least with regards to heap memory.

And yes, there is a possibility of panic. That's intentional. I want it to panic if there is a lack of an argument or if the argument cannot be coerced into a usize.

Also, your program is not equivalent to what I am doing. I do not want each line to be of size n.
>>
A difference between the programs I'm showing and what everyone else is doing. If we let a . represent a space, my output might look like this:
x...x
.x.x
..x
.x.x
x...x


Whereas the majority of programs being posted might look like this:
x...x
.x.x.
..x..
.x.x.
x...x


As n approaches infinity, I print 25% less characters.
>>
>>61453111
>embeds data in source
Hello Rajeesh, I see you learned C.
>>
>>61468565
Optimize further by replacing eight spaces with tabs
>>
>>61468596

The size of a tab character is user configurable and can never be assumed to have the width of 8 characters.
>>
File: 1485403695091.png (141KB, 800x600px) Image search: [Google]
1485403695091.png
141KB, 800x600px
Friendly reminder that this is the level of competition you have to face in sub-60k positions.
>>
#include "stdio.h"
int main(void)
{
int size;
printf("Enter the size: ");
scanf("%d", &size);
char line[size+1];
line[size+1] = '\0';

for (int i = 0; i <= size; ++i) {
line[i] = ' ';
}

for(int i = 0; i < size; ++i) {
line[i] = line[size-i-1] = '*';
printf("%s\n", line);
line[i] = line[size-i-1] = ' ';
}

return 0;
}
>>
>>61468746
Also

>all these nested for loops
You people disgust me.
>>
>>61468746
And again in ruby

print "Enter size: "
size = gets.chomp.to_i
line = Array.new(size,' ')
(0..size-1).each do |i|
line[i] = line[size-1-i] = '*'
puts line.join
line[i] = line[size-1-i] = ' '
end
>>
>>61468755

>no nested for loops
Now that's a challenge. I'd be kind of weird to constantly be moving the null terminator though...
>>
>>61468755
>Using memory when no memory is needed
Brainlet. Your shit fails when N = 8388608 when stack is 8MB.
>>
>>61468856
>Your approach doesnt work with unreasonable sizes on limited hardware
Yes, you also can't run Quake Arena on an NES. What's your point?
>>
>>61441104
This is unironically the best answer
>>
>>61468876

>Limited hardware
lolno, that's a software requirement. Stack size in Linux is only 8 MB by default. In Windows, it's only 1 MB. If you want to use an arbitrary amount of memory for which there is no upper bound, malloc should be used.
>>
>>61468876
Using two loops is the straightforward and easiest way to do it. Using a buffer to do it is retarded.
>>
>>61468894
That's fair, but still a moot point since it's one line change and a free() at the end.
I'll take n runtime over n^2 for a bit of extra memory any day.
>>
>>61468905
>Using two loops is the straightforward and easiest way to do it
Honestly I've looked at half the responses and most of them look like over-engineered gibberish.
>>
>>61468911

>n runtime
It's cute how you think your printf statement is O(1) time over a string of size n.
>>
>>61446177
Go suck some more /pol/ dick
>>
>>61468746
also
>include "stdio.h"
for fucks sake, this is a system header, go and stay with Ruby
>>
>>61468565
#!/usr/bin/env tclsh
proc cross {n} {
set cross {}
for {set i 0} {$i < $n} {incr i} {
set min [expr {min($i, $n - 1 - $i)}]
set max [expr {max($i, $n - 1 - $i)}]
set line [concat [lrepeat $max { }] *]
lset line $min *
lappend cross [join $line {}]
}
return [join $cross \n]
}

puts [cross $argv]
>>
>>61468946
>Being this mad because somebody didnt nest loops
>>
>>61468931
O(n^2) vs O(n^3) then.
No nested loops > nested loops
>>
>>61468755
So what? It's still O(n^2). And you can write one with no 'loop' at all >>61464311
>>
>>61468985
He did. There is no instruction to print a string. Printing a string is a loop of hidden in printf.
>>
>>61468995
Take Calculus 102.
>>
>>61468995
putchar is O(1).
>>
>>61469017
Take my foot up your ass
>>

X



I learnt how to Khode with Kharlie guys!!!
>>
NEW CHALLENGE
* ***
* *
*****
* *
*** *
>>
>>61469069
#include <stdio.h>

#define N 7 // must be odd and >= 5
#define WALL '*'
#define HOLE ' '

int main(void) {
for (int y = N - 1; y >= 0; --y) {
for (int x = 0; x < N; ++x) {
putchar(x == N / 2 || y == N / 2
|| (y == N - 1 && x > N / 2) || (y == 0 && x < N / 2)
|| (x == N - 1 && y < N / 2) || (x == 0 && y > N / 2)
? WALL : HOLE);
}
putchar('\n');
}
}
>>
>>61469000
trips of truth
>>
>>61469092
#!/usr/bin/env lua5.3

local N = 5 -- must be odd and >= 5
local WALL = '*'
local HOLE = ' '

local s = {}
for y = N, 1, -1 do
for x = 1, N do
if y == N // 2 + 1 or x == N // 2 + 1
or (y == N and x > N // 2) or (y == 1 and x <= N // 2)
or (x == N and y <= N // 2) or (x == 1 and y > N // 2) then
s[#s + 1] = WALL
else
s[#s + 1] = HOLE
end
end
s[#s + 1] = '\n'
end
io.stdout:write(table.concat(s))
>>
>>61469100
#!/usr/bin/env python3

N = 5 # must be odd and >= 5
WALL = '*'
HOLE = ' '

for y in range(N - 1, -1, -1):
for x in range(N):
print(WALL if y == N // 2 or x == N // 2
or (y == N - 1 and x > N // 2) or (y == 0 and x < N // 2)
or (x == N - 1 and y < N // 2) or (x == 0 and y > N // 2)
else HOLE, end='')
print()
>>
>>61469020
But its a moot point because any solution using individual character placement will have to do that n times for each line and n times for the height, and any solution using string printing is (depending on the language) most likely just doing that behind the scenes anyway.
Nesting the loops adds an additional n-time operation.
>>
>>61469136
The guy tried to prove nested loops are O(n^3).

Well actually he just said it and didn't try to explain anything.
>>
>>61469136
>Nesting the loops adds an additional n-time operation.
There is no difference in time complexity between a single loop from 1 to n*n and two nested loops 1 to n.
>>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]){
int size, i, j;
if( argc != 2 ){
printf( "usage: %s integer number\n", argv[0] );
}else{
size = atoi(argv[1]);
for(j=0;j<size;++j){
for(i=0;i<size;++i){
if( (i==j) || (i==(size-1-j)) ){
printf( "X" );
}else{
printf( " " );
}
}
printf( "\n" );
}
}

return 0;
}
>>
>>61469178
I think he meant that hiding complexity in printf is better without providing any explanation of why.
>>
>>61468565
Ruby get over yourself.
#include <stdio.h>

int main() {
int size;
scanf("%d",&size);

for(int y = 0;y<size;y++) {
for(int x = 0;x<size;x++)
if(y == x || y == size-x-1)
putchar('*');
else if(y > x || y < size-x-1)
putchar('.');
else break;
putchar('\n');
}
return 0;
}
>>
>>61468995

It's O(n^2) vs O(n^2), Anon.

With nested loops, you execute an O(1) operation O(n^2) times.
Without nested loops, you execute an O(n) operation O(n) times.

The benefit to not using nested loops is that you make less system calls. It is a lot faster to call the write() system call n times on strings of size n than it is to call it n^2 times on strings of size 1. But ultimately, the difference between the two methods is still a constant factor.
>>
>>61469069
Harder than I thought and it's a shit solution, but hey, it's a solution.

print "Enter size of Hitler Love: "
size = gets.chomp.to_i
if size % 2 == 0 then size += 1 end
half = size/2
(0..size-1).each do |i|
if i == 0 then puts '*' + ' '*(half-1) + '*'*(half+1)
elsif i == half then puts '*'*size
elsif i == size-1 then puts '*'*(half+1) + ' '*(half-1) + '*'
elsif i < half then puts '*' + ' '*(half-1) + '*'
else puts ' '*(half) + '*' + ' '*(half-1) + '*' end
end
>>
>>61469069
#!/usr/bin/perl
$n=shift;
print "*", " "x($n/2-1), "*"x($n/2+1), "\n";
for($i=0; $i<($n-3)/2; $i++) {print "*", " "x($n/2-1), "*\n"}
print "*"x$n, "\n";
for($i=0; $i<($n-3)/2; $i++) {print " "x($n/2), "*", " "x($n/2-1), "*\n"}
print "*"x($n/2+1), " "x($n/2-1), "*", "\n";
>>
>>61469250
>>61469178
Fuck you guys are right.
I can't for the fucking life of me figure out why I'm so shit at runtime analysis. Which is bad because the guy I'm trying to butter up for graduate work is my algo teacher and he fuckin knows it
>>
File: y.jpg (33KB, 429x458px) Image search: [Google]
y.jpg
33KB, 429x458px
>>61469069
as you wish.
#include "stdio.h"
#define p putchar
void p1(int n, int j){
int i;
for (i = 0; i < n; ++i) p(j);
}
void p2(int n){
int i;
p(42);
for (i = 0; i < n - 1; ++i) p(32);
}
void main(){
int n, N, i;
scanf("%d", &N); n = N / 2;
p2(n), p(42), p1(n, 42), p(10);
for (i = 0; i < n; ++i) p2(n), p(42), p(10);
p1(n, 42), p(42), p1(n, 42), p(10);
for (i = 0; i < n; ++i) p1(n, 32), p2(n), p(42), p(10);
p1(n, 42), p2(n), p(42), p(10);
}
>>
>>61469333
>I can't for the fucking life of me figure out why I'm so shit at runtime analysis.
see >>61469017
>>
>>61469346
I've gone all the way through multivariable and vector calculus.
Is it for summation? It's for summation isn't it.
We covered that for a single day at the very end of the semester and no other class I've taken wanted to explain it in depth.
I probably attend a subpar university.
>>
>>61469224
#include <stdio.h>

int main() {
int size;
scanf("%d",&size);

for(int y = 0;y<size;y++) {
for(int x = 0;x<size;x++)
if(y == x || y == size-x-1)
putchar('*');
else if(y > x && y < size-x-1)
putchar(' ');
else if(y > x || y < size-x-1)
putchar('.');
else break;
putchar('\n');
}
return 0;
}
>>
>>61469359
>I probably attend a subpar university.
Sounds plausible. You need to find a decent textbook and do the big O exercises.
>>
>>61469312
Shit. Does anyone look back at Perl code or do they just leave it there, hopefully working?
>>
>>61469389
>do they just leave it there, hopefully working
That's about 90% of why anybody remains employed with Perl.
It's not actually hard to tell what he's doing there if you know the syntax and all the dumb special operators, but most people see that and run away.
>>
How about this
n;main(a){for(a=!scanf("%d",&n),n--;a<=n;++a>n||puts(""))printf("%*s*%*s",a>n/2?n-a:a,"",abs(n-2*a),"*"+!(n&1||a^n/2));return!n;}

No additional spaces, meaningful error code.
>>
>>61469069
See >>61436361 and >>61453111
>>
BUMP!
UMP!B
MP!BU
P!BUM
!BUMP
Thread posts: 235
Thread images: 40


[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.