Update and reorganize

This commit is contained in:
Hoang Nguyen 2022-01-19 22:32:57 +07:00
parent 143979c5b4
commit 9465097aa5
No known key found for this signature in database
GPG Key ID: 813CF484F4993419
27 changed files with 782 additions and 1 deletions

View File

@ -1,3 +1,3 @@
## Practice
# Practice
Bunch of crappy code I wrote for practicing which serves no purpose.

View File

@ -0,0 +1,8 @@
cmake_minimum_required(VERSION 3.14)
project(TuringMachine C)
set(CMAKE_C_STANDARD 11)
include_directories(.)
add_executable(TuringMachine main.c declaration.h command.c description.c index.c menu.c run.c)

80
c/TuringMachine/command.c Normal file
View File

@ -0,0 +1,80 @@
#include "declaration.h"
void loadCommand(turing *t, char *nameFile) {
FILE *in;
in = fopen(nameFile, "r");
if (in == NULL) {
printf("The file '%s' was not opened", nameFile);
exit(-1);
}
printf("\nCommands:\n");
int commandNumb = 1, N = 0;
t->commands = malloc((N + 1) * sizeof(command));
int numb;
while (fscanf(in, "%d. ", &numb) != EOF) {
command tran;
char symbol1, symbol2, dir, state1, state2;
if (numb <= 0) {
printf("Error in '%s' file. There may only be commands from [1...] interval \n", nameFile);
fclose(in);
exit(0);
}
if (numb != commandNumb) {
printf("Error in '%s' file. Command numbers must be in order \n", nameFile);
fclose(in);
exit(0);
}
commandNumb++;
fscanf(in, "%c ", &state1);
fscanf(in, "%c ", &symbol1);
fscanf(in, "%c ", &symbol2);
fscanf(in, "%c ", &dir);
fscanf(in, "%c", &state2);
tran.number = numb;
tran.state1 = stateIndex(t, state1);
if (tran.state1 == -1) {
printf("Error in '%s' file", nameFile);
printf("\nIn the command %d, state %c isn't contained in the set of states of your Turing machine", numb,
state1);
fclose(in);
exit(0);
}
tran.symbol1 = symbolIndex(t, symbol1);
if (tran.symbol1 == -1) {
printf("\nError in '%s' file", nameFile);
printf("\nIn the commnand %d, symbol %c isn't contained in the alphabet of your Turing machine", numb,
symbol1);
fclose(in);
exit(0);
}
tran.symbol2 = symbolIndex(t, symbol2);
if (tran.symbol2 == -1) {
printf("\nError in 'command.txt' file");
printf("\nIn the commnand %d, symbol %c isn't contained in the alphabet of your Turing machine", numb,
symbol2);
fclose(in);
exit(0);
}
tran.dir = dir;
tran.state2 = stateIndex(t, state2);
if (tran.state2 == -1) {
printf("\nError in '%s' file", nameFile);
printf("\nIn the command %d, state %c isn't contained in the set of states of your Turing machine", numb,
state2);
fclose(in);
exit(0);
}
t->commands[N] = tran;
printf("%d. %c %c %c %c %c\n", numb, state1, symbol1, symbol2, dir, state2);
N++;
t->commands = realloc(t->commands, (N + 1) * sizeof(command));
}
t->commandsNumb = N;
fclose(in);
}

View File

@ -0,0 +1,9 @@
1. a 1 1 R a
2. a 0 0 R a
3. a B B L b
4. b 0 1 L c
5. b 1 0 L b
6. b B 1 L S
7. c 0 0 L c
8. c B B R S
9. c 1 1 L c

View File

