Programming Exercise Thread

In this thread we code irl.

You roll it, You code it, You post it.

even /g/ has a coding thread up, don't tell me you faggots will let /g/ outdo you.


Other urls found in this thread:'

will get back to you with code friends. will take me some time. will use opencv to work with maze images. you faggots better do your exercises.

Can someone make a better programming challenge image for these threads?
I've always hated this one because the difficulty of the challenges varies too much. There should be separate challenge images each with its own difficulty. I don't want to remake Wolfenstein in one roll and fucking fizzbuzz in another

wow a shitty programming challenges list saved off /g/, which you've only done two of
this will surely save Holla Forums!

I have to agree with this.

Am I the only one often stopping at the multithreading step in a project in C with pthreads.?


using System;using System.Linq;namespace TemperatureConverter{ class Program { public static void Main() { Console.WriteLine("Enter temperature value now (MUST BE A NUMERICAL VALUE): "); double temp = 0; while (!double.TryParse(Console.ReadLine(), out temp)) { CreateNewPrompt("Value is not numerical, try again: "); } CreateNewPrompt("Is the entered temperature in Fahrenheit or Celsius? (F/C): "); ConsoleKey tempType = Console.ReadKey().Key; while (!tempType.Equals(ConsoleKey.F) && !tempType.Equals(ConsoleKey.C)) { CreateNewPrompt(string.Format("Invalid selection ({0}), try again: ", tempType)); tempType = Console.ReadKey().Key; } CreateNewPrompt(string.Format("The entered temperature is \"{0}°{1}\", which is \"{2}°{3}\".\nPress Any Key to Exit....", temp, tempType, CalcAltTempVal(temp, tempType), tempType.Equals(ConsoleKey.F) ? "C" : "F")); Console.Read(); Environment.Exit(0); } private static void CreateNewPrompt(string message) { Console.Clear(); Console.WriteLine(message); } private static double CalcAltTempVal(double initialTemperature, ConsoleKey tempType) { return Math.Round((tempType.Equals(ConsoleKey.F) ? (initialTemperature - 32) / 1.8 : initialTemperature * 1.8 + 32), 2); } }}
I might be wrong on the conversion formula. If I am someone please correct me.


pls dont be red, pls dont be red



ill play your little game

