AI 资讯
Monotonic Stack: The Matrix of Array Problems
The Quest Begins (The "Why") I still remember the first time I faced the “Next Greater Element” interview question. The array looked innocent enough, but every brute‑force attempt felt like I was hammering a nail with a sponge— O(n²) time, nested loops, and a sinking feeling that I was missing something elegant. I spent an hour sketching out the problem on a whiteboard, muttering, “There has to be a way to look ahead without looking back every single time.” That frustration is a rite of passage for many developers. We’re taught to think in terms of scanning left‑to‑right, but some array puzzles scream for a different perspective: we need to remember what we’ve seen in a way that lets us answer questions about the future elements instantly. Enter the monotonic stack—a deceptively simple data structure that turns those scary “look‑ahead” problems into straight‑line walks. The Revelation (The Insight) So what’s the secret sauce? A monotonic stack is just a stack that maintains its elements in strictly increasing or strictly decreasing order. Why does that help? Consider the Next Greater Element problem: for each index i , we want the first element to its right that’s larger than arr[i] . If we walk from left to right and keep a stack of indices whose next greater element we haven’t found yet, the stack will naturally be decreasing in value. Why decreasing? Imagine the stack holds indices [i₁, i₂, …, i_k] where arr[i₁] > arr[i₂] > … > arr[i_k] . When we encounter a new value arr[j] , any element on the stack that is smaller than arr[j] has just found its next greater element—namely arr[j] . We pop those indices, record the answer, and stop when we hit a value that’s not smaller (or the stack empties). Then we push j onto the stack. Because each index is pushed once and popped at most once , the total work is linear: O(n) . No nested loops, no repeated scans—just a single pass with a stack that does the heavy lifting. The same invariant works for other “first bigger/smal
AI 资讯
Budoucnost
AI jako partner, ne kalkulačka: člověk a AI při řešení Project Euler #185 srpna 2026 Co se stane, když člověk nepoužije umělou inteligenci pouze jako nástroj, který má dodat hotovou odpověď, ale jako partnera při řešení problému? Dnes jsme to vyzkoušeli na konkrétním problému z Project Euleru. Nechtěli jsme vytvořit nový algoritmus. Chtěli jsme zjistit, jak může vypadat skutečná spolupráce člověka a AI při hledání řešení. Experiment Vybrali jsme Project Euler #185 – Number Mind. Úloha obsahuje 22 šestnáctimístných sekvencí. U každé je uvedeno, kolik číslic je na správné pozici. Úkolem je najít unikátní šestnáctimístnou sekvenci, která splňuje všechna tato omezení. Na začátku jsme si stanovili jednoduché pravidlo: Nechceme pouze získat výsledek. Chceme společně hledat cestu k němu. První problém Naše první společná zkouška nedopadla podle očekávání. Ukázalo se, že jsme si pro experiment nezvolili ideální problém a postup. Místo toho, abychom se snažili chybu zakrýt, označili jsme první pokus jako neúspěšný a změnili postup. To se ukázalo jako důležitá součást experimentu. Chyba nebyla důvodem ukončit spolupráci. Byla informací pro další krok. Project Euler #185 U samotného problému jsme postupovali bez předem připraveného algoritmu. AI začala pracovat s kandidáty a jednotlivými řádky. Člověk průběžně sledoval strukturu problému a hledal jiný pohled. V určitém okamžiku přišel klíčový návrh: «„Nehledejme jen to, co je správně. Hledejme miny – čísla, která se nám nehodí.“» Tím se změnila orientace řešení. Místo hledání správných možností jsme začali systematicky vyřazovat možnosti, které nemohou být správné. Co přinesl člověk a co AI? Martin přinesl především: intuitivní pozorování, změnu perspektivy, rozhodování o směru dalšího řešení, pochybnosti a kontrolu jednotlivých kroků, myšlenku „min“. AI přinesla: rychlé zpracování velkého množství kombinací, strukturování hypotéz, systematické porovnávání, práci s omezeními, závěrečné ověření. Role se přitom během řešení nemě
AI 资讯
Union-Find: The Fellowship of the Sets
The Quest Begins (The "Why") I still remember the first time I saw LeetCode 323 “Number of Connected Components in an Undirected Graph”. I stared at the adjacency list, thought “I’ll just run a DFS from every node”, and coded it up in ten minutes. The solution passed the easy tests, but when the hidden test cases hit a graph with 10⁵ nodes and 10⁵ edges, my DFS started to choke—stack overflows, repeated visits, and a sinking feeling that I was brute‑forcing a problem that deserved a smarter tool. That night, after a few too many coffees, I stumbled upon a tiny comment in a discussion thread: “Union‑Find can do this in almost O(1) per operation”. My curiosity sparked like a power‑up in a retro arcade game. I had to know why this seemingly simple data structure could turn a nightmare into a breeze. The Revelation (The Insight) At its heart, Union‑Find (aka Disjoint Set Union, DSU) maintains a collection of elements partitioned into disjoint subsets. It supports two operations: Find(x) – returns the representative (root) of the set containing x . Union(x, y) – merges the sets containing x and y . The magic lies in two simple heuristics: Path Compression – when we walk up the tree to find a root, we make every node on that path point directly to the root. Future finds become flat, almost constant‑time. Union by Rank/Size – we always attach the smaller tree under the root of the larger one, keeping the overall tree shallow. Why does this give us near‑O(1) amortized time? Think of each Find as paying a small “tax” to flatten the path. The tax is paid only a few times per node before it becomes a direct child of the root. Over a sequence of m operations, the total work is bounded by O(m α(n)) , where α is the inverse Ackermann function—so slow‑growing it’s practically a constant for any realistic n . In plain English: every time we climb up, we leave a shortcut behind. The next climber benefits from that shortcut, and the structure keeps getting better. It’s like building
开发者
How Many Introductions Away Are You From Pedro Pascal? A Practical Introduction to Graph Search
I was watching The Mandalorian the other day when it struck me that I don't know Pedro Pascal, which...
AI 资讯
The Matrix: Why Merge Sort Beats the Brute Force
The Quest Begins (The "Why") I still remember the first time I got hit with a sorting question in an interview. The interviewer slid a whiteboard marker across the table and said, “Sort this array of a million integers – and tell me why you chose your method.” My brain went straight to the trusty old bubble sort I’d learned in CS101. I started writing nested loops, feeling like Neo dodging bullets in slow motion, only to realize the runtime was creeping toward O(n²). After a few painful minutes, I could see the interviewer’s eyes glaze over – not because I was wrong, but because I was using a sledgehammer to crack a nut. That moment sparked a quest: What makes a sorting algorithm truly efficient, and how do I know when to reach for it? I dove into textbooks, blog posts, and late‑night YouTube deep dives. The answer kept pointing back to one algorithm that felt like discovering a hidden cheat code: Merge Sort . The Revelation (The Insight) So why does Merge Sort work so well? It’s not just about splitting and merging; it’s about guaranteeing that each level of recursion does a linear amount of work, no matter how the input is arranged. Think of an unsorted array as a messy pile of LEGO bricks. Merge Sort first divides the pile into two halves, then halves again, until each sub‑pile contains a single brick – which is, by definition, sorted. The magic happens in the merge step: we take two already‑sorted sub‑arrays and walk through them with two pointers, always picking the smaller front element and appending it to the result. Because each sub‑array is sorted, we never need to look back; we simply advance one pointer at a time. That walk is O(n) for the merge: each element is examined exactly once as it gets placed into the output array. Since we split the array log₂ n times (each level halves the size), we perform an O(n) merge at each of those log₂ n levels. Multiply them together and you get O(n log n) worst‑case time, with O(n) extra space for the temporary buffer
AI 资讯
How We Evolved a Cultural Recommendation Feed From a Weighted SQL Ranker to a Narrative Affinity Model
Building a personalization engine for a multi-format content feed, without machine learning, and the testing process that forced us to rebuild it. TL;DR We run a collaborative cultural curation platform (think: user-submitted recommendations for movies, books, games, music, and long-form posts, all mixed into one feed) on a fairly ordinary PHP + MySQL stack. Over about a year we went through two full generations of the feed ranking algorithm. The first version solved the obvious problem (stop being purely chronological) but quietly failed at real personalization. The second version fixed that by rethinking what "user taste" even means, moving scoring out of SQL and into application code, and adding a layer of post-ranking business rules. This post walks through both generations, why the second one had to happen, and how we actually tested and calibrated a feed ranking system without a data science team or an ML pipeline. No exact weights, table names, or formulas below — just the engineering story. The starting problem: one feed, five content shapes Before personalization is even on the table, a multi-format feed has a normalization problem. Movies, books, games, music, and editorial posts live in different tables, with different columns, different publishing cadences, and engagement numbers on completely different scales. "1,000 likes" on a music post and "1,000 likes" on a book review are not the same signal. So the very first architectural decision — before any ranking logic existed — was building a unification layer that maps every content type into a shared shape (type, author, title, cover, category, engagement counters, timestamp) before any scoring happens. Everything downstream depends on that layer being consistent. Generation 1: a weighted ranker living inside a single SQL query The first real version of the algorithm — internally we called it the hybrid model — had a modest goal: get away from a purely chronological feed without building anything resembl
AI 资讯
Dos formas en que un backtest te miente (y cómo evitarlas)
Pruebas una estrategia, o un modelo, sobre datos históricos. El backtest da un número bonito. Y luego, en real, no aparece. Casi siempre es una de estas dos ilusiones — y las dos se descartan con muy poco código. Empaqueté las dos correcciones como librería: honest-eval , Python puro, sin dependencias. Salieron de un bot de trading, pero el rigor no tiene nada de específico al trading. Ilusión 1: el modelo vio el futuro Partir los datos con el clásico train_test_split aleatorio es correcto para datos independientes. En una serie temporal es un desastre silencioso: mete muestras de mañana en el conjunto de entrenamiento, y el modelo "predice" en el test cosas que en producción todavía no habrían pasado. La métrica sale inflada, y confías en un edge que no existe. El test honesto es siempre el futuro : el tramo más reciente en el tiempo. from honest_eval import temporal_split train_idx , test_idx = temporal_split ( timestamps , test_frac = 0.20 , embargo = 24 ) X_tr , X_te = X [ train_idx ], X [ test_idx ] Devuelve índices, así lo aplicas a numpy, pandas o listas por igual. El embargo cierra una fuga más sutil: si tu etiqueta mira h pasos adelante, una muestra de entrenamiento a menos de h del corte ya conoce parte del resultado del test. embargo=h descarta ese borde. La métrica baja — pero por fin es la real out-of-sample . Ilusión 2: la variante ganó por suerte Tienes varias variantes y quieres la mejor. Eliges la de mayor media. Error: con pocas muestras, eso premia la varianza, no la ventaja . La variante más ruidosa suele quedar arriba por azar. Dos correcciones, ambas dentro de select_best_variant : Aparear. Mide variante y baseline sobre el mismo ensayo y trabaja con δ = variante − baseline . La varianza común del ensayo se cancela en la resta, y te quedas con la señal. Exigir cota inferior de confianza > 0. Gradúa una variante solo si media − z·SE > 0 : "incluso siendo pesimista dentro del margen de confianza, sigue por encima del baseline". from honest_eval i
AI 资讯
Building Autocomplete Like a Jedi: Mastering the Trie
The Quest Begins (The "Why") Honestly, I still remember the first time I tried to build an autocomplete widget for a side‑project. I had a list of 200 k product names, a simple filter that ran on every keystroke, and the UI felt like wading through molasses. Each keypress triggered a full scan of the list, and with a few users typing at once the browser would start to lag. I was stuck in a loop that felt like the infamous “boss fight” where you keep hitting the same pattern over and over, hoping for a different outcome. I kept asking myself: There has to be a smarter way. Why am I re‑checking the same prefixes again and again? If ten users type “tea”, why do I walk through the whole dictionary ten separate times? That question turned into a mini‑quest, and the treasure at the end was the trie data structure. The Revelation (The Insight) Look, the magic of a trie isn’t that it’s some exotic tree; it’s that it stores words by their shared prefixes . Imagine you have the words “cat”, “car”, “cart”, and “dog”. In a trie you’d have a root node, then a c branch that splits into a → t (for “cat”) and a → r → t (for “cart”), while “dog” lives on its own d → o → g path. Every common prefix is stored once , and you can walk down the tree following the characters of a query to land exactly at the node that represents all words with that prefix. Why does this give us O(L + K) time for autocomplete, where L is the length of the prefix and K is the number of results? Walking the trie follows the prefix character‑by‑character → O(L). From that node we just need to collect all words in its subtree. If we keep a list of words at each node (or run a DFS), we touch each result once → O(K). No extra work for words that don’t share the prefix. Contrast that with the naive filter approach: O(N × L) where N is the total dictionary size. For a large N, the trie is a game‑changer—it’s like switching from swinging a blunt sword to wielding a lightsaber that cuts through the prefix forest in
产品设计
How Pokemon IVs Are Calculated Under the Hood — A Reverse Engineering Guide
If you've ever wondered whether that wild Pokemon you just caught has competitive potential, you've probably heard the term IVs (Individual Values) thrown around. IVs are the hidden genetics of every Pokemon — the 0–31 numbers baked into your Pokemon at birth that determine how strong it can ultimately become. But here's the thing: the game never tells you what your IVs are. You have to reverse-engineer them. In this post, I'll walk you through exactly how IV calculators work under the hood — from the official stat formula, to the nature modifier trick, to why you often get a range instead of a single number. Live Tool: Try the calculator at randompokemongenerator.me/iv-calculator — free, no sign-up required, supports Gen III through Gen IX. What Are IVs, Exactly? Individual Values are six hidden integers between 0 and 31 , one for each stat (HP, Attack, Defense, Sp. Atk, Sp. Def, Speed). They represent the genetic potential of a Pokemon and are permanently set when the Pokemon is encountered or hatched — they can never be changed by leveling up or any in-game action. A stat with 31 IVs reaches its maximum possible value at level 100. A stat with 0 IVs starts at its theoretical minimum. In competitive play, players typically hunt for Pokemon with at least 3–4 perfect (31) IVs , with some strategies deliberately using 0 IVs in Defense or Speed for tactical advantages. The IV system as we know it today started in Generation III (Ruby/Sapphire/Emerald). Gen I–II used a predecessor called DVs (Determinant Values) , which only covered four stats and worked differently — so if you're playing on Virtual Console or Gen I/II, this calculator won't apply. The Stat Formula (Gen III+) The foundation of everything is the official stat calculation formula introduced in Generation III and still used today: For HP: HP = floor(((2 × BaseStat + IV + floor(EV / 4)) × Level) / 100) + Level + 10 For all other stats: Stat = floor((floor(((2 × BaseStat + IV + floor(EV / 4)) × Level) / 100
开发者
Por qué tu bot recibe 403 de Cloudflare (y cómo endurecer un cliente ccxt)
Si automatizas un exchange con ccxt , tarde o temprano lo verás en los logs: rachas cortas de 403 Forbidden que pegan a fetch_balance , a los OHLCV o al saldo de earn, y que desaparecen solas a los pocos minutos. No es que tu API key esté mal. Es el WAF (Cloudflare) que muchos exchanges ponen delante de su REST, challengueando a algo que "parece un bot". Y tu bot es un bot — pero uno legítimo , operando tu propia cuenta contra la API oficial. El problema no es de permisos, es de reputación de cliente HTTP. Esto va de reducir los falsos positivos del WAF, no de evadir ningún control de acceso. Dos capas que lo mitigan Saqué este patrón de un bot propio sobre OKX, tras varias rachas de 403, y lo publiqué como librería: ccxt-resilience (Apache-2.0). 1. Que el WAF challengue menos: harden Un cliente ccxt por defecto se anuncia como lo que es. Ajustar un User-Agent de navegador, la cabecera Accept-Language y un timeout holgado hace que Cloudflare lo desafíe con menos frecuencia: import ccxt from ccxt_resilience import harden exchange = harden ( ccxt . okx ({ " apiKey " : ..., " secret " : ..., " password " : ..., })) harden toca un cliente ya construido , devuelve el mismo objeto (encadenable) y nunca rompe su construcción: si algo falla al fijar los atributos, los deja como estaban. 2. Reintentar solo lo que se debe: with_retry La tentación es envolver todo en un try/except que reintente. Es una trampa: reintentar un error de credenciales o de fondos solo gasta tiempo, termina igual de mal, y esconde bugs de lógica detrás de esperas. La clave es reintentar únicamente lo transitorio —403/Cloudflare, 429, timeouts— con backoff exponencial y jitter, y re-lanzar los errores reales en el acto: from ccxt_resilience import with_retry balance = with_retry ( exchange . fetch_balance ) ohlcv = with_retry ( exchange . fetch_ohlcv , " BTC/USDT " , timeframe = " 1m " , attempts = 4 , base = 1.0 , max_s = 8.0 ) Un error de autenticación se re-lanza inmediatamente, sin reintentar. Y s
开发者
El redondeo que hace que tu bot arriesgue 10 veces lo que crees
Casi todo bot de trading tiene una línea que decide cuánto comprar . Suele parecer trivial: si arriesgo el 1% de mi saldo y mi stop está a 1000 dólares de distancia, la cantidad sale de una división. El cálculo es de primaria. Lo que no es de primaria es hacer que ese número quepa en las restricciones del exchange . Ahí es donde se pierde dinero, y de formas que no aparecen en los logs. El patrón que multiplica tu riesgo Esto está en incontables bots, y estuvo en uno mío: cantidad = max ( 1 , int ( cantidad_teorica / contract_size )) La intención es defensiva: "que nunca salga cero". El efecto es el contrario. Si la cantidad teórica sale 0.1 contratos, int() la trunca a 0 , y entonces max(1, ...) la fuerza a uno . Acabas de abrir una posición diez veces más grande que la que autorizaste. Con números concretos: saldo de 500 USD, riesgo del 1% (5 USD), entrada en 50 000, stop en 45 000, contratos de 0.01. El riesgo real de ese contrato único es de 50 USD — diez veces el presupuesto. Y ocurre en silencio: la orden se acepta, el bot sigue, no hay excepción que capturar. Lo peor es que no es un caso raro. Pasa siempre que el saldo es pequeño o el stop es ancho, es decir, exactamente cuando menos margen tienes para equivocarte. Los otros dos que cuestan dinero Ignorar el nocional mínimo. El exchange rechaza la orden por valor mínimo, el bot lo registra como error de red, y nadie se entera de que esa señal nunca se operó. El backtest la contó; la cuenta no. No reservar para comisiones. Con un stop ajustado, las comisiones de ida y vuelta pueden ser la mitad del riesgo real . Si dimensionas contra la distancia al stop y nada más, arriesgas sistemáticamente más de lo que crees. Cómo lo resolví Saqué el cálculo del bot y lo publiqué como librería: position-sizing (Apache-2.0, sin dependencias). from decimal import Decimal from position_sizing import MarketSpec , size_for_risk spec = MarketSpec ( amount_step = Decimal ( " 0.001 " ), min_amount = Decimal ( " 0.001 " ), min_noti
AI 资讯
AI Influencers Are Heading Into Uncharted Territory
Some creators fear the EU AI Act’s regulatory chaos will upend their lucrative businesses. Others are owning it by incorporating AI transparency into their creative process.
开发者
How Market Sessions Influence an Algorithmic Trading Platform
An algorithmic trading platform doesn't operate in isolation it responds to the changing conditions of the financial markets. One of the biggest factors affecting automated trading performance is the market session. Liquidity, volatility, trading volume, and price movements can vary significantly throughout the trading day, influencing how an algorithmic trading platform executes trades. Understanding how different market sessions impact automated trading can help traders choose the right strategies, manage risk more effectively, and improve overall trading performance. What Are Market Sessions? A market session refers to a specific period during which a stock exchange is open for trading. In India, the National Stock Exchange (NSE) and Bombay Stock Exchange (BSE) follow a structured trading schedule that includes the pre-open session, regular trading hours, and post-closing session. Each session has unique market characteristics, making it important for traders to understand how their automated strategies may behave during these periods. Why Market Sessions Matter in Algorithmic Trading An algorithmic trading platform follows predefined rules, but the market environment changes throughout the day. A strategy that performs well during high-volume periods may struggle when trading activity is low. Market sessions influence several key factors, including: Trading volume Market liquidity Price volatility Bid-ask spreads Order execution quality Recognizing these differences allows traders to build strategies that are better suited to specific market conditions. Pre-Open Session The pre-open session is used to determine the opening price of securities before regular trading begins. During this period: Orders are collected but not executed immediately. Prices may fluctuate as the market discovers the opening level. Liquidity can be limited. Large overnight news events may influence price movements. Most intraday automated strategies are designed to become active only afte
AI 资讯
Trump’s AI protectionism has come for robotics
This story originally appeared in The Algorithm, our weekly newsletter on AI. To get stories like this in your inbox first, sign up here. Humanoid robots usually elicit more cringe than awe: They stumble, kick children, and despite advances are still worse at using their hands than my toddler. It’s a nascent industry, and such robots…
AI 资讯
Building an AI lineup optimizer for a Discord esports bot (the algorithm, not the hype)
Every esports team captain has done this by hand at least once: open Discord, scroll through a dozen "I can play Thursday after 8" messages, cross-reference them against who plays Tank versus DPS, remember that one of your DPS is actually a sub, and try to assemble a starting five that can actually scrim tonight. It takes fifteen minutes, you get it slightly wrong, and you do it again the next day. I build Supatimer , a free Discord bot for competitive gaming teams, and "generate the lineup for me" was the single most requested feature. This post is about how the lineup optimizer actually works, why it is genuinely AI (and not in the marketing sense), and where a large language model fits in versus where it absolutely does not. "AI" is doing a lot of work in this industry Half the Discord bots on the market slapped "AI" on their landing page the week ChatGPT launched. Usually it means there is a chatbot command somewhere that proxies to an LLM. That is fine, but it is not what your team needs when it is 7:45pm and you have a scrim at 8. There are two honest definitions of AI worth separating: Search and optimization - the classical branch. Constraint satisfaction, combinatorial optimization, planning. This is the part of AI that solves "given these rules and these resources, find the best valid arrangement." Machine learning / LLMs - the statistical branch. Pattern recognition, generation, extraction from unstructured text. The lineup problem is squarely a problem for the first kind. So that is what I built first. The lineup problem, stated precisely Strip away the gaming context and a lineup is a constrained assignment problem: You have N players , each with a set of roles they can fill (Tank, DPS, Support, IGL, and so on). Each player has an availability signal for a given time block (available, maybe, unavailable). Each player has a roster status (starter, substitute, trial). The game defines a required composition : Overwatch 2 wants 1 Tank, 2 DPS, 2 Support. Va
AI 资讯
AI Slop Melodramas Are Taking Over X—and Their Creators Are Cashing In
Viral tales of good triumphing over evil are racking up millions of views. They’re almost entirely AI-generated clickbait.
开发者
Quantum computers outperform classical ones, with results you can trust
Three approaches to the issue of quantum results that can't be verified classically.
AI 资讯
OpenAI called the Hugging Face attack unprecedented. But we’ve been here before.
This story originally appeared in The Algorithm, our weekly newsletter on AI. To get stories like this in your inbox first, sign up here. Reading OpenAI’s account last week of how some of its models broke their containment and hacked into the computer systems of Hugging Face, another AI company, was the first time I got…
AI 资讯
Microsoft pressures LG into killing unwanted McAfee ads
Microsoft has intervened to stop Windows 11 users with LG monitors from being bombarded with annoying McAfee trial pop-ups. In response to complaints about the LG bloatware, Microsoft's Windows chief, Pavan Davuluri, said that LG has agreed to immediately disable the McAfee pop-up from its LG Monitor App Installer, and pledged that Microsoft will "keep […]
AI 资讯
Microsoft responds to LG monitors installing McAfee ads on Windows
App is installed through Windows Update when certain LG monitors connect to a PC.