@ -0,0 +1,51 @@
#ifndef DECLARATION_H
#define DECLARATION_H
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define ENTER 10
typedef struct {
int number;
int state1; //Тут сохраняется индекс состояния, при котором выплоняется команд, в массиве states
int symbol1; //Тут сохраняется индекс символа, при котором выплоняется команд, в массиве symbols
int symbol2; //Тут сохраняется индекс символа, который нужен записать в ячейку, в массиве symbols
char dir; //просто направление сдвига головки
int state2; //Тут сохраняется индекс состояния, в которое нужно перейти, в массиве states
} command;
typedef struct tapeT tapeT;
struct tapeT {
int symbol;
tapeT *left;
tapeT *right;
};
typedef struct {
int statesNumb; // кол-во используемых состояний
char *states;//множество состояний
int symbolsNumb;// кол-во используемых символов
char *symbols;//альфавит
int state;// состояние в головке
int commandsNumb;//число команд
command *commands;//команды
tapeT *tape;// лента
} turing;
int menu(int lastNumb);
int stateIndex(turing *t, char state); //нахождение номер индекса состояния state в states
int symbolIndex(turing *t, char symbol); //нахождение номер индекса symbol в symbols
void loadCommand(turing *t, char *nameFile); //загрузка команд из текстового файла
command findCommand(turing *t, char stateCurrent, char symbolCurrent);//нахождение нужной команды из список всех команд
void run(turing *t, bool step, char *nameFile);
void loadDescription(turing *t, char *nameFile); //загрузка описание машины из текстового файла
#endif

View File

@ -0,0 +1,60 @@
#include "declaration.h"
void loadDescription(turing *t, char *nameFile) {
FILE *in;
in = fopen(nameFile, "r");
if (in == NULL) {
printf("The file '%s' was not opened", nameFile);
exit(-1);
}
bool testForS = false, testForBlank = false;
printf("States: ");
int N = 0;
char c;
t->states = malloc((N + 1) * sizeof(char));
fscanf(in, "%c", &c);
while (c != '\n') {
t->states[N] = c;
if (t->states[N] == 'S') {
testForS = true;
}
printf("%c ", t->states[N]);
fscanf(in, "%c", &c);
N++;
t->states = realloc(t->states, (N + 1) * sizeof(char));
}
t->statesNumb = N;
if (!testForS) {
printf("\nError in file '%s'", nameFile);
printf("\nThe set of states doesn't contain state STOP(S). Add S to it, please!");
fclose(in);
exit(0);
}
printf("\nAlphabet: ");
N = 0;
t->symbols = malloc((N + 1) * sizeof(char));
while (fscanf(in, "%c", &c) != EOF) {
t->symbols[N] = c;
if (t->symbols[N] == 'B') testForBlank = true;
printf("%c ", t->symbols[N]);
N++;
t->symbols = realloc(t->symbols, (N + 1) * sizeof(char));
}
t->symbolsNumb = N;
if (!testForBlank) {
printf("\nError in file '%s'", nameFile);
printf("\nThe alphabet doesn't contain symbol Blank(B). Add B to it, please!");
fclose(in);
exit(0);
}
t->symbolsNumb++;
t->symbols[t->symbolsNumb - 1] = ' ';
printf("%c ", t->symbols[t->symbolsNumb - 1]);
fclose(in);
}

View File

@ -0,0 +1,2 @@
abcS
01B

22
c/TuringMachine/index.c Normal file
View File

@ -0,0 +1,22 @@
#include "declaration.h"
int stateIndex(turing *t, char state) {
int i;
for (i = 0; i < t->statesNumb; i++) {
if (t->states[i] == state) {
return i;
}
}
return -1;
}
int symbolIndex(turing *t, char symbol) {
int i;
for (i = 0; i < t->symbolsNumb; i++) {
if (t->symbols[i] == symbol) {
return i;
}
}
return -1;
}

View File

@ -0,0 +1,2 @@
a
10011

125
c/TuringMachine/main.c Normal file
View File

