SlideShare a Scribd company logo
1 of 11
T.C. İSTANBUL AYDIN ÜNİVERSİTESİ
-BİLGİSAYAR MÜHENDİSLİĞİ YÜKSEK LİSANS-BYL563 İleri Algoritma Analizi-

BRUTEFORCE VE HORSPOOL
ALGORİTMALARININ
KARŞILAŞTIRMALI
ANALİZİ

Hazırlayan: Veysi ERTEKİN (YL1213.010020)
İçindekiler
İçindekiler........................................................................................................................................................................2
Problemin Tanımı............................................................................................................................................................3
Arama Algortimaları........................................................................................................................................................3
Bruteforce Search:.......................................................................................................................................................3
Horspool Search:.........................................................................................................................................................4
Algoritmaların Analizi......................................................................................................................................................5
1.Test Çıktısı................................................................................................................................................................ 5
Sonuç........................................................................................................................................................................... 7
Ekler................................................................................................................................................................................ 8
1.TestCase.java:...........................................................................................................................................................8
Main.java:....................................................................................................................................................................8
AAlgorithm.java (Abstract Class):................................................................................................................................9
BruteForce.java:..........................................................................................................................................................9
Horspool.java:...........................................................................................................................................................10
Kaynakça....................................................................................................................................................................... 11
Problemin Tanımı
Oluşturulmuş bir veri havuzundan (yazı, ikilik data, veritabanında saklanan bir blok vs olabilir) verilen bir
şablonun elde edilmesi gerekmektedir. Bu tür işlemlerde elde bulunan veri kümesinden belirli özelliklere sahip
bir öğeyi bulmak adına arama algoritmaları kullanılır.

Arama Algortimaları
Bruteforce Search:
Algoritma işleyiş sırası şu şekildedir:
1. Yazıdan ve şablondan birer karakter al. Yazının sonuna gelindiyse 4. adıma geç.
2. Karakterler eşleşiyorsa 4. adıma git. Eşleşmiyorsa yazının bir sonraki karakteri, şablonun ise ilk
karkterini al ve 3. adımı tekrar et.
3. Şablonda bir sonraki karteri ve yazıdan bir sonraki karakteri al. Karakterler eşleşiyor ve şablonun
sonuna gelindiyse 4. adıma, şablon bitmemiş ise 2. adımdan devam et.
4. Bulunan index’i (bulunmadıysa yazının son index’i) ni belirlenen şekilde çıktıya bas.
En iyi
n*m

Ortalama
n*m

(Genel algoritma yapısı)
do
if (yazı karakteri== şablon karakteri)
bir sonraki karakterlere geç
else
yazıyı bir artır ve şablonun başındaki karakterden tekrar başla
while (yazının sonuna gelene kadar veya şablon bulunana kadar)

En kötü
n*m
Horspool Search:
Nigel Horspool tarafından 1980’lerde bulunmuştur. Yazı tabanlı bir algoritma olmakla birlikte BruteForce
algoritmasına nazaran uzun vadede daha performanslı bir algoritmadır.
En iyi
n

Ortalama
~n

En kötü
n*m

•

Aşağıdaki gibi bir karakter kaydırma değerlerinin bulunduğu bir tablo hazırlanır:

•

Şablon elimizdeki yazı içerisinde şablonun son karakterinden başlayarak karşılaştırırız, karakter
uyuşmazlığı oluşursa yazı içerisinden en son karşılaştırma yapmakta olduğumuz karakterin yukarıdaki
kaydırma değerlikleri tablosundaki değeri kadar kaydırma yaparız(şablon içerisinde yer almayan
karakterlerde şablon boyu kadar kaydırma gerçekleşir):

(Genel algoritma yapısı)
Horspool (P = p1p2…pm,T = t1t2…tn)
Ön İşleme
c ; d[c] ← m (karakter kaydırma değerliklerini şablonun boyutu olarak ata)
j ; 1…m-1 ; d[pj] ← m – j (şablon içerisinde yer alan karakterlerin right-most
değerliklerini bul, not: son karakter göz ardı edilir)
Arama
index←0
For index ≤ n-m Do
j ←m
for j > 0 ve (index +j) = p*j
Do j ← j-1
If j = 0 -> (index+1). konumda sonuç bulundu
index ← index +d[tpos+m]
For Sonu
Algoritmaların Analizi
Algoritmalar Java programlama dilinde soldaki resimde
gözüken hiyerarşik yapıda yazıldı.(Kaynak kodlarını eklerde
bulabilirsiniz)
JUNIT tabanlı TestCase.java’da algoritmalara hız testi
uygulanacak biçimde her biri için bir test hazırlandı.
“Main.java” da ise solda belirtilen TestCase 10000000
karakterlik yazı ile 1’den 100’e kadar karakter içeren şablon yazı
için tekrarlı olarak çalıştırıldı.

