- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
let array = [-2, 4, -10, 8];
let count = 0;
for (let i = 0; i < array.length; i++) {
if (!String(array[i]).startsWith("-")) {
count += array[i]
}
}
console.log(count) // 12
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+1
let array = [-2, 4, -10, 8];
let count = 0;
for (let i = 0; i < array.length; i++) {
if (!String(array[i]).startsWith("-")) {
count += array[i]
}
}
console.log(count) // 12
Пробовался в speed'кодинге, получил задачу: "написать код для нахождения суммы всех положительных элементов массива", ну и наскоро получилось такое xD
+4
// https://govnokod.ru/26890#comment571155
// bormand 2 часа назад #
// Можно брейнфак запилить на операторах. Как раз вроде унарных хватает.
// & * - ~ ! -- + ++ --
#include <array>
#include <vector>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <limits>
struct Brainfuck {
public:
using IPType = uint16_t;
constexpr static size_t MAX_MEMORY = std::numeric_limits<IPType>::max();
std::array<uint8_t, MAX_MEMORY> memory{};
std::vector<char> app{};
IPType ip = 0;
IPType cell = 0;
IPType find_matching_tag(IPType cur_ip, char open, char close, int ip_direction)
{
size_t stack_size = 0;
do {
if (app[cur_ip] == close) {
--stack_size;
}
if (app[cur_ip] == open) {
++stack_size;
}
cur_ip += ip_direction;
} while (stack_size > 0);
return cur_ip - ip_direction;
}
IPType find_matching_close_tag(IPType cur_ip)
{
return find_matching_tag(cur_ip, '[', ']', 1);
}
IPType find_matching_open_tag(IPType cur_ip)
{
return find_matching_tag(cur_ip, ']', '[', -1);
}
void loop_open()
{
if (memory[cell] == 0) {
ip = find_matching_close_tag(ip);
} else {
++ip;
}
}
void loop_close()
{
if (memory[cell] != 0) {
ip = find_matching_open_tag(ip);
} else {
++ip;
}
}
void exec(char op)
{
switch (op) {
case '>': ++cell; break;
case '<': --cell; break;
case '+': ++memory[cell]; break;
case '-': --memory[cell]; break;
case '.': std::putchar(memory[cell]); break;
case ',': memory[cell] = static_cast<uint8_t>(std::getchar()); break;
case '[': loop_open(); return; // no ip advancing
case ']': loop_close(); return; // no ip advancing
}
ip++;
}
void run()
{
while (ip < app.size()) {
exec(app[ip]);
}
}
public:
Brainfuck & operator++() { app.push_back('>'); return *this; }
Brainfuck & operator--() { app.push_back('<'); return *this; }
Brainfuck & operator+() { app.push_back('+'); return *this; }
Brainfuck & operator-() { app.push_back('-'); return *this; }
Brainfuck & operator*() { app.push_back('.'); return *this; }
Brainfuck & operator&() { app.push_back(','); return *this; }
Brainfuck & operator!() { app.push_back('['); return *this; }
Brainfuck & operator~() { app.push_back(']'); return *this; }
Brainfuck & operator>>(const Brainfuck &) { run(); return *this; }
};
https://wandbox.org/permlink/XJUKGyb4YbnBVwOI
Бонус («99 bottles of beer»): https://pastebin.com/s4sBK9nX (взято с https://github.com/fabianishere/brainfuck/blob/master/examples/bottles-1.bf).
+1
#include <iostream>
#include <map>
std::map<std::string, int> get_map()
{
return {
{ "hello", 1 },
{ "world", 2 },
{ "it's", 3 },
{ "me", 4 },
};
}
int main()
{
for (auto&& [ k, v ] : get_map())
std::cout << "k=" << k << " v=" << v << '\n';
return 0;
}
−1
parallel_for(1, 6, [](int value) {
wstringstream ss;
ss << value << L' ';
wcout << ss.str();
});
Вместо того чтобы заняться допиливанием С++11 для студии, макрософт решила написать своё параллельное апи и глупые примерчики к нему на тему вывести случайную перестановку элементов.
+78
public class Settings {
public static String CURRENCY = "руб.";
public static void setCurrency(String currency) {
CURRENCY = currency != null ? currency : "руб.";
}
}
Мой проект. Можно ли считать это ГК?
+2
struct S { struct Inner { }; };
template<int N> struct X;
auto refl = ˆS;
auto tmpl = ˆX;
void f() {
typename [:refl:] * x; // OK: declares x to be a pointer-to-S
[:refl:] * x; // error: attempt to multiply int by x
[:refl:]::Inner i; // OK: splice as part of a nested-name-specifier
typename [:refl:]{}; // OK: default-constructs an S temporary
using T = [:refl:]; // OK: operand must be a type
struct C : [:refl:] {}; // OK: base classes are types
template [:tmpl:]<0>; // OK: names the specialization
[:tmpl:] < 0 > x; // error: attempt to compare X with 0
}
и да, это приняли.
https://lists.isocpp.org/sg7/2021/04/0226.php
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p2320r0.pdf
+1
// https://gcc.gnu.org/onlinedocs/gcc-10.1.0/gcc/Common-Function-Attributes.html
access
access (access-mode, ref-index)
access (access-mode, ref-index, size-index)
// примеры:
__attribute__ ((access (read_only, 1))) int puts (const char*);
__attribute__ ((access (read_only, 1, 2))) void* memcpy (void*, const void*, size_t);
__attribute__ ((access (read_write, 1), access (read_only, 2))) char* strcat (char*, const char*);
__attribute__ ((access (write_only, 1), access (read_only, 2))) char* strcpy (char*, const char*);
__attribute__ ((access (write_only, 1, 2), access (read_write, 3))) int fgets (char*, int, FILE*);
В GCC 10 какой-то новый атрибут access появился, чтоб более строго что-то там гарантировать:
The access attribute enables the detection of invalid or unsafe accesses by functions to which they apply or their callers, as well as write-only accesses to objects that are never read from. Such accesses may be diagnosed by warnings such as -Wstringop-overflow, -Wuninitialized, -Wunused, and others.
The access attribute specifies that a function to whose by-reference arguments the attribute applies accesses the referenced object according to access-mode. The access-mode argument is required and must be one of three names: read_only, read_write, or write_only. The remaining two are positional arguments.
The required ref-index positional argument denotes a function argument of pointer (or in C++, reference) type that is subject to the access. The same pointer argument can be referenced by at most one distinct access attribute.
The optional size-index positional argument denotes a function argument of integer type that specifies the maximum size of the access. The size is the number of elements of the type referenced by ref-index, or the number of bytes when the pointer type is void*. When no size-index argument is specified, the pointer argument must be either null or point to a space that is suitably aligned and large for at least one object of the referenced type (this implies that a past-the-end pointer is not a valid argument). The actual size of the access may be less but it must not be more.
0
https://medium.com/@evnowandforever/f-you-i-quit-hiring-is-broken-bb8f3a48d324
tl;tr:
Чувак говорит что его заебали интервьюеры которые просят на доске перевернуть бинарное дерево.
Он считает что надо давать практические задачи, пускай даже и на дом. Если для решения практической задачи ему понадобится перевернуть бинарное дерево -- он почитает статью и напишет алгоритм.
А интервьюеры сначала хотят дерево, а потом ноют.
−3
// https://github.com/Qqwy/raii_with/blob/74e4c66a821fba6a483d62a8c583b3fab06e3443/raii/raii.h#L60
/**
* Custom Control Structure Macro to provide Resource Acquisition Is Initialization (and Resource Relinquishment is Destruction).
*
* Use this to run a block of code with `var_decl` initialized to `init`, where at the end of the block (or at an earlier `safe_return`),
* the passed `destr`-function will automatically be called with the given resource.
*
* Gotcha's:
* 1. Do not use `return` from within `raii_with`, but only `safe_return`, because otherwise the destructors will not be run.
* 2. Do not perform pointer-swaps with `var_decl`; the destructor will still be run on the original structure, because `raii` keeps its own reference to the resource.
*/
#define raii_with(var_decl, init, destr) \
while(1) /* i.c.m. break on l.4, so we can jump past the user-supplied block */ \
if(0) \
raii_glue(__raii_with_finished, __LINE__): \
break; \
else \
/* initialize _tmp lifetime list elem so replacement `raii_lifetime_list` can have previous one as tail. */ \
for(struct raii_lifetime_list_t _tmp = {.elem.resource = init, .elem.destructor = destr, .next = raii_lifetime_list};;) \
/* initialize user-supplied variable name */ \
for(var_decl = _tmp.elem.resource;;) \
if (1) { \
/* Fill `_tmp`'s tail before `raii_lifetime_list` is shadowed */ \
_tmp.next = raii_lifetime_list; \
goto raii_glue(__raii_with_setup, __LINE__); \
} else \
raii_glue(__raii_with_setup, __LINE__): \
/* Shadow `raii_lifetime_list` with inner version */ \
for(struct raii_lifetime_list_t *raii_lifetime_list = &_tmp;;) \
if(1){ \
goto raii_glue(__raii_with_body, __LINE__); \
} else \
while (1) /* so break works as expected */ \
while (1) /*so continue works as expected */ \
if (1){ \
/*after the else-block (or break or continue), destruct and finish */ \
destruct_raii_lifetime(raii_lifetime_list->elem); \
goto raii_glue(__raii_with_finished, __LINE__); \
} else \
raii_glue(__raii_with_body, __LINE__):
#endif // RAII_WITH_H
raii
A simple library to provide RAII in standard-compliant C99, using raii_with(resource, initializer, destructor) { ... }-syntax:
0
Бесконечный оффтоп имени Гологуба #6
#1: https://govnokod.ru/28992 https://govnokod.xyz/_28992
#2: https://govnokod.ru/29053 https://govnokod.xyz/_29053
#3: https://govnokod.ru/29075 https://govnokod.xyz/_29075
#4: https://govnokod.ru/29110 https://govnokod.xyz/_29110
#5: https://govnokod.ru/29127 https://govnokod.xyz/_29127