@ -0,0 +1,125 @@
#include "declaration.h"
void loadTape(turing *t, char *nameFile) {
FILE *in;
in = fopen(nameFile, "r");
if (in == NULL) {
printf("The file '%s' was not opened", nameFile);
exit(-1);
}
char state, linefeed;
fscanf(in, "%c", &state);
t->state = stateIndex(t, state);
printf("\nInitial state: %c\n", state);
if (t->state == -1) {
printf("Error in file '%s'\n", nameFile);
printf("Initial state %c isn't contained in the set of states of your Turing machine", state);
fclose(in);
exit(0);
}
fscanf(in, "%c", &linefeed);
if (linefeed != '\n') {
printf("Error in file '%s'. There may only be linefeed after initial state\n", nameFile);
fclose(in);
exit(0);
}
t->tape = NULL;
char x;
fscanf(in, "%c ", &x);
printf("Initial tape: %c", x);
if (symbolIndex(t, x) == -1) {
printf("Error in '%s' file. Symbol %c isn't contained in the alphabet of your Turing machine", nameFile, x);
fclose(in);
exit(0);
}
if (t->tape == NULL) {
t->tape = malloc(sizeof(tapeT));
t->tape->symbol = symbolIndex(t, x);
t->tape->right = NULL;
t->tape->left = NULL;
}
tapeT *temp_tape;
temp_tape = t->tape;
while (!feof(in)) {
fscanf(in, "%c ", &x);
printf("%c", x);
if (symbolIndex(t, x) == -1) {
printf("Error in '%s' file. Symbol %c isn't contained in the alphabet of your Turing machine", nameFile, x);
fclose(in);
exit(0);
}
if (temp_tape->right == NULL) {
tapeT *tmp_tp = temp_tape;
temp_tape->right = malloc(sizeof(tapeT));
if (temp_tape->right == NULL) {
printf("Not enough memory for tape \n");
exit(103);
}
temp_tape = temp_tape->right;
temp_tape->symbol = symbolIndex(t, x);
temp_tape->right = NULL;
temp_tape->left = tmp_tp;
}
}
printf("\n");
fclose(in);
}
int main(int argc, char *args[]) {
if (argc != 5) {
printf("Error: input.txt description.txt command.txt output.txt \n");
return -1;
}
bool ifLoadTape = false;
int menuNumb = 0, lastNumb = 4;
turing *t = malloc(sizeof(turing));
loadDescription(t, args[2]);
loadCommand(t, args[3]);
while (menuNumb != 4) {
menuNumb = menu(lastNumb);
switch (menuNumb) {
case 1:
loadTape(t, args[1]);
ifLoadTape = true;
break;
case 2:
if (ifLoadTape == false) {
printf("Initial tape wasn't loaded. Load tape, please!\n");
break;
}
run(t, false, args[4]);
ifLoadTape = false;
break;
case 3:
if (ifLoadTape == false) {
printf("Initial tape wasn't loaded. Load tape, please!\n");
break;
}
run(t, true, args[4]);
ifLoadTape = false;
break;
case 4:
break;
default:
break;
}
}
if (t->commands != NULL)
free(t->commands);
if (ifLoadTape) {
while (t->tape->left) {
tapeT *tmp;
tmp = t->tape;
t->tape = t->tape->left;
free(tmp);
}
t->tape = t->tape->left;
free(t->tape);
}
if (t != NULL)
free(t);
return 0;
}

19
c/TuringMachine/menu.c Normal file
View File

@ -0,0 +1,19 @@
#include "declaration.h"
int menu(int lastNumb) {
int number, ret;
printf("Modes of the machine:\n"
"1. Load tape \n"
"2. Run\n"
"3. Run step\n"
"4. Exit\n");
while (1) {
printf("\nInput ordinal number of modes(1->%d)", lastNumb);
ret = scanf("%d", &number);;
if (ret == 1 && (number >= 1 && number <= lastNumb)) break;
fflush(stdin);
printf("Error. Number must be in the interval [1..%d]", lastNumb);
break;
}
return number;
}

View File