1. Test Çıktısı

Yazı Boyutu
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000

Şablon Boyutu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

BruteForce Eşleşen
Konum
80
973
23407
404426
9022507
8697733
9652870
7777683
7717201
8701330
8051443
9175457
9375920
8685293
7720784
8249263
9670253
9534411
8116247
7563326
8523191
7930522
9097249
7692704
8125680
9972953
8259860
9309122
7757384
9562744

BruteForce
Geçen Süre
0.015395
0.035407
0.669144
1.41526
25.066208
24.203095
26.750357
21.695859
21.269434
24.161018
22.223374
25.43824
26.022715
23.734079
21.190409
23.063909
26.437851
26.298788
22.569748
20.78143
23.24659
21.734858
24.69777
21.335117
22.399384
27.660167
22.577445
25.638368
21.227868
26.303919

Horspool
Eşleşen Konum
80
973
23407
404426
9022507
8697733
9652870
7777683
7717201
8701330
8051443
9175457
9375920
8685293
7720784
8249263
9670253
9534411
8116247
7563326
8523191
7930522
9097249
7692704
8125680
9972953
8259860
9309122
7757384
9562744

Horspool Geçen
Süre
0.115458
0.171904
0.738418
4.051296
64.972631
54.692242
52.700205
37.115415
34.291054
34.092979
31.13366
31.469258
31.140844
26.334709
23.170643
23.336903
26.237724
22.42812
20.727551
18.369126
19.506774
18.484072
19.564246
15.720774
17.170928
18.655975
16.56798
17.684075
15.040854
17.943214
Yazı Boyutu
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000

Şablon Boyutu
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

BruteForce Eşleşen
Konum
9895385
8499140
7583286
9531987
7761371
7712962
9559433
7515724
9050593
9526825
8054999
8306592
8385770
8530273
9128265
9193643
8237723
8636092
7983668
7950437
8904124
8311936
9231711
9062756
9110324
9820924
9590341
7629241
9985700
7703704
8104215
8788878
8481886
9498661
7980693
8610630
8625892
9104906
9040568
7767272
7560120
8105025
9198056
9455268
9752805
8417312
8752620
9884949
7724351
8493743

BruteForce
Geçen Süre
26.885315
23.492899
20.731142
25.865692
21.084701
21.164751
25.884678
20.847113
24.96871
26.384484
22.556406
22.907912
23.07725
23.676607
25.072879
25.125734
22.903806
24.018876
22.350634
21.61786
24.447354
22.947424
25.213482
24.445814
25.15293
26.808343
26.165883
20.339611
27.63451
21.367957
22.281873
23.822853
23.539596
25.657867
22.148454
23.591937
23.588859
25.228363
24.182057
21.46289
20.852759
22.276741
25.224258
25.90777
27.049009
23.144473
23.951653
27.13727
21.230947
22.738574

Horspool
Eşleşen Konum
9895385
8499140
7583286
9531987
7761371
7712962
9559433
7515724
9050593
9526825
8054999
8306592
8385770
8530273
9128265
9193643
8237723
8636092
7983668
7950437
8904124
8311936
9231711
9062756
9110324
9820924
9590341
7629241
9985700
7703704
8104215
8788878
8481886
9498661
7980693
8610630
8625892
9104906
9040568
7767272
7560120
8105025
9198056
9455268
9752805
8417312
8752620
9884949
7724351
8493743

Horspool Geçen
Süre
18.245457
15.624302
12.239071
16.469455
14.335277
13.415204
16.907171
13.316167
14.006349
15.338993
12.650102
12.528486
13.873958
13.38185
13.099106
13.710777
13.670238
12.475632
12.701417
11.410851
14.550285
13.930404
14.255226
12.241124
14.234187
12.382239
12.778388
9.534786
14.018665
11.778778
11.934775
12.152862
11.731056
13.419823
11.752095
11.063451
11.895776
13.208406
10.810983
10.628302
11.014703
10.953125
12.262162
12.892821
14.155675
11.587888
11.165567
11.58019
10.971598
9.792899
Yazı Boyutu
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000
10000000

Şablon Boyutu
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

BruteForce Eşleşen
Konum
8728844
9614302
8294439
7770644
8285835
9872020
9612393
9554464
8443063
8338894
8431209
9056025
8174466
7963535
7525507
8614163
9589647
8685110
9375489
7595301

