Cでのマルチスレッドを使用した線形検索
ここでは、マルチスレッドの概念を適用して配列内の1つの要素を検索する方法を説明します。ここでのアプローチは非常に簡単です。いくつかのスレッドを作成してから、配列をさまざまな部分に分割します。別のスレッドが別の部分を検索します。その後、要素が見つかったら、フラグを有効にしてこれを識別します。
例
#include <stdio.h>
#include <pthread.h>
#define MAX 16
#define THREAD_MAX 4
int array[MAX] = { 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220 };
int key = 18;
int flag = 0; //flag to indicate that item is found in the array or not
int current_thread = 0;
void* ThreadSearch(void* args) { //This is linear search function. It will be running using all threads
int num = current_thread++;
for (int i = num * (MAX / 4); i < ((num + 1) * (MAX / 4)); i++){
if (array[i] == key)
flag = 1; //set flag if key is found
}
}
int main() {
pthread_t thread[THREAD_MAX];
for (int i = 0; i < THREAD_MAX; i++) { //create multiple threads
pthread_create(&thread[i], NULL, ThreadSearch, (void*)NULL);
}
for (int i = 0; i < THREAD_MAX; i++) {
pthread_join(thread[i], NULL); //wait untill all of the threads are completed
}
if (flag == 1)
printf("Key element is found\n");
else
printf("Key element is not present\n");
} 出力
$ gcc 1249.Thread_search.cpp -lpthread $ ./a.out Key element is found
-
Pythonプログラムでの線形探索
この記事では、線形検索とPython3.xでの実装について学習します。またはそれ以前。 アルゴリズム 指定されたarr[]の左端の要素から開始し、要素xをarr []の各要素と1つずつ比較します。 xがいずれかの要素と一致する場合は、インデックス値を返します。 xがarr[]のどの要素とも一致しない場合は、-1を返すか、要素が見つかりません。 次に、特定のアプローチの視覚的表現を見てみましょう- 例 def linearsearch(arr, x): for i in range(len(arr)): &nbs
-
PyTorchを使用した線形回帰?
線形回帰について 単純な線形回帰の基本 2つの連続変数間の関係を理解できます。 例- x=独立変数 重量 y=従属変数 高さ y=αx+β プログラムによる単純な線形回帰を理解しましょう- #Simple linear regression import numpy as np import matplotlib.pyplot as plt np.random.seed(1) n = 70 x = np.random.randn(n) y = x * np.random.randn(n) colors = np.random.r