const getTheNearestLocation = (locations, [ x, y ]) =>
locations.reduce((nearest, n) => {
const d = ((n[1][0] - x) ** 2 + (n[1][1] - y) ** 2) ** 0.5;
return nearest[1] < d ? nearest : [ n, d ];
}, [ null, Infinity ])[0];
const result = arr
.map(Object.values)
.sort((a, b) => b - a)
.slice(0, 3)
.join(', ');
map
следовало бы использовать flatMap
, но пока в элементах массива содержится по одному свойству - и так сойдёт. #include <iostream>
using namespace std;
int main()
{
int const n = 3;
int intArray[n];
int sum;
for (int i = 0; i < n; i++)
{
cin >> intArray[i];
}
for (int mask = 0; mask < (1 << n); ++mask)
{
sum = 0;
for (int i = 0; i < n; i++)
{
if (mask & (1 << i))
{
sum = sum + intArray[i];
}
}
cout << sum <<" ";
}
return 0;
}
mask = 0; mask < (1 << n); ++mask
).1 << i
.str.split(';').pop()
// или
str.replace(/.*;/, '')
// или
str.match(/;(.*)/)[1]
// или
/[^;]+$/.exec(str).shift()
// или
str.slice(str.lastIndexOf(';') + 1)
// или
[...str].reduce((acc, n) => n === ';' ? '' : acc + n)
// или
Array.from(str).filter((n, i, a) => !a.includes(';', i)).join('')
const newArr = arr.map(function(n) {
return [ ...n, ...Array(this - n.length).fill('') ];
}, Math.max(...arr.map(n => n.length)));
const max = arr.reduce((max, { length: n }) => max > n ? max : n, 0);
arr.forEach(n => n.push(...Array(max - n.length).fill('')));
<button class="button-third">
<input type="text" class="input-third" />
X
</button>
document.querySelector(".button-third").addEventListener("click", (evt) => {
console.log("button click")
});
document.querySelector(".input-third").addEventListener("click", (evt) => {
evt.stopPropagation();
console.log("input click")
});
getLine
, и он читает всю строку:#include <string>
#include <iostream>
int main()
{
std::string words;
std::cout << "Введите слова: ";
std::getline(std::cin, words);
std::cout << "Слова: " << words << "\n";
}
const getCode = function(s) { return s.slice(0, 3).toUpperCase();}
const getFromTree = (tree, childrenKey, getter = n => n) =>
Array.isArray(tree)
? tree.flatMap(n => [
getter(n),
...getFromTree(n[childrenKey], childrenKey, getter),
])
: [];
// или
function* flatTree(tree, childrenKey) {
if (
tree instanceof Object &&
tree[Symbol.iterator] instanceof Function
) {
for (const n of tree) {
yield n;
yield* getFromTree(n[childrenKey], childrenKey);
}
}
}
const getFromTree = function(tree, childrenKey, getter = n => n) {
const result = [];
for (const stack = this(tree); stack.length;) {
const n = stack.pop();
result.push(getter(n));
stack.push(...this(n[childrenKey]));
}
return result;
}.bind(x => x instanceof Array ? [...x].reverse() : []);
// или
const flatTree = function*(tree, childrenKey) {
const stack = [];
for (let [ i, arr ] = this(tree); ++i < arr.length || stack.length;) {
if (i === arr.length) {
[ i, arr ] = stack.pop();
} else {
yield arr[i];
stack.push([ i, arr ]);
[ i, arr ] = this(arr[i][childrenKey]);
}
}
}.bind(x => [ -1, x?.constructor === Array ? x : [] ]);
getFromTree(tree, 'children').forEach(n => console.log(n));
// или
for (const n of flatTree(tree, 'children')) {
console.log(n);
}
$values = array_combine(
array_column($example2, 'SECTION_ID'),
array_column($example2, 'VALUE')
);
$example3 = array_map(function($n) use($values) {
$n['VALUE'] = $values[$n['SECTION_ID']];
return $n;
}, $example1);
field = [
[' ', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' '],
]
#обращение к ячейке будет таким: field[1][1]
columns = ['1', '2', '3'] #обозначения столбцов
rows = ['a', 'b', 'c'] #обозначения строк
def cell2index(cell):
# превращаем строку вида b1 в индексы в списке
row = rows.index(cell[0].lower()) #если номера строки нет, вылетит исключение ValueError
col = columns.index(cell[1]) #если номера столбца нет, вылетит исключение ValueError
return row, col #возвращаем кортеж - пару значений
# пример работы - ход крестиков
while True: #повторяем, пока пользователь не введет правильный номер
cell = input('Введите ячейку для хода: ')
try:
r, c = cell2index(cell) #если номер неверный, тут вылетит исключение ValueError
if field[r][c] != ' ': #ячейка уже занята?
print('Ячейка уже занята!')
else:
break #если исключения не было, выходим из цикла
except ValueError:
print('Номер ячейки неправильный')
#сюда попадём только если номер ячейки правильный и она свободна
field[r][c] = 'x'