BruteForce
Geçen Süre
23.997836
26.811422
23.162433
21.387457
22.852492
26.732911
26.128423
25.821049
23.362561
22.852492
22.93357
24.866082
22.633892
22.167955
20.973348
23.963455
26.58769
23.649409
25.935993
20.566422

Horspool
Eşleşen Konum
8728844
9614302
8294439
7770644
8285835
9872020
9612393
9554464
8443063
8338894
8431209
9056025
8174466
7963535
7525507
8614163
9589647
8685110
9375489
7595301

Horspool Geçen
Süre
12.528999
12.248308
11.153765
9.480392
10.3784
11.938367
15.833154
11.757739
12.015339
10.365571
12.720403
12.118482
10.285007
11.269223
11.210724
10.293217
13.713343
10.674486
10.733497
9.549155

Sonuç
BruteForce algoritması sürekli aynı karmaşıklıkta veri ararken, Horspool algoritması ilk aşamalarda yüksek
karmaşıklıkta arama yapmasının ardından yazı şablonunun boyutunun birkaç karakter artmasından sonra
yaklaşık %50 oranında daha az kaynak tüketimi ile daha performanslı olarak çalışmıştır.
Ekler
1. TestCase.java:
package com.hw02;
import java.util.HashMap;
import java.util.Map;
import
import
import
import
import

org.junit.After;
org.junit.Before;
org.junit.Rule;
org.junit.Test;
org.junit.rules.TestName;

public class TestCase {
AAlgorithm algorithm;
@Rule
public TestName name = new TestName(); // Çalıştırılan her algoritmanın adını almak için “Kural” tanımladık
public static char[] text; // Yazı ‘Main’ sınıfında oluşturuluyor
public static char[] pattern; // Yazı ‘Main’ sınıfında oluşturuluyor
public static Map<String, Double> map = new HashMap<String, Double>();
long start;
@Before
public void setUp() throws Exception { // burası her algoritma başlamadan önce çalışıyor
algorithm = createObject(Class.forName("com.hw02.algorithm." + name.getMethodName())); // Hangi
algoritma çalıştırılacağını belirledik
start = System.nanoTime(); // başlangıç saatini aldık
}
@After
public void tearDown() throws Exception { // burası her algoritma bitince çalışıyor
double duration = (System.nanoTime() - start) / 1000000D;
map.put(name.getMethodName(), duration);
}
@Test
public void BruteForce() {
exec();
}
@Test
public void Horspool() {
exec();
}
private void exec() {
try { // Elimizdek yazı içinde şablonu belirlenmiş algoritma ile çalıştırıyoruz ve bulunan index’i
saklıyoruz
map.put(name.getMethodName() + "_INDEX", Double.valueOf(algorithm.sort(text, pattern)));
}
catch (Exception e) {
e.printStackTrace(); // hata alırsak loga basıyoruz
}
}
kısım

public static AAlgorithm createObject(Class<?> klass) { // algoritmaların Sınıf’ı ile nesnesini oluşturan
try {

}

return (AAlgorithm) klass.newInstance();
}
catch (Exception e) {
e.printStackTrace();// Hata alırsak görmek adına loga basıyoruz
return null;
}

}

Main.java:
package com.hw02;
import
import
import
import
import
import

java.io.File;
java.io.FileNotFoundException;
java.io.PrintWriter;
java.io.UnsupportedEncodingException;
java.security.SecureRandom;
java.util.Arrays;

import org.junit.runner.JUnitCore;
public class Main {
private static SecureRandom random = new SecureRandom();
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
int patternSize = 1; // Şablonun başlangıç boyutu
final int textSize = 10000000; // Yazı boyutu
final int MAX_PATTERN_SIZE = 100; // En fazla şablon boyutu
int startIndex; // Başlangıç konumu
char line = '0'; // ilk test çalıştırılmasında ilk başa “enter” basmayacağız sonrasında her test
çalıştırılmasından sonra
StringBuilder builder = new StringBuilder();
TestCase.text = generateArray(textSize);
for (; patternSize <= MAX_PATTERN_SIZE; patternSize++) {
startIndex = (TestCase.text.length / 4) * 3 + random.nextInt((TestCase.text.length / 4) patternSize);

// Şablonun yazıda olduğundan emin olmak adına,
// bi altta elimizdeki yazıyı 4’e böldüğümüzdeki son çeyreğinden örnek şablon aldık
TestCase.pattern = Arrays.copyOfRange(TestCase.text, startIndex, startIndex + patternSize);
JUnitCore.runClasses(TestCase.class); // Testi çalıştır
// Aşağıdaki gibi sırasıyla “TestCase” sınıfında oluşan test çıktılarını önbelleğe al
if (line == 'n')
builder.append(line);
builder.append(textSize);
builder.append('t'); // her bir veri kolonu arasına “tab” karakteri koyduk
builder.append(patternSize);
builder.append('t');
builder.append(TestCase.map.get("BruteForce_INDEX").intValue());
builder.append('t');
builder.append(TestCase.map.get("BruteForce"));
builder.append('t');
builder.append(TestCase.map.get("Horspool_INDEX").intValue());
builder.append('t');
builder.append(TestCase.map.get("Horspool"));
line = 'n';
TestCase.map.clear();
System.gc();
}

PrintWriter print = new PrintWriter(System.getProperty("user.home") + File.separator + "Desktop" +
File.separator + "out.txt", "UTF-8"); // Masaüstünde bir “out.txt” adında bir dosya oluşturduk
print.print(builder); // Testlerden elde ettiğimiz veriyi dosyaya yazdık
print.close(); // dosyayı kapattık
}

}

