Algoritma Analizi etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Algoritma Analizi etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

19 Şubat 2021 Cuma

Algoritma Analizi - O(n2) - İkinci Dereceden Yani Quadratic

Giriş
En basit örneği iç içe iki tane döngüdür.

Örnek - complexity of two nested loops over different datasets
Elimizde şöyle bir kod olsun
for things in list_a {
  for things in list_b {
    if (list_a.thing relates to list_b.thing) go ping
  }
}
Açıklaması şöyle. İki listenin de büyüklüğü farklı olabilse dahi en kötü durum düşünüleceği için sonuç O(n * m) yerine O(n^2)  olarak söylenir
It'd be O(n*m) where the worst case is n = m or n*n thus O(n^2). We are interested in worst case run time for Big O. If the data sets sizes are different then it will still be in O(n^2) since we can't guarantee that, for example, the second dataset will be a logarithmic relation to the first. If we could, they wouldn't necessarily be independent. They might be but again, we are looking at worst case and O(n logn) is within O(n^2).
Örnek - complexity of two nested loops one has fixed size
Bu soru anagramları gruplama sorusu. Şöyle yaparız. Algoritma analizi O (n * 26)'dır. Yani aslında O(n)'dir. complexity of two nested loops over different datasets sorusu ile farkını göstermek için ekledim

Her string için harf frekansı hesaplanır. Yani abbccc için şunu gibidir #1#2#3#0#0#0...#0. Her anagram aynı string'i verecektir. Böylece string'ler gruplanır.
public static List<List<String>> groupTitles(String[] strs){
  if (strs.length == 0) 
    return new ArrayList<List<String>>();

  Map<String, List<String>> res = new HashMap<>();
  int[] count = new int[26];
  for (String s : strs) {
    Arrays.fill(count, 0);
    for (char c : s.toCharArray()){
      int index = c - 'a';
      count[index]++;
    }
    StringBuilder delimStr = new StringBuilder("");
    for (int i = 0; i < 26; i++) {
      delimStr.append('#');
      delimStr.append(count[i]);
    }
            
    String key = delimStr.toString();
    if (!res.containsKey(key)) 
      res.put(key, new ArrayList<String>());
            
    res.get(key).add(s);
  }
  return new ArrayList<List<String>>(res.values());
}
Kullanmak için şöyle yaparız. duel,dule,deul bir grup, speed,spede bir grup, cars ise tek başına bir grup olur
String titles[] = {"duel","dule","speed","spede","deul","cars"};
List<List<String>> grups = groupTitles(titles);

String query = "spede";
// Iterate over groups
for (List<String> group : groups) {
  if (group.contains(query))
    System.out.println(g);
}
Örnek
Elimizde şöyle bir kod olsun. Burada da ikinci döngü aslında sabit bir değere bakarak dönmüyor. Ancak yine de sonuç O(n^2)
int n = ...;
int x = 0;
for (int i = 0; i < n; ++i) {
  for (int i = j; j < n; ++j) {
    ++x;
  }
}
Selection Sort
Bu sıralama algoritmasında içteki döngü dıştaki sıralanmamış eleman ile karşılaştırma yaparak, en küçük elemanı bulur ve yer değiştirir. Örnek burada.

Bubble Sort
n2 (n kare) arama için Bubble Sort güzel bir örnek. Bu algoritma yanyana bulunan çiftlerin karşılaştırılması şeklinde çalışıyor. Her bir eleman yanındaki ile yer değiştirmeye ihtiyaç duymayıncaya kadar tüm liste tekrar tekrar dolaşılıyor.

17 Şubat 2020 Pazartesi

Algoritma Analizi - NP-Complete - Çözümü Bulmak Zor Ancak Doğrulamak Kolay İse

Giriş
Bir NP-Hard problem bir başka NP-Hard probleme dönüştürülebiliyorsa NP-Complete oluyor.

NP-Complete bir problemin bir başka NP-Complete probleme dönüştürülebileceği kabul edilir. Dolayısıyla NP-Complete bir çözüm bulmak diğer problemlerin de çözülmesi anlamına gelir.

Bazı Polynomial problemler NP-Complete problem olabiliyor. Örnekleri şöyle.
- 2-SAT is in P; 3-SAT is NP-complete.
- Exact cover by 2-sets is in P; exact cover by 3-sets is NP-complete
- Two-dimensional matching is in P; three-dimensional matching is NP-complete
- Graph 2-coloring is trivially in P; graph 3-coloring is NP-complete
SAT, NP-Complete olarak sınıflandırılan ilk problem. Açıklaması şöyle
SAT was the first problem shown to be NP-complete, in Stephen Cook's seminal paper. Even nowadays, when introducing the theory of NP-completeness, the starting point is usually the NP-completeness of SAT.
Set Cover Problemi - Küme Örtme Problemi
Set Cover problemleri NP Complete problemlerdir. Set Cover problemi elimizde bir çok set olduğunu, bu setlerin hepsinin birleşiminin (union) evrensel seti oluşturduğunu varsayar. Evrensel seti oluşturmak için kullanılacak en az sayıdaki seti bulma problemidir. Kümelerimiz şunlar olsun

