- 1
- 2
- 3
- 4
- 5
Задачка с собеседования.
Удалить из неупорядоченного массива чисел представленного как std::vector<int> элемент за O(1).
А я тупил, и дошел до ответа только с подсказками.
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+1
Задачка с собеседования.
Удалить из неупорядоченного массива чисел представленного как std::vector<int> элемент за O(1).
А я тупил, и дошел до ответа только с подсказками.
+1
#include <array>
#include <iostream>
using namespace std;
int main() {
::array arr {1, 2, 3};
int a, b, c;
::tie(a, b, c) = arr;
printf("%d %d %d",a,b,c);
return 0;
}
https://godbolt.org/z/RRmruC
+1
function isVowel(char){
return "аоэиуыеёюя".indexOf(char.toLocaleLowerCase())>=0 ? 1 : 0;
}
function vorefy(text)
{
// Г => C 0.85
// Г => Г 0.15
// С => С 0.30
// С => Г 0.70
var markov = [[0.3,0.7],[0.85,0.15]];
var mCorr = [ 1/Math.sqrt(0.3*0.7), 1/Math.sqrt(0.85*0.15) ];
//степень влияния марковских вореантностей
var pow = x => Math.pow(x,2);
var prev=null;
return text.replace(/./g,(char,offset,text) =>
{
if (E2R[char]){
var replace = Object.entries(E2R[char]);
if (1==replace.length) {
prev = replace[0][0];
return prev;
}
var r = Math.random()*200, probability=0;
for (const [k, v] of replace) {
vowel = isVowel(k);
probability += v * ((null==prev) ? 1
: pow(
mCorr[vowel]*2*markov[isVowel(prev)][vowel]
));
if (r<=probability) {
prev = k;
return prev;
}
}
}
prev=null;
return char;
});
}
Марковым отмечена еще одна устойчивая закономерность открытых текстов, связанная с чередованием гласных и согласных букв. Им были подсчитаны частоты встречаемости биграмм вида гласная-гласная (г, г), гласная-согласная (г, с), согласная-гласная (с, г), согласная-согласная (с, с)
[color=blur]https://ideone.com/VpkwXT[/color]
+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
// https://www.linux.org.ru/forum/development/15520475
// *Какой #define макрит for в while?
#include <stdio.h>
#include <stdlib.h>
#define FOR(a, b, c, ...) {a;while(b){__VA_ARGS__ c;}}
int main(void)
{
for(int i = 0; i < 10; i++)
{
printf("test %d\n", i);
}
printf("\n");
FOR(int i = 0, i < 10, i++,
{
printf("test %d\n", i);
}
)
return EXIT_SUCCESS;
}
+1
//Use this to convert OffSet to postive:
var offset = new Date().getTimezoneOffset();
console.log(offset);
this.timeOffSet = offset + (-2*offset);
console.log(this.timeOffSet);
Это такой особый JS way, или я чего-то не понимаю?
+1
template <typename function_type, typename vector_type>
function_type read_memory(HANDLE hProcess, function_type base_address, std::vector< vector_type >&& offsets) {
function_type tmp = base_address;
for (function_type i : **reinterpret_cast< vector_type** >( &offsets )) {
ReadProcessMemory(hProcess, reinterpret_cast< PBYTE* >( tmp + i ), &tmp, sizeof(function_type), nullptr);
}
return tmp;
}
int main() {
std::vector< DWORD > offset = {
0x10,
0x14,
0x158
};
auto buffer = read_memory< DWORD, DWORD >(hProcess, base_address, std::move(offset));
}
Полуговнокодер читает память чужого процесса...
+1
SET @from = 11836;
SET @to = 11840;
INSERT INTO `sprinter_catalog_tree` (
`sprinter_catalog_tree`.`level`,
`sprinter_catalog_tree`.`position`,
`sprinter_catalog_tree`.`parent_id`,
`sprinter_catalog_tree`.`catalog`,
`sprinter_catalog_tree`.`info_id`,
-- ...
)
SELECT
`sprinter_catalog_tree`.`level`,
`sprinter_catalog_tree`.`position`,
@to,
`sprinter_catalog_tree`.`catalog`,
`sprinter_catalog_tree`.`info_id`,
`sprinter_catalog_tree`.`format_id`,
`sprinter_catalog_tree`.`linked_id`,
`sprinter_catalog_tree`.`linked_shablon_id`,
-- ...
FROM `sprinter_catalog_tree` where parent_id = @from order by id;
INSERT INTO `sprinter_catalog_tree` (
`sprinter_catalog_tree`.`level`,
`sprinter_catalog_tree`.`position`,
`sprinter_catalog_tree`.`parent_id`,
`sprinter_catalog_tree`.`catalog`,
`sprinter_catalog_tree`.`info_id`,
-- ...
)
SELECT
a.`level`,
a.`position`,
(SELECT id from sprinter_catalog_tree as b where b.parent_id = @to and b.name like (SELECT name from sprinter_catalog_tree where id = a.parent_id)),
a.`catalog`,
a.`info_id`,
a.`format_id`,
a.`linked_id`,
a.`linked_shablon_id`,
-- ...
FROM `sprinter_catalog_tree` as a where parent_id in (SELECT id FROM sprinter_catalog_tree where parent_id = @from) order by id;
INSERT INTO `sprinter_catalog_info`
(`name`,
`eng_name`,
`text`,
-- ..
)
SELECT
`sprinter_catalog_info`.`name`,
`sprinter_catalog_info`.`eng_name`,
`sprinter_catalog_info`.`text`,
`sprinter_catalog_info`.`short_text`,
-- ...
FROM `sprinter_catalog_info` where id in (SELECT info_id from `sprinter_catalog_tree` where parent_id = @from or parent_id in (SELECT id from `sprinter_catalog_tree` where parent_id = @from));
CREATE temporary table if not exists ids
SELECT id from `sprinter_catalog_tree` where parent_id = @to or parent_id in (SELECT id from `sprinter_catalog_tree` where parent_id = @to);
UPDATE sprinter_catalog_tree as a SET info_id = (SELECT id from sprinter_catalog_info as b where a.name like b.name order by id desc limit 1) where a.id in (SELECT id from ids);
DROP table ids;
Высрал вот такое говно в качестве write-n-throw скрипта.
Дано: есть элементы дерева, хранящиеся в таблице sprinter_catalog_tree, связаны друг с другом через parent_id. Каждому из них соответствует указанный в info_id элемент таблицы sprinter_catalog_info.
Задача: скопировать все вложенные в раздел @from каталога элементы и его подразделы (вложенность не более 1 уровня) в раздел @to, так чтобы у них были новые id, и также скопировать соответствующие им sprinter_catalog_info. Скопированные sprinter_catalog_tree должны указывать на корректные sprinter_catalog_info, id которых заранее не известны.
Вот такое говно получилось, расскажите как надо было?
+1
define method display (i :: <integer>)
do-display-integer(i);
end;
define method display (s :: <string>)
do-display-string(s);
end;
define method display (f :: <float>)
do-display-float(f);
end;
define method display (c :: <collection>)
for (item in c)
display(item); // runtime dispatch
end;
end;
В закромах истории нашёлся язык с runtime dispatch/multimethods.
+1
function send_message_with_photo($token, $peer_id, $message, $image_file_path) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
/* Получаем ссылку для загрузки фотографии */
curl_setopt($ch, CURLOPT_URL, 'https://api.vk.com/method/photos.getMessagesUploadServer');
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
"access_token" => $token,
"v" => "5.103"
));
$result = json_decode(curl_exec($ch), true);
$upload_url = $result['response']['upload_url'];
/* Отправляем фотографию */
curl_setopt($ch, CURLOPT_URL, $upload_url);
$file = curl_file_create($image_file_path);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
"photo" => $file,
));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
$result = json_decode(curl_exec($ch), true);
$server = $result['server'];
$photo = $result['photo'];
$hash = $result['hash'];
/* Сохраняем фотографию */
curl_setopt($ch, CURLOPT_URL, 'https://api.vk.com/method/photos.saveMessagesPhoto');
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
"access_token" => $token,
"v" => "5.103",
"server" => $server,
"photo" => $photo,
"hash" => $hash
));
$result = json_decode(curl_exec($ch), true);
$photo_id = strval($result['response'][0]['id']);
$owner_id = strval($result['response'][0]['owner_id']);
$attachment = "photo" . $owner_id . "_" . $photo_id;
/* Отправляем сообщение */
curl_setopt($ch, CURLOPT_URL, 'https://api.vk.com/method/messages.send');
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
"access_token" => $token,
"v" => "5.103",
"random_id" => rand(),
"peer_id" => $peer_id,
"message" => $message,
"attachment" => $attachment
));
$result = json_decode(curl_exec($ch), true);
curl_close($ch);
}
Говнокод для загрузки фото в ВК)