public static char[] generateArray(int size) {
char[] array = new char[size];
for (int i = size - 1, j = 0; i >= 0; i--, j++) {
array[j] = AAlgorithm.ALPHABET[random.nextInt(AAlgorithm.ALPHABET.length)];
}
return array;
}

AAlgorithm.java (Abstract Class):
package com.hw02;
public abstract class AAlgorithm {
public static final char[] ALPHABET = "abcçdefgğhıijklmnoöprsştuüvyz".toCharArray();

}

/**
* bulunan index’i döndürür
*/
public abstract int sort(char[] text, char[] pattern);

BruteForce.java:
package com.hw02.algorithm;
import com.hw02.AAlgorithm;
public class BruteForce extends AAlgorithm {
@Override
public int sort(char[] text, char[] pattern) {
int i, j;
for (i = 0, j = 0; i < text.length && j < pattern.length; i++) { // yazı boyutu kadar gitmeliyiz, şablon
boyutu kadar kontrol ettiysek demekki sonuca ulaşmışız.
if (text[i] == pattern[j]) // eşleşen karakter varsa bir sonrakini kontrol et
j++;
else {
i -= j;
j = 0;
}
}
if (j == pattern.length)
return i - pattern.length;
else
return -1;
}
}

Horspool.java:
package com.hw02.algorithm;
import com.hw02.AAlgorithm;
public class Horspool extends AAlgorithm {
private static int[] shiftTable = new int[ALPHABET.length];
@Override
public int sort(char[] text, char[] pattern) {
prepareTable(pattern); // kaydırma boyutlarının tutulduğu tabloyu oluştur
// şablonun boyutuyla başla
int i = pattern.length - 1, k;
// bulundu mu?
isMatch: while (i < text.length) {
k = i;
for (int j = pattern.length - 1; j >= 0; j--) {
if (pattern[j] == text[k]) {// karakter uyuşuyorsa bir sonrakine geç
k--;
continue;
}
else {
i += shiftTable[getCharIndex(text[i])]; // karakterin kaydırma değerliği
kadar kaydır

continue isMatch;
}

}
return k + 1; // yukarıdaki “for” döngüsünde eğer “j” sıfırandıysa buraya gelecek ve şablonun
tamamen eşleşmiş olduğu anlaşılacak, bu yüzden bulduğumuz konumu döndürüyoruz.
}
return -1;
}
public void prepareTable(char[] pattern) {
for (int i = 0; i < shiftTable.length; i++) {
shiftTable[i] = pattern.length; // ilk başta bütün karakter değerliklerini şablon byutu yap
}
for (char c : pattern) {
shiftTable[getCharIndex(c)] = shiftCount(c, pattern); // şablon karakterlerini sırasıyla
değerliklerini hesapla
}
}
private Integer shiftCount(char c, char[] pattern) {
for (int i = pattern.length - 2/* şablonun son karakterini yoksay */; i >= 0; i--) {
if (pattern[i] == c)
return pattern.length - 1 - i; // m-1-n formülüyle right-most index’i bul
}
return pattern.length;
}

}

public int getCharIndex(char i) { // karakterin alfabedeki konumunu bul
int j = 0;
for (char ch : ALPHABET) {
if (ch == i)
return j;
j++;
}
return -1;
}
Kaynakça
1. http://en.wikipedia.org/wiki/Search_algorithms
2. http://en.wikipedia.org/wiki/Category:Search_algorithms
3. http://en.wikipedia.org/wiki/Linear_search
4. http://en.wikipedia.org/wiki/Brute-force_search
5. http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm
6. http://alg.csie.ncnu.edu.tw/course/StringMatching/Horspool.ppt
7. String matching Boyer Moore's and Horspool Algorithm, https://www.youtube.com/watch?
v=rDPuaNw9_Eo

