你將如何創建這個陣列,[1,2,3,4,-1,-2,-3,1,2,-1,-2,-3,-4,-5,1,2, 3]
來自這個陣列:[1,1,1,1,0,0,0,1,1,0,0,0,0,0,1,1,1]
使用您喜歡的任何編程語言。如果您想在語言上表現出差異,則可以使用多個。
為了向您展示創建的陣列是什么,在這里它們以更并行的方式顯示:
[1,1,1,1, 0 ,0 ,0, 1,1, 0, 0, 0, 0, 0, 1,1,1]
[1,2,3,4, -1,-2,-3, 1,2, -1,-2,-3,-4,-5, 1,2,3]
它應該在陣列索引為 true(1) 時計數,并且在為負數時計數,但計數為負數。很好奇你們想出了什么代碼以及代碼有多簡單,因為我被卡住了。
感謝您的任何啟發。
uj5u.com熱心網友回復:
Python解決方案,使用itertools.groupby:
from itertools import groupby
a = [1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1]
b = []
for k, g in groupby(a):
b.extend(i * (k or -1) for i, _ in enumerate(g, 1))
print(b)
印刷:
[1, 2, 3, 4, -1, -2, -3, 1, 2, -1, -2, -3, -4, -5, 1, 2, 3]
uj5u.com熱心網友回復:
input_arr = [1,1,1,1,0,0,0,1,1,0,0,0,0,0,1,1,1]
res = [1] if input_arr[0] else [-1]
for i in range(1, len(input_arr):
if input_arr[i]:
if res[-1] > 0: res.append(res[-1] 1)
else: res.append(1)
else:
if res[-1] < 0: res.append(res[-1]-1)
else: res.append(-1)
print(res)
這是另一個python解決方案。邏輯很簡單,不需要太多解釋。
uj5u.com熱心網友回復:
這是 JavaScript 中的示例解決方案
const countArr = (arr) => {
// Checks if the arr contains 1 and 0s only
const isValid = arr.every(a => a === 1 || a === 0);
if (!isValid) return 'collection should have 1 and 0 values only';
let counter = 0; // Counting variable
return arr.map(a => {
// Reset counter IF
// current item (a) = 1 and counter is in negative
// OR
// current item (a) = 0 and counter is in positive
if ((a === 1 && counter < -1) || (a === 0 && counter > 1)) {
counter = 0
};
// Counter increment/decrement
counter = a === 1 ? counter 1 : counter - 1;
return counter;
});
}
const collection = [1,1,1,1,0,0,0,1,1,0,0,0,0,0,1,1,1]; // Collection
console.log(collection);
console.log(countArr(collection));
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/462144.html
下一篇:Python中的3種方式快速排序
