[ home / board list / faq / random / create / bans / search / manage / irc ] [ ]

/prog/ - Programming

Programming board

Catalog

8chan Bitcoin address: 1NpQaXqmCBji6gfX8UgaQEmEstvVY7U32C
The next generation of Infinity is here (discussion) (contribute)
A message from @CodeMonkeyZ, 2ch lead developer: "How Hiroyuki Nishimura will sell 4chan data"
Name
Email
Subject
Comment *
File
* = required field[▶ Show post options & limits]
Confused? See the FAQ.
Embed
(replaces files and can be used instead)
Options
Password (For file and post deletion.)

Allowed file types:jpg, jpeg, gif, png, webm, mp4, pdf
Max filesize is 8 MB.
Max image dimensions are 10000 x 10000.
You may upload 1 per post.


File: 1429926090911.jpg (49.79 KB, 640x480, 4:3, 1428781550692.jpg)

c045d0 No.2249

Coding Example Thread? Coding Examples thread.

Post code you've done.

Any language is acceptable.

Pic not related.

c01102 No.2254

"Hello, world!" in Python:

#!/usr/bin/env python2.7

import sys


OUTPUT_STREAM_NAME = u'output'
ERROR_STREAM_NAME = u'error'

OUTPUT_STREAM = sys.stdout
ERROR_STREAM = sys.stderr

STREAM = { OUTPUT_STREAM_NAME : OUTPUT_STREAM,
ERROR_STREAM_NAME : ERROR_STREAM }

BAD_THINGS = 1
GOOD_THINGS = 0

def get_exit_function():
try:
if exit is not None:
return exit

except NameError:
print_string(u'BAD THINGS',
ERROR_STREAM_NAME)

raise NameError("Quitting is too hard anyway")

def exit_because_bad_things():
exit_function = get_exit_function()
exit_function(BAD_THINGS)

def exit_because_good_things():
exit_function = get_exit_function()
exit_function(GOOD_THINGS)

def convert_to_utf8(ch):
try:
if type(ch) is not unicode:
raise TypeError('Expected "unicode" type')

return ch.encode('utf8')
except:
print_string(u'Could not convert character!',
ERROR_STREAM_NAME)

return '?'

def get_output_stream(name):
if type(name) is not unicode:
raise TypeError('Expected "unicode" type')

stream = STREAM[name]

if not stream.closed:
return stream

raise IOError("Output stream is closed")

def write_utf8(ch, stream_name):
if type(ch) is not unicode or len(ch) > 1:
raise TypeError('Expected unicode character')

try:
os = get_output_stream(stream_name)
uch = convert_to_utf8(ch)

os.write(uch)
except IOError:
exit_because_bad_things()

def print_string(string, stream_name=OUTPUT_STREAM_NAME):
try:
if len(string) > 0:
write_utf8(string[0], stream_name)
print_string(string[1:], stream_name)
else:
write_utf8(u'\n', stream_name)
except:
exit_because_bad_things()


def run():
print_string(u'Hello, world!')
exit_because_good_things()


if __name__ == '__main__':
run()

Any suggestions on how I can make it even more verbose improve it?


de14f0 No.2416

tetragraphs.c - Produces a list of the a-z tetragraph proportions in text taken from stdin.

E.g. AAAA: 0.0\nAAAB: 0.1e-07 etc.

From a cipher-cracking suite I wrote before I knew how to write good code.

#include <stdio.h>
#include <stdlib.h>
long long unsigned tetragraphs[26][26][26][26];
int incval(char *tet)
{
tetragraphs[tet[0]-'A'][tet[1]-'A'][tet[2]-'A'][tet[3]-'A']++;
return 1;
}
int inittets()
{
int i,j,k,l;
for (i=0;i<26;i++)
for (j=0;j<26;j++)
for (k=0;k<26;k++)
for (l=0;l<26;l++)
tetragraphs[i][j][k][l]=0;
}
int finishup(long number)
{
int i,j,k,l;
for (i=0;i<26;i++)
for (j=0;j<26;j++)
for (k=0;k<26;k++)
for (l=0;l<26;l++)
printf("%c%c%c%c: %lg\n",i+'A',j+'A',k+'A',l+'A',(double)tetragraphs[i][j][k][l]/number);
exit(0);
}
int loadmore(char* ch4)
{
static long i=0;
ch4[0]=ch4[1];
ch4[1]=ch4[2];
ch4[2]=ch4[3];
do
{
ch4[3]=toupper(getchar());

if(ch4[3]==EOF)
finishup(i);
}
while(ch4[3] > 'Z' || ch4[3] < 'A');
i++;
}
int main()
{
char currenttet[5];
inittets();
loadmore(currenttet);
loadmore(currenttet);
loadmore(currenttet);
loadmore(currenttet);
currenttet[4]='\0';

while(1)
{
incval(currenttet);
loadmore(currenttet);
}
}


73c26f No.2420

>>2416

Those for loops tho.. very O(n^4)


6768de No.2421