S1 = {2,3}
S2 = {2, 5}
S3 = {4, 5}
S4 = {4}
S5 = {5}

Evrensel kümemiz şudur
S {2, 3, 4, 5}.

S1, S3 kümeleri (2 küme) ile evrensel kümeye erişebilirim. Aynı zamanda S1, S4, S5 (3 küme) ile de erişebilirdim ama sayısı 3 olduğu için seçmiyorum. Gerçek hayatta şöyle bir örnek verilebilir.
Bir ilçenin 5 mahallesi olsun. Her mahalleye sağlık hizmeti götürmek isteniyor. Kurulacak sağlık ocağı her mahalleye en fazla 20 dakika mesafede olsun da isteniyor. Tüm mahallelerine hizmet verecek en az sayıda kaç sağlık ocağı kurabilirim.
Probleme yukarıdaki gibi kümeler oluşturularak başlanır.

S. Ocak1 = {Mahalle2,Mahalle3}
S. Ocak2 = {Mahalle2,Mahalle5}
S. Ocak3 = {Mahalle4,Mahalle5}
S. Ocak4 = {Mahalle4}
S. Ocak5 = {Mahalle5}

Evrensel kümemiz {Mahalle2, Mahalle3, Mahalle4, Mahalle5} 'tir.
Tüm mahallelere hizmet vermek için S.Ocak1, S.Ocak2, S.Ocak3 yeterlidir.


Diğer bir Örnek
Başka bir NP problem örneği
S kümesini A ve B olarak iki alt kümeye ayır. A ve B'deki elemanların toplamı eşit olsun. 
Bu problemin kolay bir çözümü yok. Muhtemelen tüm olasılıkları denemek gerekiyor. Ancak bize A ve B kümeleri hazır verilseydi sonucu kolayca doğrulayabilirdik.

Degree Constrained Minimum Spanning Tree
Degree Constrained Spanning Tree NP Complete problemlerdir.

Edge matching problems
Açıklaması şöyle
Edge matching problems, such as the Eternity II puzzle are NP-complete
Hamiltonian Path
Açıklaması şöyle. 
... start with any node, then go through each other node exactly once, and then go back to the beginning, so it means the path is actually a cycle. A path that goes through all nodes exactly once called a Hamiltonian path. Consequently, such a cycle is a Hamiltonian cycle.
Eğer Hamiltonian Path kullanırken bazı kısıtlar varsa, ve bu kısıtlar yüzünden döngü tamamlanamıyorsa,  backtracking search veya depth-first search kullanılabilir. Açıklaması şöyle
At some steps, we can find out that there are no available nodes to pick. It might happen if there are no more connections (because of constraints) or if all neighbor nodes have been visited already. This issue looks like the issue we had with the naive algorithm. With a graph, it’s more clear that we can do a step back and pick another random node. If we did a step back and there are still no nodes to pick, we do another step back.

Repeat until we visit all nodes and return to the first one. The cycle is complete.

Such a search is called backtracking search or depth-first search.
Çözümü Doğrulamak
Çözümü doğrulamak için ilave bilgi gerekebilir. Açıklaması şöyle.
Also note that "checking" does not always just mean "here's an answer, go check it." When one is checking a NP-complete answer, one is typically given extra information derived from the solving of the problem. My favorite example is proving that a number is prime. One can provide a list of "witness" integers which, together, can prove that a number is prime. Finding the correct list of numbers is very difficult, but once you have the list, the verification is trivial.

Algoritma Analizi - NP Hard - Çözümü Bulmak ve Doğrulamak Bile Zor İse

NP-Hard
Çözümü bulmanın yanında, doğrulamanın da zor olduğu problem sınıfına bu isim verilir. Açıklaması şöyle.
It is hard to check that it is the correct solution.
Özellikle çok fazla sayıda kombinasyona sahip problemlerde çözümü doğrulamak çok daha zor. Açıklaması şöyle.
...i.e. to find an optimal solution you had to create all possible combinations of assignments, and select one that fits best. Since this is of exponential time complexity, it is only feasible for small problems, and yours is apparently already too large.
Traveling Salesman Problem
Açıklaması şöyle
Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once and returns to the origin city?
Aslında bu problem NP-Complete olan Hamiltonian Path'in bir benzeri ancak daha zor. Açıklaması şöyle
... start with any node, then go through each other node exactly once, and then go back to the beginning, so it means the path is actually a cycle. A path that goes through all nodes exactly once called a Hamiltonian path. Consequently, such a cycle is a Hamiltonian cycle.