@ -0,0 +1,37 @@
[1] 0 0 1 1
1. a 1 1 R a
1 [0] 0 1 1
2. a 0 0 R a
1 0 [0] 1 1
2. a 0 0 R a
1 0 0 [1] 1
1. a 1 1 R a
1 0 0 1 [1]
1. a 1 1 R a
1 0 0 1 1 [ ]
3. a B B L b
1 0 0 1 [1]
5. b 1 0 L b
1 0 0 [1] 0
5. b 1 0 L b
1 0 [0] 0 0
4. b 0 1 L c
1 [0] 1 0 0
7. c 0 0 L c
[1] 0 1 0 0
9. c 1 1 L c
[ ] 1 0 1 0 0
8. c B B R S
[1] 0 1 0 0

141
c/TuringMachine/run.c Normal file
View File

@ -0,0 +1,141 @@
#include "declaration.h"
command findCommand(turing *t, char stateCurrent, char symbolCurrent) {
// find by state
command *resTrans1 = malloc(t->symbolsNumb * sizeof(command));
command resTrans;
int j = 0;
for (int i = 0; i < t->commandsNumb; i++) {
if (t->states[t->commands[i].state1] == stateCurrent) {
resTrans1[j] = t->commands[i];
j++;
}
}
// find by symbol
for (int i = 0; i < t->symbolsNumb - 1; i++) {
if (t->symbols[resTrans1[i].symbol1] == symbolCurrent) {
resTrans = resTrans1[i];
}
}
free(resTrans1);
return resTrans;
}
void run(turing *t, bool step, char *nameFile) {
int key;
char stepCommand[5];
FILE *output;
output = fopen(nameFile, "w");
if (output == NULL) {
printf("The file '%s' was not opened\n", nameFile);
exit(-1);
}
if (step) printf("<Enter> - next step, stop - stop, run - run\n");
tapeT *tempTape = t->tape;
int idPrint = 0, i = 0;
command currentTrans;
while (1) {
if (i != 0) {
fprintf(output, "\n%d. %c %c %c %c %c\n", currentTrans.number, t->states[currentTrans.state1],
t->symbols[currentTrans.symbol1], t->symbols[currentTrans.symbol2], currentTrans.dir,
t->states[currentTrans.state2]);
printf("%d. %c %c %c %c %c", currentTrans.number, t->states[currentTrans.state1],
t->symbols[currentTrans.symbol1], t->symbols[currentTrans.symbol2], currentTrans.dir,
t->states[currentTrans.state2]);
printf("\nCurrent state: %c\n", t->states[currentTrans.state2]);
}
i++;
tapeT *tape = t->tape;
while (tape->left != NULL) {
tape = tape->left;
}
int idPrint1 = 0;
while (tape->right != NULL) {
if (idPrint1 == idPrint) {
fprintf(output, "[%c]", t->symbols[tape->symbol]);
printf("[%c]", t->symbols[tape->symbol]);
idPrint1++;
} else {
fprintf(output, " %c ", t->symbols[tape->symbol]);
printf(" %c ", t->symbols[tape->symbol]);
idPrint1++;
}
tape = tape->right;
}
if (idPrint1 == idPrint) {
fprintf(output, " [%c] ", t->symbols[tape->symbol]);
printf(" [%c] ", t->symbols[tape->symbol]);
} else {
fprintf(output, " %c ", t->symbols[tape->symbol]);
printf(" %c ", t->symbols[tape->symbol]);
}
fprintf(output, "\n");
printf("\n");
if (t->states[t->state] == 'S') {
fclose(output);
return;
}
if (t->symbols[tempTape->symbol] == ' ') {
currentTrans = findCommand(t, t->states[t->state], 'B');
printf("1 \n");
} else {
currentTrans = findCommand(t, t->states[t->state], t->symbols[tempTape->symbol]);
}
if (t->symbols[currentTrans.symbol2] == 'B') {
tempTape->symbol = t->symbolsNumb - 1;
} else {
tempTape->symbol = currentTrans.symbol2;
}
if (currentTrans.dir == 'R') {
idPrint++;
if (tempTape->right == NULL) {
tempTape->right = malloc(sizeof(tapeT));
tapeT *tt = tempTape->right;
tt->left = tempTape;
tt->right = NULL;
tt->symbol = t->symbolsNumb - 1;
}
tempTape = tempTape->right;
} else {
idPrint--;
if (tempTape->left == NULL) {
tempTape->left = malloc(sizeof(tapeT));
tapeT *tt = tempTape->left;
tt->right = tempTape;
tt->left = NULL;
tt->symbol = t->symbolsNumb - 1;
idPrint = 0;
}
tempTape = tempTape->left;
}
t->state = currentTrans.state2;
if (step) {
while (1) {
key = getc(stdin);
if (key == ENTER) break;
ungetc(key, stdin);
scanf(" %4s", stepCommand);
fflush(stdin);
if (!strcmp(stepCommand, "run")) {
step = false;
break;
}
if (!strcmp(stepCommand, "stop")) {
fclose(output);
return;
}
printf("error");
fflush(stdin);
}
}
}
}