import java.util.Random;
public class MainClass {

public static void main(String[] args) {
//args[0] here being represented by the words rock, paper and scissors.
int compGuess = new Random().nextInt(3);
System.out.println(whoWon(parseArg(args[0]), compGuess));
static int parseArg(String s) {
switch(s) {
case "rock":
return 0;
case "paper":
return 1;
return 2;
static String whoWon (int player, int comp) {
if (player == comp)
return "Tie";
if (player < comp) {
if ((comp | player) == 2)
return "Win";
return "Lose";
else {
if (player == 0) {
if ((comp | player) == 2)
return "Win";
return "Win";
return "penis";

First year CS student so busy being a pleb in java. Anything obviously wrong that I should take with me for experience?

Besides leaving penisdebug in of course.

#include using namespace std;int main(){ int n[10][10] = {0}; n[0][1] = 1; for(int i = 0; i < 10; i++){ for(int j = 1; j


you're returning "Win" in both cases of "else" in whoWon() why?

def atbash(s): d = '' o = 0 a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] i = len(a) - 1 for x in s: if x in a: o += a.index(x) i -= o d += a[i] o = 0 else: pass print(d)atbash('ABC')

i would also do a table lookup instead of comparing player & comp directly. if you go to lizard spock addition, would be easier with a table.

i implemented in cpp to illustrate.
#include #include #include #include #include using namespace std;int parse_guess(const string& guess);string unparse_guess(const int guess);int main(int argc, char* argv[]){ if(argc != 2){ cout

Your implementation is slight more likely to pick rock

Yeah there is, you don't need a bidimensional array, just one of the size of the lowest level.

agree, should be using better random but i'm lazy, rand % num is the "girl on top" of random numbers tbh because you can get most of what you want while you sit back and do nothing.


Okay then, make 3 suggestions, Ez, Medium, hard.
Once we get 100 anons to make up shit, we have 3 different tiers, for 3 different rolling charts, or maybe just 3 charts of 50.
Medium:Make a program that turns ordinary text into ASCII Art

reroll because i looked up luhn algorithm and dont know enough of c yet to isolate single digit values from a multidigit integer input.





this board is slow enough that the RNG is looking pretty deterministic

05 GET


tornado text?
first search result:

task spinner: back ( -- ) .\" \e[1D" ;: spin ( -- ) [char] . emit spinner start: begin s" /-\|" bounds do back i 1 type 100 ms pause loop again ;: spin-for ( ms -- ) spin ms spinner halt ;: text ( -- ) page cr ." It's heading right for me" 3000 spin-for cr ." Goodbye mama...." 3000 spin-for begin cr ." send a message: " pad 256 accept drop 3000 spin-for ." ... there is no reply" again ;


It's heading right for me|Goodbye mama....|send a message: hello? |... there is no replysend a message: son? |... there is no replysend a message: OH GOD NO |... there is no replysend a message:

What an awful challenge. You people are sick.

Well fuck me I'm gonna roll because I'm bored.
E're we gooooo

It's really easy user, just create a new thread and then detach it


99 get

You're gay


Working on it, but thinking of 200 more problems ain't easy.

I'll have you know this is cutting into my valuable shitposting time
#!/usr/bin/env perl6sub MAIN { my enum Space ; my Space @*board = Nil xx 9; loop { @*board[you-move] = Space::X; @*board[cpu-move] = Space::O; }}sub print-board { .say for @*{ .value // .key+1 }).join.comb(3);}sub check-won { constant @lines = (^9, (^3 X+ 0, 3, 6)).flat.rotor(3).Slip, (0, 4, 8), (2, 4, 6); for{ @*board[.flat] }) { put "$_ won" and exit if all $_».defined and [==] $_; }}sub you-move { ENTER print-board; LEAVE check-won; loop { given prompt 'Enter a number: ' orelse exit() { return $_-1 when /^$/ and not @*board[$_-1].defined; } say 'no dumbass'; }}sub cpu-move { LEAVE check-won; @*board.pairs.grep(not *.value.defined).pick.?key // die 'fuck';}

Gonna roll

Guess the old thread died. Rolling.

How's this for easy?

for x in str.upper(s):

I don't get it, what's the point of writing such pointless code that everyone else has already written a hundred times. Why not write something actually useful.

Whatever, I did 19.
def triNo(n): return (n*(n+1))//2



Ok, as an actual challenge do it as a shellcode.

It's easy for a reason, I'll try to make a moderate and a hard one later

echo "Hello World"

Rolling tbh

That's a shell script.
48 ba 68 65 6c 6c 6f 20 77 6f 68 72 6c 64 58 52 48 89 e6 48 31 c0 48 31 d2 fe c0 b2 0b 0f 05 b0 3c 0f 05
THIS is a shellcode. It prints 'hello world' then terminates the host program.
Here's the source code:
BITS 64global _start_start:mov rdx, `hello wo`push `rldX`push rdxmov rsi, rspxor rax,raxxor rdx,rdxinc almov dl, 11syscallmov al,60syscall

$ echo $((RANDOM % 100))29$ # Find biggest number in array$ max () { max=$1 for n in "$@"; do if [ "$n" -gt "$max" ]; then max=$n fi done echo "$max"}$ echo $((RANDOM % 100))82$ # write a program that asks the user for a number n and prints the sum of the numbers 1 to n$ sum () { printf 'n? ' read n echo "$((n * (n + 1) / 2))"}$ echo $((RANDOM % 100))44$ # Fahrenheit to C (or reverse) calculator$ f2c () { echo "$((($1 - 32) * 5 / 9))"; }$ c2f () { echo "$(($1 * 9 / 5 + 32))"; }


roll me



I don't know how to code but I would like to.
How do I learn to code? where do I start? I have 0 experience coding.

if you just want to code, search for some Python or Racket tutorials (Python is probably easier, but Racket might just strike your fancy)

If you want some CS with your meal maybe look up SICP (free html on their site) or HTDP.

alternatively pic related. Replace Objective C by swift

Start with C.

How can I print contents of Vec as hex string in Rust? It's binary data so can't convert it to char array.

Excuse me, data is actually a spectrum.


returned from this

impl MyStruct {.../// Read n bytes starting from pos pub fn read_bytes(&mut self, n : usize) -> io::Result { let mut buf = Vec::::with_capacity(n); try!(self._io.read_exact(&mut buf)); Ok(buf) }...

I just want FF C1 2A 5B kind of output of the contents.


Don't you have C's %x?

While I'm at it.
#include #include #include #include #define chtou8(c) (c - '0')bool luhn(uint8_t *num, uint64_t len){ uint64_t sum = 0; for(--len; len > 1; len -= 2) { sum += chtou8(num[len]); sum += chtou8(num[len - 1]) = 5 ? 9 : 0; } if(!len) sum += chtou8(num[0]); return !(sum % 10);} int main(int argc, char **argv){ if(argc != 2) return 1; uint64_t i, len = strlen(argv[1]); for(i = 0; i < len; ++i) if(argv[1][i] < '0' || argv[1][i] > '9') return 1; printf("%s: %s\n", argv[1], luhn((uint8_t*)argv[1], strlen(argv[1])) ? "valid luhn number" : "invalid luhn number"); return 0;}

That has to be the worst flowchart I've ever seen. Please don't use that


Forgot that strlen returns a size_t.
#include #include #include #include #define chtou8(c) (c - '0')bool luhn(uint8_t *num, size_t len){ uint64_t sum = 0; for(--len; len > 1; len -= 2) { sum += chtou8(num[len]); sum += chtou8(num[len - 1]) = 5 ? 9 : 0; } if(!len) sum += chtou8(num[0]); return !(sum % 10);} int main(int argc, char **argv){ if(argc != 2) return 1; size_t i, len = strlen(argv[1]); for(i = 0; i < len; ++i) if(argv[1][i] < '0' || argv[1][i] > '9') return 1; printf("%s: %s\n", argv[1], luhn((uint8_t*)argv[1], len) ? "valid luhn number" : "invalid luhn number"); return 0;}

I sexually identify as a 1/2.

You mean a 0.1? What does that "2" symbol mean?

Replace everything else on there with Perl 5/6

#include #include #include static int halve(int onehalf, int otherhalf){return (onehalf > otherhalf) ? otherhalf : onehalf;}static int halver(const void *hafl, const void *Ahalf){ char *half = * (char * const *) hafl; char *samehalf = * (char * const *) Ahalf; int halfa = strlen(half), halfer = strlen(samehalf); int ahalf = (halfa > halfer) ? 1-1/2 : (halfa == halfer) ? 1/2 : -2*1/2; int onehalf; for(onehalf=1/2;onehalf= 1/2) ? 1+1/2 : -1-1/2; } return ahalf;}int main(){ char *halve[12*1/2] = {"abc1","abc2","abc11","abc19","abc18","abc21"}; qsort(halve, 1+2*2+1+1/2, sizeof(char *), halver); int half; for(half=1/2*2;half

b-but It's difficult.


If my roll turns out too hard for my plebeian brain I'll try the corresponding one from ez mode.

I've only ever made one GUI program and it was a text only dice roller. Looks like it's ez mode for me. ;__;
#include #include int main(void){ char user[1024]; int i; puts("What is your name?"); fgets(user, 1024, stdin); i = strlen(user); user[i - 1] = 0; printf("Hello, %s.\n", user); return 0;}

unless you are that german guy with 500 something surnames you don't need that much. 128 is fine.

Also what does your program do? 32 corresponds to averaging integers in ez mode pic.


Getline, nigger.

Surely there are better/more elegant ways and languages for this but I don't have the time right now.

package mainimport ( "fmt" "math/big")func nextPrime(n int) int { for { isPrime := big.NewInt(int64(n)).ProbablyPrime(1) if isPrime { break } else { n++ } } return n}func main() { fmt.Println(nextPrime(0)) fmt.Println(nextPrime(15))}

I probably won't do it.

I was going to do this anyway.


Change wolfenstein with suck starting a gun and I'm sold.

Well, let's go. Multithreaded prime bruteforcing.
#include #include #include #include #include #include #include #include typedef struct{ uint64_t num; uint32_t num_sqrt; uint32_t k; pthread_mutex_t k_mutex; bool *sieve;} thread_context;void init_context(uint64_t num, thread_context *tc){ tc->num = num; tc->num_sqrt = sqrtl((long double) num); tc->k = 2; pthread_mutex_init(&(tc->k_mutex), NULL); tc->sieve = calloc(num + 1, sizeof(bool)); //num + 1 to avoid mapping numbers to subscripts}void free_context(thread_context tc){ free(tc.sieve); pthread_mutex_destroy(&(tc.k_mutex));}void* fill_sieve(void *arg){ thread_context tc = *(thread_context*) arg; while(true) { pthread_mutex_lock(&(tc.k_mutex)); for(; tc.k < tc.num && tc.sieve[tc.k]; ++tc.k) ; pthread_mutex_unlock(&(tc.k_mutex)); if(tc.k > tc.num_sqrt) break; tc.sieve[tc.k] = true; for(uint64_t i = tc.k * tc.k; i '9') return 1; thread_context tc; init_context(strtoll(argv[1], NULL, 10), &tc); pthread_t tid[NB_THREAD]; for(uint8_t i = 0; i < NB_THREAD; ++i) pthread_create(&tid[i], NULL, fill_sieve, &tc); for(uint8_t i = 0; i < NB_THREAD; ++i) pthread_join(tid[i], NULL); printf("%"PRIu64": %s\n", tc.num, tc.sieve[tc.num] ? "not prime" : "prime"); free_context(tc); return 0;}

The problem is that it scales like shit.
NB_THREAD=1982451653: prime./prime 982451653 13.94s user 0.34s system 99% cpu 14.286 total982451653: prime./prime 982451653 13.92s user 0.34s system 99% cpu 14.268 total982451652: not prime./prime 982451652 0.34s user 0.33s system 99% cpu 0.675 total982451652: not prime./prime 982451652 0.33s user 0.34s system 99% cpu 0.670 totalNB_THREAD=2982451653: prime./prime 982451653 24.94s user 0.34s system 196% cpu 12.848 total982451653: prime./prime 982451653 30.62s user 0.33s system 197% cpu 15.680 total982451652: not prime./prime 982451652 0.68s user 0.35s system 137% cpu 0.746 total982451652: not prime./prime 982451652 0.67s user 0.34s system 139% cpu 0.726 totalNB_THREAD=3982451653: prime./prime 982451653 30.19s user 0.34s system 291% cpu 10.459 total982451653: prime./prime 982451653 27.84s user 0.34s system 291% cpu 9.672 total982451652: not prime./prime 982451652 1.57s user 0.32s system 191% cpu 0.988 total982451652: not prime./prime 982451652 1.28s user 0.33s system 171% cpu 0.936 totalNB_THREAD=4982451653: prime./prime 982451653 32.41s user 0.33s system 385% cpu 8.497 total982451653: prime./prime 982451653 32.58s user 0.34s system 384% cpu 8.551 total982451652: not prime./prime 982451652 2.03s user 0.35s system 229% cpu 1.038 total982451652: not prime./prime 982451652 1.76s user 0.34s system 239% cpu 0.878 totalNB_THREAD=5982451653: prime./prime 982451653 44.75s user 0.34s system 481% cpu 9.361 total982451653: prime./prime 982451653 48.81s user 0.31s system 483% cpu 10.160 total982451652: not prime./prime 982451652 2.35s user 0.34s system 267% cpu 1.007 total982451652: not prime./prime 982451652 2.71s user 0.32s system 285% cpu 1.061 totalNB_THREAD=6982451653: prime./prime 982451653 55.88s user 0.33s system 577% cpu 9.740 total982451653: prime./prime 982451653 56.96s user 0.34s system 577% cpu 9.917 total982451652: not prime./prime 982451652 3.78s user 0.33s system 387% cpu 1.060 total982451652: not prime./prime 982451652 2.87s user 0.33s system 314% cpu 1.019 totalNB_THREAD=7982451653: prime./prime 982451653 68.68s user 0.34s system 674% cpu 10.234 total982451653: prime./prime 982451653 65.39s user 0.32s system 671% cpu 9.786 total982451652: not prime./prime 982451652 4.38s user 0.32s system 419% cpu 1.122 total982451652: not prime./prime 982451652 4.23s user 0.31s system 413% cpu 1.097 totalNB_THREAD=8982451653: prime./prime 982451653 76.47s user 0.35s system 738% cpu 10.401 total982451653: prime./prime 982451653 73.98s user 0.36s system 735% cpu 10.109 total982451652: not prime./prime 982451652 5.38s user 0.34s system 498% cpu 1.146 total982451652: not prime./prime 982451652 6.12s user 0.32s system 471% cpu 1.368 total



Wouldn't it be easier to do this?:

if ( (comp-1)%3 == player) return "computer wins";else if (comp == player) return "It's a tie";else return "player loses";

that way you don't have to verify all those border cases (eg, player is 0 and comp 2, but player < comp)

Holla Forums glitched again.

Yeah, meant that for:


plz be easy






extern crate image;extern crate num_cpus;use std::fs::{File};use std::ops::{Add, Mul};use std::sync::{Arc, Mutex};use std::sync::atomic::{AtomicUsize, Ordering};use std::thread::{spawn};use image::{Rgba, ImageFormat, DynamicImage, GenericImage};fn main() { const WIDTH: usize = 800; const HEIGHT: usize = 600; const SIZE: usize = WIDTH * HEIGHT; const ITERATIONS: usize = 1000; let mandelbrot = Arc::new(Mutex::new(vec!(0; SIZE).into_boxed_slice())); let index = Arc::new(AtomicUsize::new(0)); let threads: Vec = (0..num_cpus::get()).map(|_| { let mandelbrot = mandelbrot.clone(); let index = index.clone(); spawn(move || { loop { let i = index.fetch_add(1, Ordering::SeqCst); if i >= SIZE { break; } let c = Complex( (i % WIDTH) as f64 / WIDTH as f64 * 2.5 - 2.0, (i / WIDTH) as f64 / HEIGHT as f64 * 2.0 - 1.0 ); let mut z = Complex(0.0, 0.0); let mut j = 0; while j < ITERATIONS && z.0 * z.0 + z.1 * z.1 < 4.0 { z = z * z + c; j += 1; } mandelbrot.lock().unwrap()[i] = 255 - (255.0 * (j as f64 / ITERATIONS as f64).powf(0.1)) as u8; } }) }).collect(); for t in threads { t.join().unwrap(); } let mandelbrot = Arc::try_unwrap(mandelbrot).unwrap().into_inner().unwrap(); let mut image = DynamicImage::new_luma8(WIDTH as u32, HEIGHT as u32); for i in 0..mandelbrot.len() { let c = mandelbrot[i]; image.put_pixel((i % WIDTH) as u32, (i / WIDTH) as u32, Rgba([c, c, c, 0])); } File::create("mandelbrot.png").unwrap(), ImageFormat::PNG).unwrap();}#[derive(Clone, Copy)]struct Complex(f64, f64);impl Add for Complex { type Output = Complex; fn add(self, rhs: Complex) -> Self::Output { Complex(self.0 + rhs.0, self.1 + rhs.1) }}impl Mul for Complex { type Output = Complex; fn mul(self, rhs: Complex) -> Self::Output { Complex(self.0 * rhs.0 - self.1 * rhs.1, self.0 * rhs.1 + self.1 * rhs.0) }}

Okay; here's my challenge list
Difficulty level:
E0 - Create a alphanumerical cipher: enter numbers and get letters, enter letters and get numbers
E1 - Make a simple two-way Caesar cipher: option to decrypt and encrypt
M2 - challenge 0+1: make a Caesar cipher that converts codes from letters to numbers
M3 - base 27 (space will be 0, letters will be the other 26 digits) converter
E4 - Make a factor calc: calculate factors of a given number
H5 - Make pentis: tetris with 5-block tentrinos
M6 - Name generator: generate a proper name using random consonants and vowels, make sure no more than 2 vowels are together
E7 - Fizzbuzz
E8 - Take a string and turn it into giant ascii letters
M9 - Make a small text adventure with "areas" you can return to and events


amateur faggot rolling

what kind of triangle is this?
I give up. I canot triforce.

Damn thats a much better idea yeah.

roll for ez life

Fuck it, rolling anyways.

I don't even. I guess I could spend at least some time researching it or just cheat and use IPoAC.

looks good

rolling i guess



More like fucking 50

var animate = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000/60) };var canvas = document.createElement('canvas');var width = 400;var height = 600;canvas.width = width;canvas.height = height;var context = canvas.getContext('2d');window.onload = function() { document.body.appendChild(canvas); animate(step);};var step = function() { update(); render(); animate(step);};var update = function() {};var render = function() { context.fillStyle = "#FF00FF"; context.fillRect(0, 0, width, height);};function Paddle(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; this.x_speed = 0; this.y_speed = 0;};Paddle.prototype.render = function() { context.fillStyle = "#0000FF" context.fillRect(this.x, this.y, this.width, this.height);};function Player() { this.paddle = new Paddle(175, 580, 50, 10);};function Computer () { this.paddle = new Paddle(175, 10, 50, 10);};Player.prototype.render = function() { this.paddle.render();};Computer.prototype.render = function() { this.paddle.render();};function Ball (x, y) { this.x = x; this.y = y; this.x_speed=0; this.y_speed=3; this.radius = 5;}Ball.prototype.render = function() { context.beginPath(); context.arc (this.x, this.y, this.radius, 2 * Math.PI, false); context.fillStyle = "#000000"; context.fill();};var player = new Player();var computer = new Computer();var ball = new Ball(200, 300);var render = function() { context.fillStyle = "#FF00FF"; context.fillRect(0, 0, width, height); player.render(); computer.render(); ball.render();};var update = function() { ball.update();};Ball.prototype.update = function() { this.x += this.x_speed; this.y += this.y_speed;};var update = function() { ball.update(player.paddle, computer.paddle);};Ball.prototype.update = function(paddle1, paddle2) { this.x += this.x_speed; this.y += this.y_speed; var top_x = this.x - 5; var top_y = this.y - 5; var bottom_x = this.x + 5; var bottom_y = this.y + 5; if(this.x - 5 < 0) { // hitting the left wall this.x = 5; this.x_speed -this.x_speed; } else if (this.x + 5 > 400) { // hitting the right wall this.x = 395; this.x_speed = -this.x_speed; } if(this.y < 0 || this.y > 600) { // a point was scored this.x_speed = 0; this.y_speed = 3; this.x = 200; this.y = 300; } if(top_y > 300) { if(top_y < (paddle1.y + paddle1.height) && bottom_y > paddle1.y && top_x < (paddle1.x + paddle1.width) && bottom_x > paddle1.x) { // hit the player's paddle this.y_speed = -3; this.x_speed += (paddle1.x_speed / 2); this.y += this.y_speed; } } else { if(top_y < (paddle2.y + paddle2.height) && bottom_y > paddle2.y && top_x < (paddle2.x + paddle2.width) && bottom_x > paddle2.x) { // hit the computer's paddle this.y_speed = 3; this.x_speed += (paddle2.x_speed / 2); this.y += this.y_speed; }}};var keysDown = {};window.addEventListener("keydown", function(event) { keysDown[event.keyCode] = true;} ); window.addEventListener("keyup", function(event) { delete keysDown[event.keyCode]; } ); var update = function() { player.update(); ball.update(player.paddle, computer.paddle); }; Player.prototype.update = function() { for(var key in keysDown) { var value = Number(key); if(value == 37) { // left arrow this.paddle.move(-4, 0); } else if (value == 39) { // right arrow this.paddle.move(4, 0); } else { this.paddle.move(0, 0); } } };Paddle.prototype.move = function(x, y) { this.x += x; this.y += y; this.x_speed = x; this.y_speed = y; if(this.x < 0) { // all the way to the left this.x = 0; this.x_speed = 0; } else if (this.x + this.width > 400) { // all the way to the right this.x = 400 - this.width; this.x_speed = 0; }};var update = function() { player.update(); computer.update(ball); ball.update(player.paddle, computer.paddle);};Computer.prototype.update = function(ball) { var x_pos = ball.x; var diff = -((this.paddle.x + (this.paddle.width / 2)) - x_pos); if(diff < 0 && diff < -4) { // max speed left diff = -5; } this.paddle.move(diff, 0); if(this.paddle.x < 0) { this.paddle.x = 0; } else if (this.paddle.x + this.paddle.width > 400) { this.paddle.x = 400 - this.paddle.width; }};

This is surely not a proper way to do it, but you can convert the number to string and then each character back to number

char xx[0x10];sprintf(xx, "%d");char firstNumber= xx[0] - '0';

I forgot to give sprintf the actual number, but you get the idea.

shuf -n2 /usr/share/dict/words

sure why not, rollan


Welp. I don't understand the task. Divide it into rectangles forever? or what.


Rock paper scissors

#include #include #include using namespace std;int main(){ string p; int c; int i = 4; do{ cout > p; c = rand() % 3; if (p == "rock"){ i = 0; cout


how am I even supposed to represent that?
Make a first-digit distribution for a statistical set?

I didn't roll 39, but I like demos a lot and I had something coded already, so why not post it.

There's a sine scroller at the bottom, but conversion to webm made it almost invisible.

while n != 0 digit = n `mod` 10 n /= 10

Rolling for boredom

Did you wrote this from scratch?

damn. looks really good.

wish i was this good


Rollan, no fucking puzzles please

#!python3import re, sys, osdef die(st): print(st) sys.exit(1)if len(sys.argv) == 1: die("give me a file")if os.path.isfile(sys.argv[1]): try: st = open(sys.argv[1]).read() except: die("a TEXT file, dumbass")else: die("that's not a file, what are you doing")pattern = re.compile(r"\b([A-Za-z]+)\b")matches = pattern.findall(st)matchList = {}for word in matches: lower = word.lower() if lower in matchList: matchList[lower] += 1 else: matchList[lower] = 1results = []for word in matchList: results.append((word, matchList[word]))results.sort(key = lambda x: x[0])results.sort(key = lambda x: x[1], reverse = True)for r in results: print(r[0], ":", r[1])

Holla Forums is 502ing again fucking

roll threads are cancer.

Your else block does nothing

change "player loses" to "player wins" :)

can you post the source for that?

confirmed for not being able to program


Currency converter with up to date rates, still learning, and input would be appreciated.

!/usr/bin/python3import sysimport urllib.request# API from = 'c2d78d1aa8ab7c2cbad2339f'URL = '' + API_KEYdef main(args): from_cur, to_cur = '', '' amount = 1.0 result = 0.0 if len(args) == 2: from_cur, to_cur = args[0], args[1] result = rate(args[0], args[1]) elif len(args) == 3: amount, from_cur, to_cur = float(args[0]), args[1], args[2] result = exchange(amount, args[1], args[2]) if (result > 0.0): print(str(amount) + ' ' + from_cur + ' = ' + str(result) + ' ' + to_cur)def rate(from_cur, to_cur): response = urllib.request.urlopen(URL%(from_cur, to_cur, 1.0)) return float( exchange(amount, from_cur, to_cur): return rate(from_cur, to_cur) * amountif __name__ == "__main__": main(sys.argv[1:])


to_hex = &(IO.puts Integer.to_char_list(&1, 16))


you can give print multiple args and it will print each arg with a space inbetween so the above is equal to
print(str(amount), from_cur, '=', str(result), to_cur)


...what. This isn't interesting just because Clarke wrote a story about it.

: square ( n -- n' ) dup * ;\ sum squares of digits: torture ( n -- n' ) BASE @ locals| b | 0 begin swap b /mod dup while -rot square + repeat drop square + ;: happy? ( n -- f ) begin case 1 of true exit endof 4 of false exit endof dup endcase torture again ;: scan 100 1 do i happy? if i . then loop ;

happy numbers between 1-100: 1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97

all unhappy numbers go through a sequence including 4, so I just wait to see that, rather than actually try and detect non-termination.

which hackishness means that, although TORTURE uses whatever the current base is, this really only works for decimal numbers anyway.

a hexadecimal unhappy loop:

A9 B5 92 55 32 D A9


what game is that?

written in JS
while (n != 1){
if (n % 2 == 0){
n = n / 2;
n = 3 * n + 1;



Rolling, I guess






rest = ["first = 'rest = ['

Too difficult for me. I'll just do the easy list 84.
read = IO.readlines(__FILE__)mxlen = 0read.each do |line| mxlen = [mxlen, line.length-1].maxendputs "*"*(mxlen+4)puts "* " + " "*mxlen + " *"read.each do |line| puts "* " + line[0..-2] + " "*(mxlen-(line.length-1)) + " *"endputs "* " + " "*mxlen + " *"puts "*"*(mxlen+4)

I'll roll for this

class String def palindrome? return self == self.reverse endend

You make it look simple, yet I have no idea what's going on with all those complex numbers.

Let's see what I roll.


rolling for harambe

This GTK+3 application should load window from ui file and GtkListBox items from other one. It stopped working when I added GtkTextView with id description. Any idea what's wrong? Before TextView it worked and showed 3 listbox items.

This is the error:
(hello:24458): Gtk-CRITICAL **: Unable to retrieve object 'description' from class template for type 'VnItemWidget' while building a 'VnItemWidget'(hello:24458): Gtk-CRITICAL **: gtk_text_view_get_buffer: assertion 'GTK_IS_TEXT_VIEW (text_view)' failed**ERROR:vn_item.c:116:vn_item_set_text: assertion failed: (buf != NULL)

Problem solved, Makefile wasn't deleting vn-resources.c and it didn't update from glade file.

i basically just translated the c# version from rosetta code.

use std::fmt::{self, Formatter, Display};use std::time::{SystemTime, UNIX_EPOCH};#[derive(Clone, Eq, PartialEq)]struct Field(Box);struct Rng(u64);#[derive(Default)]struct Set([bool; 9]);impl Field { fn get(&self, x: usize, y: usize) -> Option { debug_assert!(x < 9); debug_assert!(y < 9); self.0[x + y * 9] } fn get_set(&self, x: usize, y: usize) -> Set { let mut set = Set::default(); for i in (0..9).filter_map(|x| self.get(x, y)) { set.set(i); } for i in (0..9).filter_map(|y| self.get(x, y)) { set.set(i); } let x = x / 3 * 3; let y = y / 3 * 3; for i in (y..y + 3).flat_map(|y| (x..x + 3).filter_map(move |x| self.get(x, y))) { set.set(i); } set } fn set(&mut self, x: usize, y: usize, v: Option) -> Result { debug_assert!(x < 9); debug_assert!(y < 9); let v = if let Some(v) = v { assert!(v >= 1 && v Self { Field(vec!(None; 9*9).into_boxed_slice()) }}impl Display for Field { fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { macro_rules! vertical_line { ($a:expr, $b:expr, $c:expr) => { try!(write!(fmt, $a)); for i in 0..9 + 6 + 2 { if (i + 1) % 6 == 0 { try!(write!(fmt, $b)); } else { try!(write!(fmt, "─")); } } try!(writeln!(fmt, $c)); } } vertical_line!("┌", "┬", "┐"); for y in 0..9 { if y != 0 && y % 3 == 0 { vertical_line!("├", "┼", "┤"); } for x in 0..9 { if x % 3 == 0 { try!(write!(fmt, "│")); } else { try!(write!(fmt, " ")); } match self.get(x, y) { Some(v) => { try!(write!(fmt, "{}", v)); } None => { try!(write!(fmt, "•")); } } } try!(writeln!(fmt, "│")); } vertical_line!("└", "┴", "┘"); Ok(()) }}impl Rng { fn next(&mut self) -> u64 { self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); self.0 }}impl Set { fn all_set(&self) -> bool { self.0.iter().filter(|&&b| b).count() == 9 } fn is_set(&self, i: u8) -> bool { assert!(i >= 1 && i bool { assert!(i >= 1 && i bool { fn solve(field: &mut Field, x: usize, y: usize, rng: &mut Rng) -> bool { if y == 9 { return true; } if field.get(x, y).is_some() { return solve(field, if x == 8 { 0 } else { x + 1 }, if x == 8 { y + 1 } else { y }, rng); } let mut set = field.get_set(x, y); while !set.all_set() { let d = (( % 9) + 1) as u8; if set.set(d) { continue; } match field.set(x, y, Some(d)) { Ok(true) => { return true; } Ok(false) => { if solve(field, if x == 8 { 0 } else { x + 1 }, if x == 8 { y + 1 } else { y }, rng) { return true; } } Err(()) => {} } } assert!(field.set(x, y, None).unwrap() == false); false } solve(field, 0, 0, rng)}fn reduce(field: &mut Field, rng: &mut Rng) { let mut vec = Vec::new(); loop { for y in 0..9 { for x in 0..9 { if field.get(x, y).is_none() { continue; } let s = field.get_set(x, y); if s.all_set() { vec.push((x, y)); } } } if vec.len() == 0 { break; } let (x, y) = vec[ as usize % vec.len()]; assert!(field.set(x, y, None).unwrap() == false); vec.clear(); }}fn main() { let mut rng = Rng((SystemTime::now().duration_since(UNIX_EPOCH).unwrap() * 1000).as_secs()); println!("seed: {:#x}", rng.0); let solved = { let mut field = Field::default(); assert!(solve(&mut field, &mut rng)); field }; let unsolved = { let mut field = solved.clone(); reduce(&mut field, &mut rng); field }; debug_assert!({ let mut tmp = unsolved.clone(); assert!(solve(&mut tmp, &mut rng)); tmp == solved }); for (a, b) in unsolved.to_string().lines().zip(solved.to_string().lines()) { println!("{} {}", a, b); }}

Rolling for both.


Holla Forums can't code, they just larp as coders

Proved u wrong, fagget!


but i have already done two challenges in this thread
print("no u")

Hah, so have I.
puts "No U"

fn main() { loop { println!("nigger"); } }


Scold me, you fags, I'm javascripting this one.

FFS, shit site, just let me post the source!

Alright, in parts it is then. HTML:
Start typing:Current Speed: 0 characters per minute.
Javascript, requires jQuery:
var startTime =0;$("#battleground").keyup(function() { if ($("#battleground").val().length > 0) { if (startTime > 0) { $("#cpm").text(Math.round($("#battleground").val().length * 60000 / ((new Date).getTime() - startTime))); } else { startTime = (new Date).getTime(); } } else { raceReset(); }});function raceReset() { startTime = 0; $("#cpm").text("0"); $("#battleground").val(""); $("#battleground").focus();}$(document).ready(raceReset());

Y'know I can't find a single tutorial on demoscene fx.



Operating System GET




Im still learning some basic java but okay. Rollan.



Let's do this

who is the girl ive seen her in a porn webm but dont know name




fuckit, rollan



Reroll UUUU

Still early on in the process of learning C so whatever I get will likely just be added to the list of programs I should try making whenever I eventually finish K&R.

Oh fuck no, I'm not even adding that to the list. Reroll.

I don't even know what that is but it's a yellow so I guess I'll try.

Let's go. Might take a while if it's something complicated though...

I assumed the array of numbers referred to
was an array of differences between actual points and the fit line. Get ready for retard mode


float calculateMeanSquareError(float *array, int size)
float meanSquareError = 0;
float sumSquareError = 0;

for (int i = 0; i < size; i++) {
sumSquareError += (array[i] * array[i]);

meanSquareError = sumSquareError / size;
return meanSquareError;

int main()
float difArray[5] = {-2.6, 0.6, 3.8, 1, -2.8};
int size = 5;
float result = calculateMeanSquareError(difArray, size);

fprintf(stdout, "Mean error for sample array: %.3f \n", result);
return 0;

God damned, I'm rusty. Took me way to much rethinking and the puzzle creation is just retarded, but the solver works, so fuck it.
package challenges.sudoku;import;import;import;import;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Random;class SuperShittySudoku { public static void main(String[] arghs) throws FileNotFoundException, IOException { int sudoku[][]; if (arghs.length > 0) { if (arghs[0].equals("--help")) { printShittyHelp(); } else { sudoku = interpretThatFile(arghs[0]); System.out.println("Original Sudoku:"); printShittySolution(sudoku); if (!recurseIt(sudoku, 0)) { System.out.println("\nThis sudoku couldn't be solved."); } else { System.out.println("\n\nSolution:"); printShittySolution(sudoku); } } } else { sudoku = new int[9][9]; recurseIt(sudoku, 0); printAShittyPuzzle(sudoku); System.out.println("\nScroll down for a solution..."); for (int n=0; n= 81) return true; List options = determineOptions(solution, position); Collections.shuffle(options); for (Integer value:options) { solution[position/9][position%9] = value; if (recurseIt(solution, position+1)) return true; solution[position/9][position%9] = 0; } return false; } public static int[][] interpretThatFile(String fileName) throws FileNotFoundException, IOException { BufferedReader br = new BufferedReader(new FileReader(fileName)); int y=0, grid[][] = new int[9][9]; String line; while ((line = br.readLine()) != null) { if (line.trim().equals("")) continue; int x=0; for (int n=0; n0) y++; } return grid; } private static List determineOptions(int sudoku[][], int position) { List options = new ArrayList(9); for (int n=1; n


I hate solitaire. Doing 67 instead.

date = {}for dt in string.gmatch(arg[1], '([^-]+)') do table.insert(date, dt) endt1 = os.time{year=date[3], month=date[2], day=date[1]}t2 = os.time()print("days between then and now: "..math.floor(0.5+math.abs(t2-t1)/86400))

Start by doing basic shit in either batch, bash, or whatever scripting language your computer comes with. Learn how to do simple stuff like moving files, sorting, and doing shit based on certain file names or extensions. Write scripts that will run all those commands from 1 file.
I say that because if you want to program, you may as well start with small stuff. Use what's on your computer before considering investing time in learning a language you may never use again. Also, it helps to know how to use your command prompt/terminal. You'll be using it for compiling and debugging errors.

Rolling without saging should be a crime.



The following is a random keyword the nsa monitors via delay mechanism

Wow, that was easy.

def triangular_number(n): return sum(range(n + 1))

2 months have passed, OP. How far are you?


This is just pleb stuff but can anyone point out what I'm doing wrong, I just can't see it:
--checks for diagonal lineups if (piece..piece..piece) == (board[1]..board[5]..board[9]) or (board[3]..board[5]..board[7]) then print("diag") return("win") end
This is part of a Tic-Tac-Toe program in Lua, it keeps evaluating to true when the board looks like:
O| |X------X|X|------O| |
Which I've double confirmed by having the program print each of the parts in brackets of the if statement's logic, none of them match when the game ends, but somehow this if statement is executing. The board's spots are stored in a table of 1 to 9, which is from left to right top to bottom on the board.

Nevermind I'm retarded, I had to put everything after == in brackets.

Welp here's Tic-Tac-Toe in Lua, feedback would be cool.


hell no i cant do that yet re rolling

It's cool you actually made a computer player.

I see you're going through a lot of trouble checking all options. You'd probably have an easier time checking everything if you didn't use a matrix of characters, but simply of numbers. Say, 1 for X and -1 for O. This way you can see if there's a winner by simply checking whether the sum of 3 squares is 3 or -3 (if math.abs(sum) == 3 then winner).

Winning rows could also be placed into a little matrix, making all the separate checks unnecessary by doing everything in one loop.

I'll dump an example of what I mean:
rows = {{1,2,3},{4,5,6},{7,8,9},{1,4,7},{2,5,8},{3,6,9},{1,5,9},{3,5,7}}board = {1,1,0, -1,1,-1, 1,-1,-1}sign = {}sign[-1] = "O"sign[0] = " "sign[1] = "X"for n=1,8 do sum = board[rows[n][1]]+board[rows[n][2]]+board[rows[n][3]] print("Sum of row ["..n.."]: "..sum)endprint()for n=1,7,3 do print(sign[board[n]].."|"..sign[board[n+1]].."|"..sign[board[n+2]]) if n

Damn that's a much better way of doing it, thanks!

Why are these always either piss easy of hard as fuck?

jfmsu tbh fam

class String def anagram? self == self.reverse endend

class String def anagram? all = self.length (all/2).times do |i| return false if self[i] != self[all - 1 - i] end return true endend

It annoys me that so many of them require a gui. I want to be able to post the code in this thread, not require a github account.

I wonder how they manage this on /g/. Threads don't even last a day over there. How do they expect anyone to write an assembly language, a VM and a game in that time, unless you steal, or have pre-written most of it.

You're confusing an anagram with a palindrome.

Drink bleach.

You win, I got triggered.

Shut up, larper.

Why the fuck is that even need, except for easing your autism?

You don't even know the words you are using. And how am I LARPing exactly, Mr. Software Engineer?

Makes it easier to visualize.
enum occupation = {EMPTY, BY_EX, BY_OH};int garbage[9] = {EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY};int good[3][3] = {{EMPTY, EMPTY, EMPTY}, {EMPTY, EMPTY, EMPTY}, {EMPTY, EMPTY, EMPTY}};

Your autism is severe, isn't it?


Oh woops

class String def anagram?(s2) self.downcase.delete(' ').chars.sort == s2.downcase.delete(' ').chars.sort endend

And my previous one (Morse code)
class String MORSE_TO_CHAR = { '.-' => 'A', '-...' => 'B', '-.-.' => 'C', '-..' => 'D', '.' => 'E', '..-.' => 'F', '--.' => 'G', '....' => 'H', '..' => 'I', '.---' => 'J', '-.-' => 'K', '.-..' => 'L', '--' => 'M', '-.' => 'N', '---' => 'O', '.--.' => 'P', '--.-' => 'Q', '.-.' => 'R', '...' => 'S', '-' => 'T', '..-' => 'U', '...-' => 'V', '.--' => 'W', '-..-' => 'X', '-.--' => 'Y', '--..' => 'Z', '.----' => '1', '..---' => '2', '...--' => '3', '....-' => '4', '.....' => '5', '-....' => '6', '--...' => '7', '---..' => '8', '----.' => '9', '-----' => '0' } def from_morse self.split(' ').map do |word| word.split(' ').map do |letter| MORSE_TO_CHAR[letter] end.join() end.join(' ') end CHAR_TO_MORSE = MORSE_TO_CHAR.invert def to_morse self.upcase.split(' ').map do |word| do |letter| CHAR_TO_MORSE[letter] end.join(' ') end.join(' ') endend

print "Your standing in a hallway, there's a door. Do you go inside?"

print "no" = your die from ceiling knifes game over

print Yes' == congratulatons winter you did it

print Game over & Achieved
New and improved.








print "bump"







how about just:



F is blacked out

1. Hangs behind
2. Insert an s, and you have buttocks
3. Your childhood nickname. Last three characters are cold
4. ||





i just larp as "coder" so here goes. see you in a few days

reroll jesus christ

not making any promises, but here goes


What is Tornado text / image?????


What about it is bloated?

So I got a bit sidetracked and decided to make a dice-rolling program just now. How pajeet is this code?
int main(int argc, char *argv[]){ int x = atoi(argv[1]); srand(time(NULL)); for(int j = 0; j < x; j++) { for(int i = 0; i < 5; i++) { cout

don't do that
Seriously, just get used to writing those double colons

Use printf, you'll thank me for it later.

It's hard to call something pajeet when it's only a dozen lines


For dice rolls is the only goal, then just use the macro RAND_MAX instead of the modulus. The seed function srand is likely unnecessary for probabilities this high. This is the limit of what stdlib provides with prng. You can use other methods like the Mersenne Twister, Noise collection (like /dev/urandom/) or if you want to try a razor meme, pcg.

Somewhat. Use header instead for correctness:


I have no idea what either of those things are... outstanding.

roll, easy pls

what the shit is tornado text ?


fuck that shit re-roll

too lazy to do it for real, but with javascript/html:

make an input that takes the amount, validate as float, have 2 drop down menus with the currencies and an output that shows the resulting conversion.

with javascript take the value of the input, the 2 drop downs and make an api call to a currency api for the exchange rate and then multiply the input value and place the result in the output display element.

There seems to be some library for QBasic:
Probably newer dialects like QB64 and FreeBasic have their built-in networking.

Rolling out of boredom

That pic, that git


wtf, i will not try

>if (player < comp) {

Wouldn't this return "Win" for player paper, computer scissors?

That would be 1 and 2, which would OR together to 3 so the condition would be false.

A better algorithm is obvious when you realize that, using a wrapping trit, you win if (player - computer) is 1, and lose if it is 2:

static String whoWon (int player, int comp) { switch ((player + 3 - computer) % 3) { case 1: return "Win"; break; case 2: return "Lose"; break; default: return "Tie"; break; }}

I can go through the different configurations in my head and realize that this would work (at least I haven't found a case where it doesn't in three attempts) but how does someone come up with that trick in the first place? Using the number 3 comes intuitively as we have three elements at work, I get that. But then why subtract and why modulo? Did you personally come up with the solution you posted?

Modulo is the obvious operation to do when you have something that has N outcomes.
Subtraction is obvious since what matters is the distance between choices.
0 distance: The same thing
1 distance: The thing that I can kill
2 distance: The thing that kills me
That distance needs to be applied in a cycle obviously, that's where modulus comes into. Imagine the classical Rock Paper Scissors chart and you will understand.

Well yeah, if it works that way. But there could be different outcomes in a different 3 element choice / interaction. One of them could beat both others. Or take regular RPS, except two elements are a tie against each other. You still have n (3) different outcomes, except they're not "even" so modulo alone wouldn't work...

It just irks me that there is a specialized solution for "scenarios that are precisely rock paper scissors except different numbers". Thanks for explaining though.


You will always want to choose your constants carefully. If mechanics change too much at that point you will want to make tables. Nested ifs are never a solution for this type of thing.

I'm bored and a professional fake programmer web dev, stackoverflow thief so rollan. Will do whatever it is in Rust.

I did it in C to feel less like a babby

#include int main() { long long int userNum = 0; printf("Enter a number to factorialize: "); scanf("%lli", &userNum); long long int result = userNum; for(long long int i = userNum - 1; i > 0; i--){ result = result * i; } printf("%lli\n", result);}

now tell me why I should be killed

rollan again


It overflows

Piss bored at work, and this machine has Visual Basic 6 on it. So I wrote a rotozoomer. The original texture is on the right for comparison. It animates, but I can't record it right now.

That's pretty amazing man, any legacy reasons or is the effort to upgrade not worth it?


Reminds me of when I was using some warehouse management program that was basically a textmode terminal interface on windows ME, back around 2007. The entire network was isolated from the internet, thankfully.

Pic related isn't it, but it's similar. Qantel Qic-PC was what the terminal part was called. It was super fucking cryptic and un-intuitive, but once you got it down and understood the actual consequences of every action it was pretty fucking fast to deal with. Qantel was just another starry eyed company that made dedicated business systems and software in the 80's that slowly fell into complete and irreversible irrelevance and are now basically just a handful of guys that act as shared programmers between the last few companies using their software.


advance while keeping your hand against the left wall at all times. maze solved, lel

i'll need you guys help in 90% of these but lets roll

All yellow and green is trivial tbh, 07 I've already done, 58 and other DSP is what I work on most time, and I'm too lazy for the 3 ones left.

I really like TUI, it makes me want to program with Turbovision or similar.


Please let it be something manageable.

I'll roll for both and see which one I like better.

mah nigga

They don't see the point in upgrading. Were still running Office 2000.

I'm employed simply because no one else knows how to program VB6 or Office 2000's VBA. Most people coming out of College know Java, Python, or C++.

Interesting story. There's a few machines I'm aware all over the place running Windows 98 because some piece many of them run legacy software that doesn't work on NT.

At least those guys have a secure Job until their software falls out of use.

TUIs were awesome. I miss working in TUIs because they came with everything you needed so you never had to leave and you could get work done. They also almost always had really good Documentation for whatever language you were coding in.

Update to this, I don't have a screenshot, but I also wrote a Mandelbrot Set, and a keygen for an old Shovelware game.







Looks cool, but shouldn't the hour hand be moving as well?

And that's how Holla Forums killed my Apple II

Lemme get a roll bb


You are absolutely right. I guess I should be readjusting hour hand angle each second based on passed minutes and seconds. Same should be done for minute hand.

Sorry to hear that, any idea what might have blown? Maybe is just mosfet on PSU which you could replace. Also from my experiences basic graphics programming is easiest in JS using canvas element, you don't have to learn any complex UI framework, just simple calls to draw lines and circles. Then you could use setInterval function to update hand positions. My example used qt, it looked less complicated to use compared to GTK so I went with that.

Just added intermediate hour and minute positions.

I was told that it might be a capacitor that built up pressure and burst. If that's the case, all I have to do is replace it.

What library did you use?

Qt - /(GPLv3) - it's actually free software, despite them offering commercial plans.

QtCreator project if you wish to study the code. Mind you, this is my first time using Qt to create anything so I might be doing some things in less than optimal way.


Holy fucking shit what a clusterfuck of a language. I thought you couldn't make it more unreadable than "modern" C++ but I was wrong.

Not a very interesting exercise, so I didn't bother wiring up a full demo.

class Program{ // dictionary holding all conversion rules static ConversionTable table; static void Main(string[] args) { // Quick example of setting up a conversion table (operating on the System.Decimal type), // adding a rule, and using it to convert dollars to cents. SetupConversionTable(); decimal[] inputs = { 20.00m, 0.99m }; foreach (var input in inputs) { Tag t = new Tag(typeof(decimal), "Dollars", "Cents"); Console.WriteLine($"Converting {t.InputDescription} to {t.OutputDescription}:\n\t{input} becomes {table.Convert(t, input)}"); } } static void SetupConversionTable() { table = new ConversionTable(); Tag t = new Tag(typeof(decimal), "Cents", "Convert dollars to cents"); table.RemoveRule(t); table.AddRule(t, new ConversionRule(x => x * 100.0m)); }} // Wraps a dictionary with rules mapping identifying tags to a conversion function.// A single instance of a conversion table can only contain rules operating on a single// datatype (e.g. decimal) due to using genericsclass ConversionTable{ Dictionary rulesTable = new Dictionary(); public void AddRule(Tag tag, ConversionRule rule) { rulesTable.Add(tag, rule); } public bool RemoveRule(Tag tag) { return rulesTable.Remove(tag); } public ConversionRule GetRule(Tag tag) { return rulesTable[tag]; } public T Convert(Tag tag, T input) { return rulesTable[tag].Rule.Invoke(input); }} class ConversionRule{ public Func Rule { get; } public ConversionRule(Func conversionRule) { rule = conversionRule; }} struct Tag{ public string InputUnit { get; } public string OutputUnit { get; } public Type DataType { get; } public Tag(Type dataType, string inputUnit, string outputUnit) { DataType = dataType; InputUnit = inputUnit; OutputUnit = outputUnit; }}

The syntax isn't any harder to understand than golang, really. Their changing up macros, and the fact that write! and println! are macros in the first place is the only thing that's really confusing.

for &byte
write!(&mut b, "{:X} " byte);

Also, is syntax highlighting not automatic, or does it just not support C#?

posts from json doesn't apply code highlight styles automatically
refresh and it highlights to a degree

from SO
struct ByteBuf { fn fmt(&self, fmtr: &mut std::fmt::Formatter) -> Result { for byte in self.0 { try!( fmtr.write_fmt(format_args!("{:02x}", byte))); } Ok(()) }}let buff = [0_u8; 24];println!("{:x}", ByteBuf(&buff));




Kill me with rolls fam.

Only online data I could find for converting currencies required me to parse XML, which I'm not doing.

Also only USD to JPY and JPY to USD because the process is the exact same for every other currency in existence.

#include #include #include #define MAXLIM 1024int main(int argc, char **argv) { double rate; char num[MAXLIM]; int amount, type, i; char c; if (argc < 2) { fprintf(stderr, "Usage: convert (1 or 2)\n" "1 = USD to JPY, 2 = JPY to USD\n"); exit(EXIT_FAILURE); } if (!isdigit(*argv[1])) { fprintf(stderr, "Please enter 1 or 2 as an argument!\n"); exit(EXIT_FAILURE); } printf("Input amount to be converted:\n"); i = 0; while ((c = getchar()) != EOF && c != '\n') num[i++] = c; type = *argv[1] - '0'; rate = .008540; amount = atoi(num); if (type == 1) printf("%f\n", amount / rate); else printf("%f\n", amount * rate); return 0;}

i'm trying to learn C, rollan


Let's try my motivation.



random name generator come on
so easy

#51-Unit Converter. Converts Units.#Specifically weight, area, and length#fuck me this is going to be boring#dicc weightweight = {"ng":0.000000001, "mg":0.001, "cg":0.01, "g":1.0, "km":1000}#dicc area area = {"nm2":0.000000000000000001, "mm2":0.000001, "cm2":0.0001, "m2":1, "km2":1000000, "AU2":22380000000000000000000}#length dictionarylength = {"nm":0.000000001, "mm":0.001, "cm":0.01, "m":1.0, "km":1000, "AU":149597870691.013}#inb4 i could have a class and avoid having 3 seperate functionsdef convertWeight(value,unit1,unit2): print("\nResult:", value, unit1, "is", value * (weight[unit1] / weight[unit2]), unit2, "\n")def convertArea(value,unit1,unit2): print("\nResult:", value, unit1, "is", value * (area[unit1] / area[unit2]), unit2, "\n")def convertLength(value,unit1,unit2): print("\nResult:", value, unit1, "is", value * (length[unit1] / length[unit2]), unit2, "\n")#the head honchodef theMemeSupreme(mode): if mode == 1: print("~Valid Weight Units~") for key in weight.keys(): print(key) while True: try: value = int(input("Enter value:")) unit1 = input("Enter current unit:") unit2 = input("Enter desired unit:") convertWeight(value,unit1,unit2) break except: print("\nYou Silly Willy! You Messed Something Up! Try Again! :)\n") if mode == 2: print("~Valid Area Units~") for key in area.keys(): print(key) while True: try: value = int(input("Enter value:")) unit1 = input("Enter current unit:") unit2 = input("Enter desired unit:") convertArea(value, unit1, unit2) break except: print("\nYou Silly Willy! You Messed Something Up! Try Again! :)\n") if mode == 3: print("~Valid Length Units~") for key in length.keys(): print(key) while True: try: value = int(input("Enter value:")) unit1 = input("Enter current unit:") unit2 = input("Enter desired unit:") convertLength(value, unit1, unit2) break except: print("\nYou Silly Willy! You Messed Something Up! Try Again! :)\n")#hold on to your dick, lets get this piece of shit on the roadwhile True: try: pickanumba = int(input("Please Pick a Mode by typing the appropriate number:\n1. Weight\n2. Area\n3. Length\n>")) if not pickanumba in range(1,4): raise ValueError("HEY PICK AN APPROPRITE NUMBER!!") theMemeSupreme(pickanumba) except: print("\nTry Again?\n")

rolling, may or may not do the thing


roll me up fam

going to go fullout on this one fam wish me luck

finna roll for tomorrow morning

oh fuck

Let's roll.

quick roll

from datetime import dateimport systry: y1,m1,d1 = [int(x) for x in sys.argv[1].split('-')] y2,m2,d2 = [int(x) for x in sys.argv[2].split('-')] delta = date(y1,m1,d1) - date(y2,m2,d2) print(abs(delta.days))except: print("Calculate days between dates\n input date format: YYYY-MM-DD")

OK, I'm currently on fagOS computer at the office with no developer tools installed. Let's roll.

I've been wanting to try monogame for a while, I wonder how hard will it be to do raycasting on C#.
Shamelessly advertising my telegram RNG bot

Rate my code /g/

#include #include #include #include #include #include off_t greatest = -1, smallest = -1;char greatestname[256], smallestname[256];void recurse_directory(const char *, const char *);off_t filesize(const char *); int main(int argc, char ** argv) { recurse_directory(".", argv[1]); printf("Largest file: %s (%lld bytes)\nSmallest file: %s (%lld bytes)\n", greatestname, greatest, smallestname, smallest); return 0;}void recurse_directory(const char *base, const char *filename) { DIR *dir; struct dirent *ent; dir = opendir(filename); if(dir != NULL) { while((ent = readdir(dir))) { if((strcmp("..", ent->d_name) == 0 && ent->d_namlen == 2) || (strcmp(".", ent->d_name) == 0 && ent->d_namlen == 1)) { continue; } size_t buffersize = strlen(base) + strlen(filename) + ent->d_namlen + 3; char * fullpath = (char *)malloc(buffersize); strcat(fullpath, base); strcat(fullpath, "/"); strcat(fullpath, filename); if(ent->d_type == DT_DIR) { recurse_directory(fullpath, ent->d_name); } else { if(ent->d_namlen d_name, ent->d_namlen) == 0 || strncmp(".", ent->d_name, ent->d_namlen) == 0 )) { continue; }; strcat(fullpath, "/"); strcat(fullpath, ent->d_name); off_t size = filesize(fullpath); printf("%s (%lld)\n", fullpath, size); if(size != -1 && (size < smallest || smallest == -1)) { smallest = size; strncpy(smallestname, fullpath, 256); } else if(size != -1 && (size > greatest || greatest == -1)) { greatest = size; strncpy(greatestname, fullpath, 256); } } memset(fullpath, 0, buffersize); free(fullpath); } }}off_t filesize(const char *filename) { struct stat fstat; if(stat(filename, &fstat) == 0) { return fstat.st_size; } else { printf("Stat KO.\n"); FILE * fd = fopen(filename, "rb"); if(fd == NULL) { perror(filename); return -1; } fseek(fd, 0, SEEK_END); off_t size = ftello(fd); fclose(fd); return size; }}

Also, rolling again. I got time to kill.

Fuck this.


Gonna take a reroll on this.

Fuck it; why not?

How fucking boring. Just using Python so I don't have to do shitty string comparisons in C/C++:

#!/usr/bin/env pythonimport argparsefrom enum import Enumimport randomclass Flip(str, Enum): heads = 'heads' tails = 'tails'def main(): parser = argparse.ArgumentParser(description='Guess heads or tails') parser.add_argument('guess', help='Your guess, heads or tails', type=lambda val: Flip(val.lower())) args = parser.parse_args() result = random.choice(list(Flip)) print('Your choice was {}, and the result was {}. You {}!'.format(args.guess, result, 'won' if args.guess is result else 'lost'))if __name__ == '__main__': main()


green role

Not sure if this is the place to ask but I'm having a little trouble understanding orders of growth.
So from what I think I understand if I'm searching for an entry in a phone book via binary search the solution time is logarithmic because every step devises the amount of possible 'correct' entries by 2.
Inversely, If I'm preforming a breadth first search on a binary tree than the search time is exponential because for each step the amount of nodes to search doubles.

Is that all correct?

Also rolling I guess.

That's pretty much it. Although I have to wonder why you'd perform a breadth first search on a binary tree, since presumably you're looking for something to fit some criteria. If the current node doesn't match it then it should give some information as to which branch to go down to find it.

Unless you've got an unsorted binary tree in which case it might be faster to sort the tree then search it.

Not rolling because I've got enough other shit to waste my time on without adding on more stuff.

All right, let's go.


Nice to see you anons have some practice. I also am making a project currently: an Holla Forums client for console. I'm currently writing the json parsing library. I'm trying to keep it as generic as possible, though. I'm having some kind of trouble, as I end up iterating more than twice over the whole catalog json document, but I refuse to make it shell out some kind of shitty linked list made by me, I don't want to use anything other than arrays.
Of course, I'm making it in the autism language per excellence, C. It also won't include anything other than curl and iostream. Surely my autism will get me some validation around here, right?


03 - Password
#include #include #include intmain(int argc, char *argv[]){ int n; char c; srand(time(NULL)); for (n = 0; n != atoi(argv[1]); n++, c = rand()) (c < 127 && c > 32) ? putchar(c) : n--; putchar('\n'); return 0;}

This was a fun little thing

number four
File Edit Options Buffers Tools C Help /* palindrome checker */#include #include #define STRLEN 100/* argv[1] should be string */intmain(int argc, char *argv[]){ int n, l; l = strlen(argv[1]); char *string = argv[1]; char revstring[l]; for (n = 0; l >= 0; n++) revstring[n] = string[--l]; l = strlen(argv[1]); if (!strncmp(string, revstring, l - 1)) printf("YES\n"); else printf("NO\n"); return 0;}

no idea why I defined strlen

For who is SICP supposed to be? Complete beginners or people who already have a large amount of experience and want to perfect their skills?




fuck it, I hate my job

i got number 71
I have to use a given amount to get the least amount of euro/coins possible

here is the code i have so far. I am very new to python

a = float(input("what is the amount"))
euros = (5,10,20,50,100,200,500)

for i in euros:

if a % i >= i
a % i = y


At what point in the code did you declare variable c?




I have been noticing a trend on all the boards of Holla Forums, which you should be typing in the address as httpS

kys pls


I think i finally did it for the lowest euro generator given a certain amount:
a = input("what is the amount? ")euros = {"five": 5,"ten": 10, "twenty": 20, "fifty": 50,"one-hundred":100,"two-hundred":200,"five-hundred":500}times_dict= {}rem_dict = {}while a > 4: for k,v in euros.iteritems(): rem = a % v times = a / v if times > 0: times_dict[(k)] = times rem_dict[(k)] = rem minimum = min(times_dict, key=times_dict.get) rem = rem_dict[(minimum)] print times_dict[(minimum)],minimum a -= times_dict[(minimum)] * euros[(minimum)] times_dict.clear() rem_dict.clear() if a

roll for something easy

#include #include #define SQR(x) ((x)*(x))void circle(int rad){ for(int i=0;i

No coins?
import java.util.Scanner;public class euro { private static Scanner sc; public static void main(String args[]) { sc = new Scanner(; System.out.println("Enter Ammount: (ex 1,34)"); double amount = sc.nextDouble(); int shekelAmount; for (double shekels : new double[]{500, 200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01}) { if (amount == 0.0) { break; } shekelAmount = (int) Math.floor(amount / shekels); if (shekelAmount != 0) { amount = ((double) Math.round((amount % shekels) * 100d) / 100d); System.out.println(shekels + " x " + shekelAmount); } } }}


Noob here, did #26 in python 3. How bad is my code?

import randomsudoku = []for x in range(9): sudoku.append([0,0,0,0,0,0,0,0,0])while True: for sudokuindex, row in enumerate(sudoku): for rowindex, number in enumerate(row): column = [] for line in sudoku: column.append(line[rowindex]) while(True): unrandomizedlist = [1,2,3,4,5,6,7,8,9] randomizedlist = random.sample(unrandomizedlist, len(unrandomizedlist)) for x in randomizedlist: if x in column: continue if x in row: continue sudoku[sudokuindex][rowindex] = x placedvalue = 1 break if(placedvalue): break passon = 1 for x in sudoku: for z in x: if(z == 0): passon=0 if(passon): break else: sudoku = [] for x in range(9): sudoku.append([0,0,0,0,0,0,0,0,0]) for x in sudoku: print(x)for sudokuindex, row in enumerate(sudoku): for rowindex, number in enumerate(row): if(random.random() > 0.4): sudoku[sudokuindex][rowindex] = 0print("\n")for x in sudoku: print(x)for sudokuindex, row in enumerate(sudoku): for rowindex, number in enumerate(row): if(number==0): column = [] for line in sudoku: column.append(line[rowindex]) for x in range(1,10): if x in column: continue if x in row: continue sudoku[sudokuindex][rowindex] = xprint("\n")for x in sudoku: print(x)

how about you try it again in a real language like rust?

No promises

Is this enought?

#include #include int fact(int n) { int result = 1; for (int i = 2; i

#include #include int fact(int n) { if (n==0)return 1; return n*fact(n-1);}int main() { printf("%d\n", fact(5)); return EXIT_SUCCESS;};


fn main() { println!("{}", (2..std::env::args().nth(1).unwrap().parse::().unwrap() + 1).fold(1, |acc, i| acc * i));}


$ cat fact.s .intel_syntax _start_start: sub sp, 11 mov di, sp mov cx, 2 call read mov si, sp call atoi mov ax, bx call fact mov ebx, eax mov di, sp mov cx, 10 call itoa mov si, sp call print jmp .# eax: input/outputfact: mov ecx, eax mov eax, 1 fact_loop: mul ecx cmp edx, 0 jne fact_overflow loop fact_loop ret fact_overflow: xor eax, eax ret# di: buffer# ebx: input# cx: length - 1 (for zero byte)itoa: mov eax, ebx mov bx, cx itoa_loop: xor dx, dx push bx mov ebx, 10 div ebx pop bx add dx, '0' push dx dec cx cmp eax, 0 je itoa_reverse cmp cx, 0 jne itoa_loop itoa_reverse: sub bx, cx mov cx, bx itoa_reverse_loop: pop ax mov [di], ax inc di loop itoa_reverse_loop mov byte ptr [di], 0 ret# si: buffer# ebx: resultatoi: xor ebx, ebx atoi_loop: lodsb cmp al, '0' jb ret cmp al, '9' ja ret sub al, '0' mov cl, al mov eax, ebx mov ebx, 10 mul ebx cmp edx, 0 jne atoi_overflow xor ebx, ebx mov bl, cl add ebx, eax jc atoi_overflow jmp atoi_loop atoi_overflow: xor bx, bx ret# di: buffer# cx: length - 1 (for zero byte)read: mov bx, cx read_loop: xor ah, ah int 0x16 cmp al, '\b' je read_backspace cmp al, '\r' je read_newline cmp cx, 0 je read_loop mov ah, 0xE int 0x10 stosb dec cx jmp read_loop read_backspace: cmp cx, bx je read_loop lea si, backspace_str call print dec di inc cx jmp read_loop read_newline: mov byte ptr [di], 0 lea si, newline_str call print ret# si: bufferprint: lodsb cmp al, 0 je ret mov ah, 0xE int 0x10 jmp printret: retbackspace_str: .asciz "\b \b"newline_str: .asciz "\r\n".org 510.word 0xAA55$ as -o fact.o fact.s$ ld -Ttext 0x7c00 --oformat binary -o fact fact.o$ qemu-system-i386 -hda fact

Only problem: Can't count factorials whose results are bigger than 32 bits (thus 12 is the max).

Total size: 232 bytes (not counting the zeroes up to 512).
I hope someone's bored enough to help me optimize it/make it smaller. Could save a lot of space using DOS APIs, but I'm not very knowledgeable in those.

unsigned long fact(int i) { const static unsigned long fact_table[] = { 1, // 0 1, // 1 2, // 2 6, // 3 24, // 4 120, // 5 720, // 6 5040, // 7 40320, // 8 362880, // 9 3628800, // 10 39916800, // 11 479001600, // 12 6227020800, // 13 87178291200, // 14 1307674368000, // 15 20922789888000, // 16 355687428096000, // 17 6402373705728000, // 18 121645100408832000, // 19 2432902008176640000 // 20 }; if (i < 0 || i > 20) return 0; return fact_table[i];}

This just reminds me why I never do anything in assembly.



You should cache the `atoi(argv[1])` instead of wasting cpu cycles on it on every iteration.

To be fair, the actual factorial function is just 5 instructions if I didn't check for overflow. If I wrote it for linux instead of standalone it'd be about as big as your program. The rest are fancy keyboard input/atoi/itoa functions.

It's more the handling everything yourself. I find it tedious since you're thinking more about what goes/is where than in other languages. You have to intimately know your program at a lower level than any other language where the compiler handles it for you.

Of course, but thats the whole fun of trying to write shit in asm. I'd never write a serious program in assembly but I find it simply fun and challenging to think at such a low level.


ok whatevs



I'm depressed as fuck right now, give me digits.

rolling for an easy one since i'm a newb


roll for dubz