#ifndef SCHEDULER_HPP
#define SCHEDULER_HPP
#include "process.h"
#include "event.h"
enum Mode {FCFS, SJF, RR, PRIORITY};
class scheduler {
private:
Process* readyq; //container
unsigned int vacant;//last vacant spot of ready queue array.
void enqueue(Process&);//Add element to ready queue.
Process dequeue(); //Removes element from ready queue.
int order;//Incremented & assigned to process on add.
int mode; //scheduling method- run-time changes is possible.
public:
/*PARAM: (capacity for container, mode for scheduler)
NOTE: Uses new.*/
scheduler(const unsigned int&, const int&);
//Deletes array created by new.
~scheduler();
/*PARAM: (process to add to container)*/
void add(Process&);
/*PARAM: (CPU status, event queue, time quantum)
NOTE: tq, time quantum, only applicable for RR.*/
void run(bool&, Event*, unsigned int&, const int&, const unsigned int& tq = 0);
};

#include "objcmp.hpp"
#include "heap_sort.hpp"
#ifdef DEBUG
#include <cstdio>
#endif
scheduler::scheduler(const unsigned int& amount, const int& _mode) {
readyq = new Process[amount];
for (int i = 0; i < amount; i++) {
//Uninitialized junk may interfere & cause seg. faults.
readyq[i].state = TERMINATED;
}
vacant = 0;
order = 0;
mode = _mode;
}

scheduler::~scheduler() {
delete [] readyq;
}

Process scheduler::dequeue() {
static struct cmp<Process, int, std::less_equal> lec
(&Process::CPU_duration_remaining);
static struct cmp<Process, int, std::less_equal> lep
(&Process::priority);
static struct cmp<Process, int, std::less_equal> leo
(&Process::order);
Process output = readyq[0];
switch(mode) {
case SJF:
reheapify<Process, int, std::less_equal>
(readyq, vacant, lec);
break;
case PRIORITY:
reheapify<Process, int, std::less_equal>
(readyq, vacant, lep);
break;
default:
reheapify<Process, int, std::less_equal>
(readyq, vacant, leo);
break;
}
return output;
}

void scheduler::enqueue(Process& add_me) {
static struct cmp<Process, int, std::less>
oless(&Process::order);
static struct cmp<Process, int, std::less>
cless(&Process::CPU_duration_remaining);
static struct cmp<Process, int, std::less>
pless(&Process::priority);
switch(mode) {
case RR:
case FCFS:
insert<Process, int, std::less>
(readyq, vacant, add_me, oless);
break;
case SJF:
insert<Process, int, std::less>
(readyq, vacant, add_me, cless);
break;
case PRIORITY:
insert<Process, int, std::less>
(readyq, vacant, add_me, pless);
break;
default:
printf("Error: Hit default case on scheduler::add.\n");
exit(EXIT_FAILURE);
break;
}
}

void scheduler::add(Process& add_me) {
order++;
add_me.order = order;
#ifdef DEBUG
printf("Process#%d at the front of ready queue\nNeed to add process id#%d\n", readyq[0].id, add_me.id);
#endif
for (int i = 0; i < vacant; i++) {
if (add_me.id == readyq[i].id) {
//Already exists - don't add clones to the ready queue.
readyq[i] = add_me;
Process temp[i + 1];
for (int j = 0; j < i + 1; j++) {
temp[j] = dequeue();
}//end for
for (int j = 0; j < i + 1; j++) {
enqueue(temp[j]);
}
#ifdef DEBUG
goto display;
#else
return;
#endif
}//end if
}//end for
enqueue(add_me);
#ifdef DEBUG
display:
for (unsigned int j = 0; j < vacant; j++) {
printf("Process Id#%d with order %d.\n", readyq[j].id, readyq[j].order);
}
#endif
//vacant is incremented by insert().
}

void scheduler::run
(bool& cpu_idle, Event* event_queue, unsigned int& ev,
const int& ctime, const unsigned int& tq) {
static struct cmp<Event, int, std::less> lt
(&Event::occur_time);
if (vacant <= 0) {
printf("Scheduler has no processes in ready queue.\n");
return;
}
if (cpu_idle && mode != RR) {
#ifdef DEBUG
printf("CPU is idle - and non-pre-emptive scheduling.\n");
#endif
//Run process
cpu_idle ^= 1; //Set to busy.
Process running = dequeue();
Event e;
e.pid = running.id;
e.happened = CPU_BURST_COMPLETION;
e.occur_time = ctime + running.CPU_burst_length_next;
insert<Event, int, std::less>(event_queue, ev, e, lt);
} else if (!cpu_idle && mode == RR && tq != 0) {
#ifdef DEBUG
printf("CPU is busy and pre-emptive scheduling.\n");
#endif
//Set aside process. Send IO_Burst Completion Event.
//Get new process. Send CPU Completion Event.
} else if (!cpu_idle && mode == RR) {
#ifdef DEBUG
printf("Error: Time quantum is 0.\n");
#endif
exit(EXIT_FAILURE);
}
/*CPU is not idle and mode is not RR
or CPU is idle and the mode is RR*/
}
#endif

One file of a homework assignment. This thread could get quite long.


de14f0 No.2422

>>2420

Actually those loops are O(1) because it's just performing 26^4 loops, independent of n.

The whole program takes O(n) time and O(1) space, I think.


73c26f No.2426

>>2422

True I didn't see the less than 24 being common in all the loops


73c26f No.2427

File: 1431290247919.png (542.8 KB, 637x423, 637:423, Q3cHpp1.png)

>>2426

>>2422

I mean 26




[Return][Go to top][Catalog][Post a Reply]
Delete Post [ ]
[]
[ home / board list / faq / random / create / bans / search / manage / irc ] [ ]