More Related Content

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

BruteForce ve Horspool Algoritmalarının Karşılaştırılmalı Analizi

  • 1. T.C. İSTANBUL AYDIN ÜNİVERSİTESİ -BİLGİSAYAR MÜHENDİSLİĞİ YÜKSEK LİSANS-BYL563 İleri Algoritma Analizi- BRUTEFORCE VE HORSPOOL ALGORİTMALARININ KARŞILAŞTIRMALI ANALİZİ Hazırlayan: Veysi ERTEKİN (YL1213.010020)
  • 2. İçindekiler İçindekiler........................................................................................................................................................................2 Problemin Tanımı............................................................................................................................................................3 Arama Algortimaları........................................................................................................................................................3 Bruteforce Search:.......................................................................................................................................................3 Horspool Search:.........................................................................................................................................................4 Algoritmaların Analizi......................................................................................................................................................5 1.Test Çıktısı................................................................................................................................................................ 5 Sonuç........................................................................................................................................................................... 7 Ekler................................................................................................................................................................................ 8 1.TestCase.java:...........................................................................................................................................................8 Main.java:....................................................................................................................................................................8 AAlgorithm.java (Abstract Class):................................................................................................................................9 BruteForce.java:..........................................................................................................................................................9 Horspool.java:...........................................................................................................................................................10 Kaynakça....................................................................................................................................................................... 11
  • 3. Problemin Tanımı Oluşturulmuş bir veri havuzundan (yazı, ikilik data, veritabanında saklanan bir blok vs olabilir) verilen bir şablonun elde edilmesi gerekmektedir. Bu tür işlemlerde elde bulunan veri kümesinden belirli özelliklere sahip bir öğeyi bulmak adına arama algoritmaları kullanılır. Arama Algortimaları Bruteforce Search: Algoritma işleyiş sırası şu şekildedir: 1. Yazıdan ve şablondan birer karakter al. Yazının sonuna gelindiyse 4. adıma geç. 2. Karakterler eşleşiyorsa 4. adıma git. Eşleşmiyorsa yazının bir sonraki karakteri, şablonun ise ilk karkterini al ve 3. adımı tekrar et. 3. Şablonda bir sonraki karteri ve yazıdan bir sonraki karakteri al. Karakterler eşleşiyor ve şablonun sonuna gelindiyse 4. adıma, şablon bitmemiş ise 2. adımdan devam et. 4. Bulunan index’i (bulunmadıysa yazının son index’i) ni belirlenen şekilde çıktıya bas. En iyi n*m Ortalama n*m (Genel algoritma yapısı) do if (yazı karakteri== şablon karakteri) bir sonraki karakterlere geç else yazıyı bir artır ve şablonun başındaki karakterden tekrar başla while (yazının sonuna gelene kadar veya şablon bulunana kadar) En kötü n*m
  • 4. Horspool Search: Nigel Horspool tarafından 1980’lerde bulunmuştur. Yazı tabanlı bir algoritma olmakla birlikte BruteForce algoritmasına nazaran uzun vadede daha performanslı bir algoritmadır. En iyi n Ortalama ~n En kötü n*m • Aşağıdaki gibi bir karakter kaydırma değerlerinin bulunduğu bir tablo hazırlanır: • Şablon elimizdeki yazı içerisinde şablonun son karakterinden başlayarak karşılaştırırız, karakter uyuşmazlığı oluşursa yazı içerisinden en son karşılaştırma yapmakta olduğumuz karakterin yukarıdaki kaydırma değerlikleri tablosundaki değeri kadar kaydırma yaparız(şablon içerisinde yer almayan karakterlerde şablon boyu kadar kaydırma gerçekleşir): (Genel algoritma yapısı) Horspool (P = p1p2…pm,T = t1t2…tn) Ön İşleme c ; d[c] ← m (karakter kaydırma değerliklerini şablonun boyutu olarak ata) j ; 1…m-1 ; d[pj] ← m – j (şablon içerisinde yer alan karakterlerin right-most değerliklerini bul, not: son karakter göz ardı edilir) Arama index←0 For index ≤ n-m Do j ←m for j > 0 ve (index +j) = p*j Do j ← j-1 If j = 0 -> (index+1). konumda sonuç bulundu index ← index +d[tpos+m] For Sonu
  • 5. Algoritmaların Analizi Algoritmalar Java programlama dilinde soldaki resimde gözüken hiyerarşik yapıda yazıldı.(Kaynak kodlarını eklerde bulabilirsiniz) JUNIT tabanlı TestCase.java’da algoritmalara hız testi uygulanacak biçimde her biri için bir test hazırlandı. “Main.java” da ise solda belirtilen TestCase 10000000 karakterlik yazı ile 1’den 100’e kadar karakter içeren şablon yazı için tekrarlı olarak çalıştırıldı. 1. Test Çıktısı Yazı Boyutu 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 Şablon Boyutu 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 BruteForce Eşleşen Konum 80 973 23407 404426 9022507 8697733 9652870 7777683 7717201 8701330 8051443 9175457 9375920 8685293 7720784 8249263 9670253 9534411 8116247 7563326 8523191 7930522 9097249 7692704 8125680 9972953 8259860 9309122 7757384 9562744 BruteForce Geçen Süre 0.015395 0.035407 0.669144 1.41526 25.066208 24.203095 26.750357 21.695859 21.269434 24.161018 22.223374 25.43824 26.022715 23.734079 21.190409 23.063909 26.437851 26.298788 22.569748 20.78143 23.24659 21.734858 24.69777 21.335117 22.399384 27.660167 22.577445 25.638368 21.227868 26.303919 Horspool Eşleşen Konum 80 973 23407 404426 9022507 8697733 9652870 7777683 7717201 8701330 8051443 9175457 9375920 8685293 7720784 8249263 9670253 9534411 8116247 7563326 8523191 7930522 9097249 7692704 8125680 9972953 8259860 9309122 7757384 9562744 Horspool Geçen Süre 0.115458 0.171904 0.738418 4.051296 64.972631 54.692242 52.700205 37.115415 34.291054 34.092979 31.13366 31.469258 31.140844 26.334709 23.170643 23.336903 26.237724 22.42812 20.727551 18.369126 19.506774 18.484072 19.564246 15.720774 17.170928 18.655975 16.56798 17.684075 15.040854 17.943214
  • 6. Yazı Boyutu 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 Şablon Boyutu 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 BruteForce Eşleşen Konum 9895385 8499140 7583286 9531987 7761371 7712962 9559433 7515724 9050593 9526825 8054999 8306592 8385770 8530273 9128265 9193643 8237723 8636092 7983668 7950437 8904124 8311936 9231711 9062756 9110324 9820924 9590341 7629241 9985700 7703704 8104215 8788878 8481886 9498661 7980693 8610630 8625892 9104906 9040568 7767272 7560120 8105025 9198056 9455268 9752805 8417312 8752620 9884949 7724351 8493743 BruteForce Geçen Süre 26.885315 23.492899 20.731142 25.865692 21.084701 21.164751 25.884678 20.847113 24.96871 26.384484 22.556406 22.907912 23.07725 23.676607 25.072879 25.125734 22.903806 24.018876 22.350634 21.61786 24.447354 22.947424 25.213482 24.445814 25.15293 26.808343 26.165883 20.339611 27.63451 21.367957 22.281873 23.822853 23.539596 25.657867 22.148454 23.591937 23.588859 25.228363 24.182057 21.46289 20.852759 22.276741 25.224258 25.90777 27.049009 23.144473 23.951653 27.13727 21.230947 22.738574 Horspool Eşleşen Konum 9895385 8499140 7583286 9531987 7761371 7712962 9559433 7515724 9050593 9526825 8054999 8306592 8385770 8530273 9128265 9193643 8237723 8636092 7983668 7950437 8904124 8311936 9231711 9062756 9110324 9820924 9590341 7629241 9985700 7703704 8104215 8788878 8481886 9498661 7980693 8610630 8625892 9104906 9040568 7767272 7560120 8105025 9198056 9455268 9752805 8417312 8752620 9884949 7724351 8493743 Horspool Geçen Süre 18.245457 15.624302 12.239071 16.469455 14.335277 13.415204 16.907171 13.316167 14.006349 15.338993 12.650102 12.528486 13.873958 13.38185 13.099106 13.710777 13.670238 12.475632 12.701417 11.410851 14.550285 13.930404 14.255226 12.241124 14.234187 12.382239 12.778388 9.534786 14.018665 11.778778 11.934775 12.152862 11.731056 13.419823 11.752095 11.063451 11.895776 13.208406 10.810983 10.628302 11.014703 10.953125 12.262162 12.892821 14.155675 11.587888 11.165567 11.58019 10.971598 9.792899
  • 7. Yazı Boyutu 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 Şablon Boyutu 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 BruteForce Eşleşen Konum 8728844 9614302 8294439 7770644 8285835 9872020 9612393 9554464 8443063 8338894 8431209 9056025 8174466 7963535 7525507 8614163 9589647 8685110 9375489 7595301 BruteForce Geçen Süre 23.997836 26.811422 23.162433 21.387457 22.852492 26.732911 26.128423 25.821049 23.362561 22.852492 22.93357 24.866082 22.633892 22.167955 20.973348 23.963455 26.58769 23.649409 25.935993 20.566422 Horspool Eşleşen Konum 8728844 9614302 8294439 7770644 8285835 9872020 9612393 9554464 8443063 8338894 8431209 9056025 8174466 7963535 7525507 8614163 9589647 8685110 9375489 7595301 Horspool Geçen Süre 12.528999 12.248308 11.153765 9.480392 10.3784 11.938367 15.833154 11.757739 12.015339 10.365571 12.720403 12.118482 10.285007 11.269223 11.210724 10.293217 13.713343 10.674486 10.733497 9.549155 Sonuç BruteForce algoritması sürekli aynı karmaşıklıkta veri ararken, Horspool algoritması ilk aşamalarda yüksek karmaşıklıkta arama yapmasının ardından yazı şablonunun boyutunun birkaç karakter artmasından sonra yaklaşık %50 oranında daha az kaynak tüketimi ile daha performanslı olarak çalışmıştır.
  • 8. Ekler 1. TestCase.java: package com.hw02; import java.util.HashMap; import java.util.Map; import import import import import org.junit.After; org.junit.Before; org.junit.Rule; org.junit.Test; org.junit.rules.TestName; public class TestCase { AAlgorithm algorithm; @Rule public TestName name = new TestName(); // Çalıştırılan her algoritmanın adını almak için “Kural” tanımladık public static char[] text; // Yazı ‘Main’ sınıfında oluşturuluyor public static char[] pattern; // Yazı ‘Main’ sınıfında oluşturuluyor public static Map<String, Double> map = new HashMap<String, Double>(); long start; @Before public void setUp() throws Exception { // burası her algoritma başlamadan önce çalışıyor algorithm = createObject(Class.forName("com.hw02.algorithm." + name.getMethodName())); // Hangi algoritma çalıştırılacağını belirledik start = System.nanoTime(); // başlangıç saatini aldık } @After public void tearDown() throws Exception { // burası her algoritma bitince çalışıyor double duration = (System.nanoTime() - start) / 1000000D; map.put(name.getMethodName(), duration); } @Test public void BruteForce() { exec(); } @Test public void Horspool() { exec(); } private void exec() { try { // Elimizdek yazı içinde şablonu belirlenmiş algoritma ile çalıştırıyoruz ve bulunan index’i saklıyoruz map.put(name.getMethodName() + "_INDEX", Double.valueOf(algorithm.sort(text, pattern))); } catch (Exception e) { e.printStackTrace(); // hata alırsak loga basıyoruz } } kısım public static AAlgorithm createObject(Class<?> klass) { // algoritmaların Sınıf’ı ile nesnesini oluşturan try { } return (AAlgorithm) klass.newInstance(); } catch (Exception e) { e.printStackTrace();// Hata alırsak görmek adına loga basıyoruz return null; } } Main.java: package com.hw02; import import import import import import java.io.File; java.io.FileNotFoundException; java.io.PrintWriter; java.io.UnsupportedEncodingException; java.security.SecureRandom; java.util.Arrays; import org.junit.runner.JUnitCore;
  • 9. public class Main { private static SecureRandom random = new SecureRandom(); public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException { int patternSize = 1; // Şablonun başlangıç boyutu final int textSize = 10000000; // Yazı boyutu final int MAX_PATTERN_SIZE = 100; // En fazla şablon boyutu int startIndex; // Başlangıç konumu char line = '0'; // ilk test çalıştırılmasında ilk başa “enter” basmayacağız sonrasında her test çalıştırılmasından sonra StringBuilder builder = new StringBuilder(); TestCase.text = generateArray(textSize); for (; patternSize <= MAX_PATTERN_SIZE; patternSize++) { startIndex = (TestCase.text.length / 4) * 3 + random.nextInt((TestCase.text.length / 4) patternSize); // Şablonun yazıda olduğundan emin olmak adına, // bi altta elimizdeki yazıyı 4’e böldüğümüzdeki son çeyreğinden örnek şablon aldık TestCase.pattern = Arrays.copyOfRange(TestCase.text, startIndex, startIndex + patternSize); JUnitCore.runClasses(TestCase.class); // Testi çalıştır // Aşağıdaki gibi sırasıyla “TestCase” sınıfında oluşan test çıktılarını önbelleğe al if (line == 'n') builder.append(line); builder.append(textSize); builder.append('t'); // her bir veri kolonu arasına “tab” karakteri koyduk builder.append(patternSize); builder.append('t'); builder.append(TestCase.map.get("BruteForce_INDEX").intValue()); builder.append('t'); builder.append(TestCase.map.get("BruteForce")); builder.append('t'); builder.append(TestCase.map.get("Horspool_INDEX").intValue()); builder.append('t'); builder.append(TestCase.map.get("Horspool")); line = 'n'; TestCase.map.clear(); System.gc(); } PrintWriter print = new PrintWriter(System.getProperty("user.home") + File.separator + "Desktop" + File.separator + "out.txt", "UTF-8"); // Masaüstünde bir “out.txt” adında bir dosya oluşturduk print.print(builder); // Testlerden elde ettiğimiz veriyi dosyaya yazdık print.close(); // dosyayı kapattık } } public static char[] generateArray(int size) { char[] array = new char[size]; for (int i = size - 1, j = 0; i >= 0; i--, j++) { array[j] = AAlgorithm.ALPHABET[random.nextInt(AAlgorithm.ALPHABET.length)]; } return array; } AAlgorithm.java (Abstract Class): package com.hw02; public abstract class AAlgorithm { public static final char[] ALPHABET = "abcçdefgğhıijklmnoöprsştuüvyz".toCharArray(); } /** * bulunan index’i döndürür */ public abstract int sort(char[] text, char[] pattern); BruteForce.java: package com.hw02.algorithm; import com.hw02.AAlgorithm; public class BruteForce extends AAlgorithm { @Override public int sort(char[] text, char[] pattern) {
  • 10. int i, j; for (i = 0, j = 0; i < text.length && j < pattern.length; i++) { // yazı boyutu kadar gitmeliyiz, şablon boyutu kadar kontrol ettiysek demekki sonuca ulaşmışız. if (text[i] == pattern[j]) // eşleşen karakter varsa bir sonrakini kontrol et j++; else { i -= j; j = 0; } } if (j == pattern.length) return i - pattern.length; else return -1; } } Horspool.java: package com.hw02.algorithm; import com.hw02.AAlgorithm; public class Horspool extends AAlgorithm { private static int[] shiftTable = new int[ALPHABET.length]; @Override public int sort(char[] text, char[] pattern) { prepareTable(pattern); // kaydırma boyutlarının tutulduğu tabloyu oluştur // şablonun boyutuyla başla int i = pattern.length - 1, k; // bulundu mu? isMatch: while (i < text.length) { k = i; for (int j = pattern.length - 1; j >= 0; j--) { if (pattern[j] == text[k]) {// karakter uyuşuyorsa bir sonrakine geç k--; continue; } else { i += shiftTable[getCharIndex(text[i])]; // karakterin kaydırma değerliği kadar kaydır continue isMatch; } } return k + 1; // yukarıdaki “for” döngüsünde eğer “j” sıfırandıysa buraya gelecek ve şablonun tamamen eşleşmiş olduğu anlaşılacak, bu yüzden bulduğumuz konumu döndürüyoruz. } return -1; } public void prepareTable(char[] pattern) { for (int i = 0; i < shiftTable.length; i++) { shiftTable[i] = pattern.length; // ilk başta bütün karakter değerliklerini şablon byutu yap } for (char c : pattern) { shiftTable[getCharIndex(c)] = shiftCount(c, pattern); // şablon karakterlerini sırasıyla değerliklerini hesapla } } private Integer shiftCount(char c, char[] pattern) { for (int i = pattern.length - 2/* şablonun son karakterini yoksay */; i >= 0; i--) { if (pattern[i] == c) return pattern.length - 1 - i; // m-1-n formülüyle right-most index’i bul } return pattern.length; } } public int getCharIndex(char i) { // karakterin alfabedeki konumunu bul int j = 0; for (char ch : ALPHABET) { if (ch == i) return j; j++; } return -1; }
  • 11. Kaynakça 1. http://en.wikipedia.org/wiki/Search_algorithms 2. http://en.wikipedia.org/wiki/Category:Search_algorithms 3. http://en.wikipedia.org/wiki/Linear_search 4. http://en.wikipedia.org/wiki/Brute-force_search 5. http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm 6. http://alg.csie.ncnu.edu.tw/course/StringMatching/Horspool.ppt 7. String matching Boyer Moore's and Horspool Algorithm, https://www.youtube.com/watch? v=rDPuaNw9_Eo