- 1
- 2
- 3
https://www.researchgate.net/publication/325358150_cQASM_v10_Towards_a_Common_Quantum_Assembly_Language
cQASM v1.0: Towards a Common Quantum Assembly Language
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
Всего: 338
+2
https://www.researchgate.net/publication/325358150_cQASM_v10_Towards_a_Common_Quantum_Assembly_Language
cQASM v1.0: Towards a Common Quantum Assembly Language
The quantum assembly language (QASM) is a popular intermediate representation used in many quantum compilation and simulation tools to describe quantum circuits. Currently, multiple different dialects of QASM are used in different quantum computing tools. This makes the interaction between those tools tedious and time-consuming due to the need for translators between theses different syntaxes. Beside requiring a multitude of translators, the translation process exposes the constant risk of loosing information due to the potential incompatibilities between the different dialects. Moreover, several tools introduce details of specific target hardware or qubit technologies within the QASM syntax and prevent porting the code to other hardwares. In this paper, we propose a common QASM syntax definition, named cQASM, which aims to abstract away qubit technology details and guarantee the interoperability between all the quantum compilation and simulation tools supporting this standard. Our vision is to enable an extensive quantum computing toolbox shared by all the quantum computing community.
Вот это я понимаю, а то вон там мелкософт какие-то говношарпы придумывает очередные:
https://docs.microsoft.com/en-us/quantum/language/?view=qsharp-preview
+1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SQARESZ 3
void rotateclockwise(char *ptra, size_t sz)
{
char (*a_ar)[sz] = (void *)ptra;
char b_ar[sz][sz];
for (size_t y = 0; y < sz; y++)
{
for (size_t x = 0; x < sz; x++)
{
b_ar[y][x] = a_ar[sz-1-x][y];
}
}
memcpy(a_ar, b_ar, sz*sz);
}
void print_ar(char *ptra, size_t sz)
{
char (*a_ar)[sz] = (void *)ptra;
for (size_t y = 0; y < sz; y++)
{
for (size_t x = 0; x < sz; x++)
{
printf("%i ", a_ar[y][x]);
}
printf("\n");
}
}
int main()
{
char a[SQARESZ][SQARESZ] =
{
{1,2,3},
{4,5,6},
{7,8,9}
};
print_ar((char *)a, SQARESZ);
printf("\n");
rotateclockwise((char *)a, SQARESZ);
print_ar((char *)a, SQARESZ);
printf("\n");
rotateclockwise((char *)a, SQARESZ);
print_ar((char *)a, SQARESZ);
printf("\n");
rotateclockwise((char *)a, SQARESZ);
print_ar((char *)a, SQARESZ);
printf("\n");
rotateclockwise((char *)a, SQARESZ);
print_ar((char *)a, SQARESZ);
printf("\n");
return 0;
}
https://habr.com/post/317300/ В C++17 до сих пор нет нормальных многомерных массивов, которые были в Fortran начиная с Fortran 90
> UPD от 2016-12-10 14:03. Посмотрел на этот коммент от @selgjos, поэкспериментировал с компилятором и понял, что с помощью C99 VLA всё-таки можно добиться нужного мне эффекта.
> В общем, окей, в C есть нужные мне массивы. Как и в Fortran. А в C++ их по-прежнему нет.
+2
/*
x86-64 clang (trunk) -O3
https://godbolt.org/z/t8NDGG
#include <inttypes.h>
uint32_t saturation_add(uint32_t a, uint32_t b)
{
const uint64_t tmp = (uint64_t)a + b;
if (tmp > UINT32_MAX)
{
return UINT32_MAX;
}
return tmp;
}
*/
saturation_add:
mov edx, esi
mov eax, edi
add edi, esi
add rax, rdx
mov edx, 4294967295
cmp rax, rdx
mov eax, -1 // ЗАЧЕМ???
cmovbe eax, edi
ret
https://en.wikipedia.org/wiki/Saturation_arithmetic
Почему компиляторы до сих пор такое говно
+1
;;; the toplevel operators of each equation in the system
;;; type : array[term]
(defmacro match-acz-state-methods (state__) `(svref ,state__ 0))
;;; functional terms
;;; type : array[term]
(defmacro match-acz-state-lhs-f (state__) `(svref ,state__ 1))
;;; variables on the LHS
;;; type : array[term]
(defmacro match-acz-state-lhs-v (state__) `(svref ,state__ 2))
;;; contants on the RHS
;;; type : array[term]
(defmacro match-acz-state-rhs-c (state__) `(svref ,state__ 3))
;;; functional terms on RHS
;;; type : array[term]
(defmacro match-acz-state-rhs-f (state__) `(svref ,state__ 4))
;;; notes repeated functional terms of LHS
;;; type : array[bool]
(defmacro match-acz-state-lhs-f-r (state__) `(svref ,state__ 5))
;;; notes repeated variables of LHS
;;; type : array[bool]
(defmacro match-acz-state-lhs-v-r (state__) `(svref ,state__ 6))
;;; notes repeated constants of RHS
;;; type : array[bool]
(defmacro match-acz-state-rhs-c-r (state__) `(svref ,state__ 7))
;;; notes repreated funcational terms of RHS
;;; type : array[bool]
(defmacro match-acz-state-rhs-f-r (state__) `(svref ,state__ 8))
;;; variables and funs acocunted for by RHS-c-sol
;;; type : fixnum
(defmacro match-acz-state-lhs-mask (state__) `(svref ,state__ 9))
;;; funs accounted for by RHS-c-sol
;;; type : fixnum
(defmacro match-acz-state-lhs-f-mask (state__) `(svref ,state__ 10))
;;; bit vector of all repeated (> 0) terms on LHS
(defmacro match-acz-state-lhs-r-mask (state__) `(svref ,state__ 11))
;;; solution matrix for constants
;;; type : array[fixnum]
(defmacro match-acz-state-rhs-c-sol (state__) `(svref ,state__ 12 ))
;;; max value of elements of RHS-C-sol
;;; type : fixnum
(defmacro match-acz-state-rhs-c-max (state__) `(svref ,state__ 13))
;;; solutions matrix; functional terms
;;; type : array[fixnum]
(defmacro match-acz-state-rhs-f-sol (state__) `(svref ,state__ 14))
;;; max value of elements of RHS-f-sol
;;; type : fixnum
(defmacro match-acz-state-rhs-f-max (state__) `(svref ,state__ 15))
;;; type : fixnum 11111 ... 1111
(defmacro match-acz-state-rhs-full-bits (state__) `(svref ,state__ 16))
;;; array of compatibility bitvectors; constants
;;; type : array[fixnum]
(defmacro match-acz-state-rhs-c-compat (state__) `(svref ,state__ 17))
;;; array of compatibility bitvectors; funcs
;;; type : array[fixnum]
(defmacro match-acz-state-rhs-f-compat (state__) `(svref ,state__ 18))
;;; number of constants on LHS after simplification
;;; type : fixnum
(defmacro match-acz-state-lhs-c-count (state__) `(svref ,state__ 19))
;;; number of functions on LHS after simplification
;;; type : fixnum
(defmacro match-acz-state-lhs-f-count (state__) `(svref ,state__ 20))
;;; number of variables on LHS after simplification
;;; type : fixnum
(defmacro match-acz-state-lhs-v-count (state__) `(svref ,state__ 21))
;;; number of constants on RHS after simplification
;;; type : fixnum
(defmacro match-acz-state-rhs-c-count (state__) `(svref ,state__ 22))
;;; number of functions on RHS after simplification
;;; type : fixnum
(defmacro match-acz-state-rhs-f-count (state__) `(svref ,state__ 23))
;;; t iff all solutions have been reported.
(defmacro match-acz-state-no-more (state__) `(svref ,state__ 24))
https://github.com/CafeOBJ/cafeobj/blob/master/chaos/e-match/match-acz.lisp
0
enum crap
{
shit = 0,
fuck,
dick,
ass,
turd,
fart,
};
static char *crap_to_str(int crap)
{
switch (crap)
{
case shit:
{
return "shit";
}
case fuck:
{
return "fuck";
}
case dick:
{
return "dick";
}
case ass:
{
return "ass";
}
case turd:
{
return "turd";
}
case fart:
{
return "fart";
}
default:
{
return "!!!UNKNOWN CRAP!!!";
}
}
}
Есть ли возможность через какую-нибудь плюсовую метушню с шаблонами, констэспрами и препроцессором нагенерировать подобную хрень из готового определения структуры?
+3
Кстати, разные эпизоды из Зеленого слоника можно сопоставить с разными статьями
о C++. Если статья про какие-то новые возможности, которые вводятся в
каком-нибудь С++20, это когда братишке покушать принесли. Если статья о том,
как можно метапрограммировать на шаблонах, то это когда вилкой говно чистить.
Ну что ты! Я тебе сейчас расскажу, вот смотри, Я тебе хорошую сейчас расскажу! Смотри, я… вот у нас здесь копипаста много… ой-ой… копипаста много, понимаешь? Смотри, копипаст, они тебе код читать мешает. А я вот, давай я здесь напишу метушни на темплейтах и консэкспрах с препроцессором сишным, и весь копипаст сокращу слышишь? Ну что, писать?
+4
#include <stdio.h>
#include <inttypes.h>
#include <stddef.h>
void printuint64(const uint64_t state);
uint64_t game_of_life8x8(const uint64_t old);
uint8_t getbit(uint64_t in, uint8_t y, uint8_t x);
uint8_t getbit(uint64_t in, uint8_t y, uint8_t x)
{
return !!((in) & (1ULL << ((y&0b111) + (x&0b111)*8)) );
}
uint64_t setbit(uint8_t y, uint8_t x, uint8_t bit)
{
if (bit)
{
return 1ULL << ((y&0b111) + (x&0b111)*8);
}
return 0;
}
uint64_t game_of_life8x8(const uint64_t old)
{
uint64_t new_state = 0;
#define GETBIT(y,x,val) getbit(val, y, x)
#define SETBIT(y,x,bit) setbit(y,x,bit)
#define SUMAROUND(y,x,val) ( \
GETBIT(y+1,x,val) + GETBIT(y-1,x,val) \
+ GETBIT(y,x+1,val) + GETBIT(y,x-1,val) \
+ GETBIT(y+1,x+1,val) + GETBIT(y+1,x-1,val) \
+ GETBIT(y-1,x+1,val) + GETBIT(y-1,x-1,val) \
)
#define CELLSTATE(y,x,val) \
(GETBIT(y,x,old) == 1 ? \
( ((SUMAROUND(y,x,val) == 2 ) || ( SUMAROUND(y,x,val) == 3 )) ? 1 : 0) \
: \
( ( SUMAROUND(y,x,val) == 3 ) ? 1 : 0 ) \
)
#define SETCELL_SH(y,x,val) SETBIT(y,x,CELLSTATE(y,x,val))
#define FILL_LINE(y) \
SETCELL_SH(y,7,old) | SETCELL_SH(y,6,old) | SETCELL_SH(y,5,old) | \
SETCELL_SH(y,4,old) | SETCELL_SH(y,3,old) | SETCELL_SH(y,2,old) | \
SETCELL_SH(y,1,old) | SETCELL_SH(y,0,old)
new_state = FILL_LINE(7) | FILL_LINE(6) | FILL_LINE(5)
| FILL_LINE(4) | FILL_LINE(3) | FILL_LINE(2)
| FILL_LINE(1) | FILL_LINE(0);
return new_state;
}
void printuint64(const uint64_t state)
{
for (size_t i = 7; i != SIZE_MAX; i--)
{
for (size_t j = 7; j != SIZE_MAX; j--)
{
printf("%u", !!((state >> (j+i*8)) & 1) );
}
printf("\n");
}
}
int main(void)
{
// Glider
uint64_t state =
(( 0b01000000ULL ) << 8*7 ) |
(( 0b00100000ULL ) << 8*6 ) |
(( 0b11100000ULL ) << 8*5 ) |
(( 0b00000000ULL ) << 8*4 ) |
(( 0b00000000ULL ) << 8*3 ) |
(( 0b00000000ULL ) << 8*2 ) |
(( 0b00000000ULL ) << 8*1 ) |
(( 0b00000000ULL ) << 8*0 );
for (size_t i = 0; i < 50; i++)
{
printuint64(state);
state = game_of_life8x8(state);
printf("\n");
}
return 0;
}
Conway's game of life внутри uint64_t (8 на 8) с периодическими граничными условиями.
0
// https://dev.to/saigowthamr/how-to-reverse-a-string-in-javascript-3i9c
// In this tutorial, we are going to learn three different ways to reverse a string
// in JavaScript by using the reverse method, reduce method.
// First way
const str = "hello"
str.split('').reverse().join('')
//"olleh"
// We used split method to split the string into an array of individual strings then chain it to reverse method.
// Second way
const str = "hello"
[...str].reduce((prev,next)=>next+prev)
//"olleh"
// First, we spread the string using spread operator and reverse the string using the reduce method
// Third way
function reverseString(str){
const arr = [...str]
let reverse= "";
while(arr.length){
reverse = reverse + arr.pop()
}
return reverse
}
// I mostly like the Second way to reverse a string using reduce method.
// Happy coding...
Это видимо такой вид соревнований, типа как вкрутить лампочку в патрон наиболее упоротым и неочевидным способом. Нахрена это нужно обычному программисту? Может это такой способ ручной обфускации? Тогда понятно
+1
#include <stdio.h>
#include <inttypes.h>
#include <string.h>
typedef struct
{
uint8_t arr[10];
uint8_t pos;
uint8_t is_swap;
} arr10;
arr10 bubble_sort_recursion(arr10 a);
void bubble_sort (uint8_t arr[static 10]);
void bubble_sort (uint8_t arr[static 10])
{
arr10 a;
memcpy(a.arr, arr, sizeof(a.arr));
a.pos = 0;
a.is_swap = 0;
a = bubble_sort_recursion(a);
memcpy(arr, a.arr, sizeof(a.arr));
}
arr10 bubble_sort_recursion(arr10 a)
{
if (a.pos != 9)
{
if (a.arr[a.pos] > a.arr[a.pos + 1])
{
uint8_t tmp = a.arr[a.pos + 1];
a.arr[a.pos + 1] = a.arr[a.pos];
a.arr[a.pos] = tmp;
a.is_swap = 1;
}
a.pos++;
return bubble_sort_recursion(a);
}
else
{
if (a.is_swap == 0)
{
return a;
}
else
{
a.pos = 0;
a.is_swap = 0;
return bubble_sort_recursion(a);
}
}
}
int main(void)
{
uint8_t arr[10] = {244, 90, 254, 109, 33, 85, 69, 81, 126, 71};
bubble_sort(arr);
printf("%" PRIu8 ", %" PRIu8 ", %" PRIu8 ", %" PRIu8 ", %" PRIu8 ", %" PRIu8 ", %" PRIu8 ", %" PRIu8 ", %" PRIu8 ", %" PRIu8,
arr[0], arr[1], arr[2], arr[3], arr[4], arr[5], arr[6], arr[7], arr[8], arr[9]);
return 0;
}
Рекурсивная сортировка пузырьком
+1
// https://habr.com/post/428846/
// Работа со строками на этапе компиляции в современном C++
// Определим статическую строку как массив символов, для удобства будем считать, что строка всегда оканчивается нулевым символом:
template<size_t Size>
using static_string = std::array<const char, Size>;
constexpr static_string<6> hello = {'H', 'e', 'l', 'l', 'o', '\0'};
constexpr auto hello = make_static_string("hello");
// Здесь нам поможет одна из форм вариативного шаблона, которая позволяет развернуть
// шаблонные аргументы как индексы для агрегатной инициализации нашей статической
// строки из строкового литерала:
template<size_t Size, size_t ... Indexes>
constexpr static_string<sizeof ... (Indexes) + 1> make_static_string(const char (& str)[Size]) {
return {str[Indexes] ..., '\0'};
}
constexpr auto hello = make_static_string<0, 1, 2, 3, 4>("hello"); // hello == "hello"
// ...
//Будем сравнивать строки посимвольно, пока не выявим различия, либо не достигнем конца хотя бы одной из строк.
// Поскольку constexpr for еще не изобрели, воспользуемся рекурсией и тернарным оператором:
template<size_t Size1, size_t Size2>
constexpr int static_string_compare(
const static_string<Size1>& str1,
const static_string<Size2>& str2,
int index = 0) {
return index >= Size1 && index >= Size2 ? 0 :
index >= Size1 ? -1 :
index >= Size2 ? 1 :
str1[index] > str2[index] ? 1 :
str1[index] < str2[index] ? -1 :
static_string_compare(str1, str2, index + 1);
}
Ммм, какой БАГОР
Крестобляди опять накостылили какой-то параши на шаблонах и радуются