DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Floyd's Cycle Algorithm for Fraud Detection in Java Systems
  • Understanding HyperLogLog for Estimating Cardinality
  • Hybrid Search: A New Frontier in Enterprise Search
  • Optimizing the Traveling Salesman Problem: Integrating Graph Neural Networks With Branch and Bound Algorithms

Trending

  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • Unlocking AI Coding Assistants Part 3: Generating Diagrams, Open API Specs, And Test Data
  • Integrating Security as Code: A Necessity for DevSecOps
  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Metal and the Simulated Annealing Algorithm

Metal and the Simulated Annealing Algorithm

The Simulated Annealing algorithm described in this article demonstrates its effectiveness as a powerful tool for finding optimal solutions to complex problems.

By 
Vitaly Kuznetsov (Ippolitov) user avatar
Vitaly Kuznetsov (Ippolitov)
·
Jan. 29, 25 · Analysis
Likes (2)
Comment
Save
Tweet
Share
2.4K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, I’ll walk you through Bryan Luke’s Simulated Annealing Algorithm, a powerful probabilistic approach to finding optimal solutions among numerous possibilities. We’ll explore its implementation using the classic N-Queens problem as an example. Unlike greedy algorithms, simulated annealing intelligently explores the solution space to avoid being trapped in poor solutions.

What Is Simulated Annealing?

Simulated annealing is inspired by the physical process of annealing metals, where a material is heated and then cooled slowly to improve its internal structure. The algorithm mimics this process to find solutions in complex problem spaces.

Developed in the late 1980s, simulated annealing has become a go-to tool in fields like computer science, engineering, finance, and even biology. It’s especially effective for optimization problems with vast and irregular search spaces.

The Algorithm in Action


Algorithm Phases

  1. Initialization: Begin by selecting a random initial state and setting a temperature. The temperature controls the likelihood of accepting new states at each step:
    • High temperature: Lower probability of accepting a new state.
    • Low temperature: Higher probability of accepting a new state.
  2. Iterative changes: Make a small, random modification to the current solution to create a new candidate state.
  3. State evaluation: Compare the new state to the current state. Accept the better state. If the new state is worse, accept it with a probability determined by the formula:
    • exp((curScore - newScore) / temperature) >= random[0..1]
  4. Cooling schedule: Gradually reduce the temperature.
  5. Termination: End the process when a termination condition is met.

Solution Example Using N-Queens Problem

Let’s explore how this algorithm can solve the N-Queens problem: positioning N queens on an N×N chessboard so that no two queens threaten each other on diagonals, verticals, or horizontals.

Solution Example Using N-Queens Problem


Representing the Board

We’ll represent the chessboard as a 1D array, where each element represents a queen’s position on the Y-axis. Since all values in the array are unique, no queens threaten each other horizontally or vertically.

Evaluating the Board

The goal is to minimize the calculated number of queens that threaten each other. A solution is reached when this number becomes zero.

Generating New States

At each step, swap the positions of two random queens along the X-axis.

Algorithm Implementation in Kotlin

Kotlin
 
for (temperature in temperatures) {
  val new = current.randomSwapQueens()
  // acceptNewScore is always true here new.score < current.score
  val acceptNewScore = exp((current.score - new.score) / temperature) > Random.nextFloat()
  if (acceptNewScore) {
    current = new
    if (current.score < best.score) {         
      best = current  
      if (best.score == 0) {  return  }  
    } 
  }
}

val temperatures = sequence { 
  var t = 0.7        // initial temperature
  while (t > 0.02) { // final temperature 
    repeat(400) {    // steps per change
      yield(t)       // send t to sequence
    }  
    t *= 0.99        // decreasing coefficient
  }
}

val QueenBoard.score get() = this.threatingQueenCount


This solution achieves a runtime of approximately 180 ms for a 100×100 board on an Apple M1 chip.

Conclusion

Simulated annealing is a versatile and powerful algorithm for tackling optimization problems, from finding the shortest path to designing VLSI chips. It’s a testament to how theoretical concepts like physical annealing can be adapted to solve practical challenges in computing and beyond. I hope it inspires you to experiment with other problems and helps you find efficient solutions in your work!

You can find all the source code on GitHub: simulated annealing. For comparison, check out the C-based source code on GitHub: archive data.

Thanks for reading!

Data structure Algorithm Kotlin (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Floyd's Cycle Algorithm for Fraud Detection in Java Systems
  • Understanding HyperLogLog for Estimating Cardinality
  • Hybrid Search: A New Frontier in Enterprise Search
  • Optimizing the Traveling Salesman Problem: Integrating Graph Neural Networks With Branch and Bound Algorithms

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!