54
lua/math.lua Normal file
View File

@ -0,0 +1,54 @@
#!/usr/bin/env lua5.3
-- NOTE: Lua uses double-precision float and 64-bit integer
-- (except when being specifically compiled with single-precision float and 32-bit integer)
-- Double-precision floating-point number: exact integers up to 2^53
-- [1 bit](sign) + [11 bits](exponent) + [53 bits (52 explicitly stored)](fraction)
-- Single-precision floating-point number: exact integers up to 2^24
-- [1 bit](sign) + [8 bits](exponent) + [24 bits (23 explicitly stored)](fraction)
-- Integer wraps around
-- Below are max(min)imum presentable integers
print(math.maxinteger == 0x7fffffffffffffff) -- 2^63 - 1
print(math.mininteger == 0x8000000000000000)
-- Convert ineger to float (up to 2^53)
print(math.type(3 + 0.0))
-- Force a number to be integer (has no fractional part)
local function cond2int(x)
return math.tointeger(x) or x
end
print(math.type(3.0 | 0))
print(math.tointeger(356.00))
print(math.tointeger(5.6))
print(cond2int(5.6))
-- Hex numbers are auto-converted to dec
print(0xffa4)
-- NOTE: operators of floats/integers returns a float/integer
-- Exception: division always returns a float. Use `//` to get an integer division
print(3 / 2)
print(math.pi // 1.2)
-- Rounding decimal digits
local pi = math.pi
print(pi - pi % 0.0001)
-- Radian is used by default
print(math.sin(30))
print(math.deg(2 * math.pi))
-- Unbiased rounding number function (haft-integers are rounded to the nearest even integer)
-- Using simply math.floor(x + 0.5) will always round the number up (eg. 2.5 -> 3)
-- also 2^52 + 0.5 cannot be represent (2^52 -> 2^53 has fixed interval 1)
local function round(x)
local f = math.floor(x)
if x == f or (x % 2.0 == 0.5) then
return f
else
return math.floor(x + 0.5)
end
end
print(round(2.5))
print(round(3.5))

29
lua/string.lua Normal file
View File

@ -0,0 +1,29 @@
-- Strings are immutable
-- 'modify' it by using another string
local a = 'one string'
local b = string.gsub('one string', 'one', 'another')
print(a)
print(b)
-- Length
print(#"Count the length")
-- C-like escape sequences
print("Backslash inside quotes: '\\'")
print('Backslash inside quotes: \'\\\'')
-- utf-8
print('\x42 is the letter B')
print('\u{3b1} is alpha')
-- Querk
print('Notice the ]] below?')
print [===[a[b[i]] = x]===]
--[====[ Wow comment too
Still inside the comment
]====] print('Normal text here')
-- \z skips all subsequent space characters
local data = '\x00\x01\x02\x03\x04\x05\x06\x07\z
\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F'
print(data)

View File

@ -0,0 +1,62 @@
import socket
from utility import wait_for_acknowledge
# initiate connection
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_addr = (socket.gethostname(), 2019) # change here for sending to another machine in LAN
client.connect(server_addr)
print(f"Connected to server!")
client.settimeout(5) # limit each communication time to 5s
# listening to server command
print("Client is now waiting for server's command.")
cmd_from_server = wait_for_acknowledge(client, "Start sending image.")
# send an ACK
imgCount_from_server = 0
if cmd_from_server == "Start sending image.":
print("Command \"Start sending image.\" received.")
print("Sending ACK...")
client.sendall(bytes("ACK", "utf-8"))
try:
print("Client is now waiting for the number of images.")
imgCount_from_server = int(wait_for_acknowledge(client, str(3)))
except:
raise ValueError("Number of images received is buggy.")
if imgCount_from_server > 0:
print("Number of images to receive: ", imgCount_from_server)
print("Sending ACK...")
client.sendall(bytes("ACK", "utf-8"))
print(f"Client is now eceiving {imgCount_from_server} images.")
for i in range(imgCount_from_server):
index = i + 1
file = f"./imgfromserver{index}.jpg"
try: # check for existing file, will overwrite
f = open(file, "x")
f.close()
except:
pass
finally:
f = open(file, "wb")
print(f"\tReceiving image {index}")
imgsize = int(wait_for_acknowledge(client, str(3)))
print(f"\tImage size of {imgsize}B received by Client")
print("Sending ACK...")
client.sendall(bytes("ACK", "utf-8"))
buff = client.recv(imgsize)
f.write(buff)
f.close()
print(f"File {file} received!")
print("Sending ACK...")
client.sendall(bytes("ACK", "utf-8"))
# a = wait_for_acknowledge(client,"This is done.")
print("All images received.")
print("Closing connection.")
client.close()

View File

@ -0,0 +1,66 @@
import socket
from os import listdir
from re import findall
from utility import wait_for_acknowledge
"""Global Var"""
buff_size = 1024
fileList = [file for file in listdir() if findall(r'.jpg',file) != []] #include all .jpg photos in that directory
#fileList = ['jihyo.jpg','dami.jpg','uju.jpg'] #images to be sent over to client
#initiate connection
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_addr = (socket.gethostname(), 2019) #change here for sending to another machine in LAN
s.bind(server_addr)
s.listen(5)
client, address = s.accept()
print(f"Connection from {address} has been established!")
#Send message to client to notify about sending image
print("Server sending command: \"Start sending image.\"")
client.sendall(bytes("Start sending image." ,"utf-8"))
#wait for reply from client
print("Server is now waiting for acknowledge from client.")
ack_from_client = wait_for_acknowledge(client,"ACK")
if ack_from_client != "ACK":
raise ValueError('Client does not acknowledge command.')
#Send message to client to notify about sending image
imgCount = len(fileList)
print("Server sends the number of images to be transfered client.")
client.sendall(bytes(str(imgCount) ,"utf-8"))
#wait for reply from client
print("Server is now waiting for acknowledge from client.")
ack_from_client = wait_for_acknowledge(client,"ACK")
if ack_from_client != "ACK":
raise ValueError('Client does not acknowledge img count.')
print("Server will now send the images.",end='')
for file in fileList:
img = open(file, 'rb')
b_img = img.read()
imgsize = len(b_img)
client.sendall(bytes(str(imgsize) ,"utf-8"))
print(f"\t sending image {file} size of {imgsize}B.")
print("Server is now waiting for acknowledge from client.")
ack_from_client = wait_for_acknowledge(client,"ACK")
if ack_from_client != "ACK":
raise ValueError('Client does not acknowledge img size.')
client.sendall(b_img)
img.close()
print(f"Image {file} sent!")
print("Server is now waiting for acknowledge from client.")
ack_from_client = wait_for_acknowledge(client,"ACK")
if ack_from_client != "ACK":
raise ValueError('Client does not acknowledge image transfer completion.')
print("All images sent.\nClosing connection.")
client.close()

View File

@ -0,0 +1,14 @@
def wait_for_acknowledge(client, response):
"""
Waiting for this response to be sent from the other party
"""
amount_received = 0
amount_expected = len(response)
msg = str()
while amount_received < amount_expected:
data = client.recv(16)
amount_received += len(data)
msg += data.decode("utf-8")
# print(msg)
return msg