<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by CG_Musta on Medium]]></title>
        <description><![CDATA[Stories by CG_Musta on Medium]]></description>
        <link>https://medium.com/@mmcryptogem?source=rss-d2ca05e21155------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yIwMJ_XUVhLJ3ce3PIoiXQ.png</url>
            <title>Stories by CG_Musta on Medium</title>
            <link>https://medium.com/@mmcryptogem?source=rss-d2ca05e21155------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:27:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mmcryptogem/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I Backtested Dozens of Nasdaq Swing Trading Strategies.]]></title>
            <link>https://mmcryptogem.medium.com/i-backtested-dozens-of-nasdaq-swing-trading-strategies-26afcdd2f759?source=rss-d2ca05e21155------2</link>
            <guid isPermaLink="false">https://medium.com/p/26afcdd2f759</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[financial-planning]]></category>
            <category><![CDATA[investment]]></category>
            <category><![CDATA[nasdaq]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <dc:creator><![CDATA[CG_Musta]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 15:29:30 GMT</pubDate>
            <atom:updated>2026-11-19T15:29:30.363Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Backtested Dozens of Nasdaq Swing Trading Strategies. Almost All of Them Were Misleading. (English Version)</h3><p><em>Including one system that showed a Profit Factor of 1.94 across two independent markets. The actual figure was 0.79.</em></p><p>Anyone who has ever backtested a trading strategy knows the feeling. The numbers look great, the equity curve rises smoothly, and the Profit Factor is above 2. Then you move to live trading, and nothing works quite the same way.</p><p>For a long time, I thought the problem was discipline, psychology, or simply bad luck.</p><p>It wasn’t.</p><p>The gap between simulation and reality has specific, repeatable technical causes. And almost every time, those errors push the results in the same direction: upward.</p><p>This article documents a research project built around a different objective. Rather than trying to find a strategy that works, I wanted to disprove every strategy that appeared to work and see what was left standing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xeRxOOnneKGDrMp9L6-Mzg.png" /></figure><h3>Before We Begin</h3><p>Before getting into the research, I think it’s important to clarify something.</p><p>I wasn’t starting from scratch, and I wasn’t looking for a strategy to begin trading with.</p><p>I’ve been investing and trading financial markets for over 15 years. During that time, I’ve developed my own trading methodology, which I still use today. It’s primarily a swing trading approach based on spot positions and daily-chart analysis, applied across different markets and refined through years of experience, observation, and adaptation to changing market conditions.</p><p>This research came from a different need.</p><p>I wanted to understand whether it was possible to identify a long-term structural edge, particularly in the Nasdaq, that was robust enough to be turned into a systematic strategy and potentially automated in the future.</p><p>And that’s where things become much more difficult.</p><p>Having a discretionary trading method that works because it incorporates experience, context, and market interpretation is one thing.</p><p>Turning that same advantage into precise, measurable, repeatable rules that a machine could execute without human intervention — or that a complete beginner could follow — is something else entirely.</p><p><strong>Automation isn’t the starting point. It’s the final test.</strong></p><p>If an idea cannot survive realistic costs, execution delays, changing market regimes, out-of-sample testing, and different market years, it isn’t robust enough to automate.</p><p>So this research wasn’t about finding just any strategy. It was about finding something that could demonstrate an edge even after removing as much discretionary judgment as possible.</p><p>The results should be viewed from that perspective: not as a search for the perfect strategy, but as an attempt to understand how much of a trading edge can actually be measured, isolated, and eventually automated.</p><h3>The Research Protocol</h3><h3>Five criteria, all at the same time</h3><p>Every hypothesis had to pass five checks simultaneously.</p><p>Passing four out of five meant rejection. No exceptions, and no adjusting parameters afterward to rescue the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ljtPOXXPJdBV_JOdpwmTXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_twWyc9UhTVep9KODSj7mA.png" /><figcaption><strong>Figure 1 — The funnel.</strong> Percentage of hypotheses surviving each validation stage. The sharpest drop occurs when realistic trading costs are introduced. Many ideas work in theory but fail once spreads are included.</figcaption></figure><h3>Four Silent Ways a Backtest Can Be Inflated</h3><h3>The most useful part of the entire research</h3><p>Each of the following errors can be invisible in the final results.</p><p>They produce numbers that look credible, and they consistently make performance appear better than it really is.</p><h3>1. Indicator Offset Bias</h3><p>Some indicators plot their signals one bar backward for purely visual reasons.</p><p>When data is exported, that offset can carry over. A value that only becomes known at bar T+1 appears at bar T.</p><p>Anyone building a backtest using that data is unknowingly using information from the future.</p><p>This is a form of look-ahead bias, and it can make an otherwise unprofitable strategy appear highly effective.</p><h3>2. Missing or Underestimated Trading Costs</h3><p>With tight stop-loss levels, transaction costs can represent a substantial portion of the total risk.</p><p>I measured configurations where a two-point spread accounted for more than 50% of the stop-loss distance.</p><p>None of those strategies could realistically work, regardless of how good their entry signals appeared.</p><h3>3. Exit Execution Semantics</h3><p>Many backtesting engines allow stop-loss and take-profit orders to trigger on the entry bar itself.</p><p>In the live execution model I was comparing against, those orders only became active on the following bar.</p><p>That difference may seem insignificant.</p><p>But in one configuration I tested, correcting it reduced the Profit Factor from <strong>1.64 to 1.06</strong>.</p><h3>4. Multi-Timeframe Data Alignment</h3><p>In exported market data, a candle’s timestamp usually represents its opening time.</p><p>If you align a higher timeframe with a lower timeframe using that timestamp incorrectly, you may assign information from a higher-timeframe candle that is still forming.</p><p>In other words, your strategy is using information that wasn’t available at the time.</p><p><strong><em>One of my hypotheses initially showed a Profit Factor of 1.94. After correcting the alignment, the actual Profit Factor was 0.79. The strategy looked excellent. In reality, it was losing money.</em></strong></p><p>What makes this particularly important is that the hypothesis had passed every other validation check: a large sample, two independent markets, and an orderly parameter gradient.</p><p>Anyone who failed to verify that single detail could easily have published it as a successful strategy.</p><h3>The Graveyard</h3><h3>What didn’t work — and there was plenty</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M2AHb249OYJYwUHOCvlMmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I4eQ3z-dLpFYtISxKV0TGA.png" /></figure><h3>What Survived</h3><h3>Three trading logics, two time horizons, sixteen years</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mwlr7t9sftgbKXC7blePFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zG19vALKVGeoSbRZFMeiPw.png" /><figcaption><strong>Figure 2 — Equity curve.</strong> Displayed on a logarithmic scale, where equal slopes represent equal percentage returns. The progression is relatively consistent across sixteen years, without obvious discontinuities attributable to a handful of lucky events.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*1OzJWoIvGI-VWyrO.png" /><figcaption><strong>Figure 3 — Drawdown.</strong> Maximum drawdown: <strong>21.5%</strong>. Recovery periods remained relatively contained, without prolonged drawdowns beyond the operational tolerance threshold used in the research.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*aa3zObcC5-mknkl0.png" /><figcaption><strong>Figure 4 — Annual stability.</strong> Two years fell below the profitability threshold out of seventeen: 2011 and 2016. No single year dominates the overall result, an important check when trying to distinguish a repeatable structure from coincidence.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*9bSCtC5_kBAy9R1q.png" /><figcaption><strong>Figure 5 — Monthly performance heatmap.</strong> Green represents positive months, red represents negative months, with intensity proportional to the size of the result. Profits are distributed across the sample rather than concentrated in a few isolated periods.</figcaption></figure><h3>The Three Components</h3><p>The exact entry and exit rules remain proprietary.</p><p>What I can document is the statistical behavior of each component and, more importantly, how they interact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LIARb3vKWTyvd5JbyuTPWQ.png" /></figure><p>The components were deliberately designed with different profiles.</p><p>Component A wins frequently but generates relatively small gains.</p><p>Component B wins less than half the time but has a much higher average profit-to-loss ratio.</p><p>This asymmetry isn’t an unintended side effect. It’s the mechanism that makes the combined system stronger than its individual parts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*51wafM4E-TpSfNIiGhsAtA.png" /><figcaption><strong>Figure 6 — Correlation.</strong> Component A is largely independent of the other two. When one component experiences an unfavorable period, the others tend to offset some of the weakness. This helps explain why the combined system’s drawdown is lower than that of each component individually.</figcaption></figure><h3>The Constraint That Became an Advantage</h3><h3>When practicality and statistics point in the same direction</h3><p>Part of this research began with a very simple problem.</p><p>A trading system that generates signals in the middle of the night isn’t particularly practical for someone living in Europe who needs to sleep.</p><p>I decided to measure performance by time of day.</p><p>Initially, I expected a trade-off: lower returns in exchange for a strategy that was easier to execute.</p><p>The opposite happened.</p><p>The trading hours corresponding to nighttime in Europe were actually the worst-performing periods, falling below the profitability threshold.</p><p>Removing them improved the system across every major metric.</p><p>The Profit Factor increased, the drawdown was nearly cut in half, and the share of total profit coming from a small number of exceptional trades fell from more than 40% to less than 20%.</p><p><strong><em>I hadn’t sacrificed anything. I had simply removed the hours that were destroying value.</em></strong></p><h3>Stated Limitations</h3><h3>Research that doesn’t acknowledge its limitations isn’t research</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e6FRMnfcVx_CyDR7h7l3lg.png" /></figure><h3>Conclusion</h3><p>The final numerical result is a system with a <strong>Profit Factor of 1.488 across 1,024 trades</strong>.</p><p>It’s not a spectacular number, and that’s intentional.</p><p>Throughout this research, several configurations produced extraordinary results.</p><p>Some showed Profit Factors above 2. Others above 3. One even exceeded 10.</p><p>Every single one of those spectacular results turned out to be an artifact when examined properly.</p><p>A data alignment bias. An unaccounted trading cost. A sample that was too small. A metric that was technically correct but misleading.</p><p>What remains after removing those artifacts is much more modest.</p><p>But it has been measured, it is reproducible under the tested conditions, and it is the result of my own research.</p><p>The value of this work isn’t really what I found.</p><p><strong>It’s what I was able to eliminate.</strong></p><h3>What’s Next?</h3><p>The research is ongoing.</p><p>The next steps include validation on a second equity index, forward testing using live market data, and further refinement of components with only a marginal contribution to overall performance.</p><p>I’ll publish updates as the results become available, whether they’re positive or negative.</p><p>Anyone interested in following the beta-testing process can find more information on the CG Investment website or within the community.</p><p>The beta is intended for people who want to observe the validation process from the inside: signals, results, updates, and, most importantly, what happens when a system moves from research into real-world conditions.</p><p>There is no promise that it will work.</p><p>That’s precisely why we’re testing it.</p><p><strong>Official website:</strong> <a href="https://cginvestment.it/">https://cginvestment.it/</a></p><p><strong>CG INVESTMENT · QUANTITATIVE RESEARCH</strong></p><p>FX:NAS100 · 4H + Daily · January 2010 — August 2026 · 1,024 verified backtest trades</p><p><em>For informational and educational purposes only. This content does not constitute financial advice or an investment solicitation. Historical and simulated results are not indicative of future performance. All trading involves the risk of capital loss.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26afcdd2f759" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ho testato decine di strategie swing sul Nasdaq. Quasi tutte erano false.]]></title>
            <link>https://mmcryptogem.medium.com/ho-testato-decine-di-strategie-swing-sul-nasdaq-quasi-tutte-erano-false-15c59fe7a003?source=rss-d2ca05e21155------2</link>
            <guid isPermaLink="false">https://medium.com/p/15c59fe7a003</guid>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[trading]]></category>
            <dc:creator><![CDATA[CG_Musta]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 17:13:26 GMT</pubDate>
            <atom:updated>2026-08-25T17:24:36.562Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Compreso un sistema che mostrava Profit Factor 1,94 su due mercati indipendenti. Il valore reale era 0,79.</em></p><p>Chiunque abbia backtestato una strategia conosce quella sensazione. I numeri sono ottimi, la curva sale pulita, il Profit Factor supera 2. Poi si passa all’operativita’ reale e non succede niente di simile.</p><p>Per molto tempo ho pensato che fosse una questione di disciplina, o di psicologia, o di sfortuna. Non lo e’. La distanza tra simulazione e realta’ ha cause tecniche precise, ripetibili, e quasi sempre spinge i risultati nella stessa direzione: verso l’alto.</p><p>Questo e’ il resoconto di un programma di ricerca costruito con un obiettivo diverso dal solito. Non trovare una strategia che funziona — <em>falsificare</em> tutte quelle che sembrano funzionare, e vedere cosa resta in piedi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ic1bmeT3JV6YMRIs9yW5wQ.png" /></figure><h3>Prima di iniziare</h3><p>Prima di entrare nel merito della ricerca, credo sia importante chiarire una cosa.</p><p>Non sono partito da zero e non stavo cercando una strategia con cui iniziare a fare trading.</p><p>Investo e opero sui mercati da oltre 15 anni e, nel tempo, ho costruito un mio metodo operativo che utilizzo tuttora. È un approccio principalmente swing, basato sullo spot e sull’analisi del Daily, applicato a diversi mercati e costruito attraverso anni di esperienza, osservazione e adattamento alle diverse condizioni di mercato.</p><p>Questa ricerca nasce quindi da un’esigenza diversa.</p><p>Il mio obiettivo era capire se fosse possibile individuare, in particolare sul Nasdaq, un <strong>edge strutturale di lungo periodo</strong> sufficientemente robusto da poter essere trasformato in qualcosa di sistematico e, in prospettiva, automatizzato.</p><p>Ed è proprio qui che la difficoltà aumenta.</p><p>Una cosa è avere un metodo discrezionale che funziona perché incorpora esperienza, contesto e capacità di interpretare il mercato. Un’altra è riuscire a trasformare quel tipo di vantaggio in regole precise, misurabili e ripetibili, che possano essere eseguite da una macchina senza l’intervento umano, oppure da un novellino che non sa nulla di mercati.</p><p><strong><em>L’automazione non è il punto di partenza. È il test finale.</em></strong></p><p>Se un’idea non riesce a sopravvivere a costi reali, ritardi di esecuzione, cambiamenti di regime, out-of-sample e anni diversi di mercato, non è abbastanza robusta per essere automatizzata.</p><p>Per questo questa ricerca non nasce dalla necessità di trovare <em>una strategia qualsiasi</em>. Nasce dalla volontà di trovare qualcosa che possa dimostrare di avere un edge anche quando eliminiamo, il più possibile, la componente discrezionale.</p><p>Il risultato che segue va letto in quest’ottica: non come la ricerca della strategia perfetta, ma come il tentativo di capire <strong>quanto dell’edge possa essere realmente misurato, isolato e, un giorno, automatizzato.</strong></p><h3>Il protocollo</h3><p><em>Cinque criteri, tutti simultanei</em></p><p>Ogni ipotesi ha dovuto superare cinque controlli contemporaneamente. Superarne quattro su cinque significa respinta, senza appello e senza ritocchi ai parametri.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOIvQHi-ToggJXZPU6EePA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A5RMiBQDP8fByq80Qlm-Qw.png" /><figcaption>Fig. 1 — L’imbuto. Percentuale di ipotesi che supera ciascun livello di controllo. Il salto piu’ brusco avviene sul criterio dei costi reali: molte idee funzionano in teoria e muoiono sullo spread.</figcaption></figure><h3>Quattro modi silenziosi di gonfiare un backtest</h3><p><em>La parte piu’ utile di tutto il lavoro</em></p><p>Ognuno di questi errori e’ invisibile nei risultati. Produce numeri credibili. E li produce sempre verso l’alto.</p><h3>1 · Bias di offset negli indicatori</h3><p>Alcuni indicatori disegnano i marcatori spostati indietro di una barra per ragioni puramente grafiche. I dati esportati ereditano quello spostamento: alla barra T compare un valore che sara’ noto solo alla barra T+1. Chi costruisce un backtest su quei dati usa informazione futura senza saperlo.</p><h3>2 · Costi assenti o sottostimati</h3><p>Su stop stretti il costo di transazione puo’ rappresentare una frazione dominante del rischio. Ho misurato configurazioni in cui 2 punti di spread valevano oltre il 50% della distanza dello stop. Nessuna di quelle strategie poteva funzionare, indipendentemente dalla qualita’ del segnale.</p><h3>3 · Semantica di esecuzione delle uscite</h3><p>Molti simulatori attivano stop e target gia’ dalla barra di ingresso. Le piattaforme reali li attivano dalla successiva. La differenza sembra minima. Su una configurazione testata ha spostato il Profit Factor da 1,64 a 1,06.</p><h3>4 · Allineamento temporale multi-timeframe</h3><p>Nei dati esportati il timestamp di ogni barra e’ l’orario di <em>apertura</em>. Chi allinea un timeframe superiore a uno inferiore usando quel campo associa a ogni barra un valore che appartiene a una barra ancora in formazione — quindi non ancora nota.</p><p><strong><em>Su una mia ipotesi: Profit Factor apparente 1,94. Profit Factor reale 0,79. La strategia sembrava eccellente. Era perdente.</em></strong></p><p>Vale la pena sottolineare che quell’ipotesi aveva superato <em>tutti</em> gli altri controlli. Campione ampio, due mercati indipendenti, gradiente ordinato sui parametri. L’avrebbe pubblicata chiunque non avesse verificato quell’unico dettaglio.</p><h3>Il cimitero</h3><p><em>Cosa non ha funzionato, e non e’ poco</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*a66RzddciVX2U4xQKm7wtw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TESbXHvXrjEiWvWuo1MKjg.png" /></figure><h3>Cosa e’ sopravvissuto</h3><p><em>Tre logiche, due orizzonti, sedici anni</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*64wlNtfB3iLIAeJaeAmk6Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Q8lyLWNk3UdH5CnXjd9SA.png" /><figcaption><strong>Fig. 2 — Curva del capitale</strong>. Scala logaritmica: pendenze uguali significano rendimenti percentuali uguali. La progressione e’ regolare su sedici anni, senza discontinuita’ attribuibili a singoli eventi fortunati.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lw5anG3Xv7fQux_bbjCpsQ.png" /><figcaption><strong>Fig. 3 — Drawdown.</strong> Massimo 21,5%. I recuperi restano contenuti; nessun periodo di sofferenza prolungato oltre la soglia di sopportabilita’ operativa.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nWsfb6WYDhankjCVjs7tVA.png" /><figcaption><strong>Fig. 4 — Stabilita’ annuale</strong>. Due anni sotto la soglia di redditivita’ su diciassette (2011 e 2016). Nessun anno domina il risultato complessivo: e’ il controllo che separa una struttura da una coincidenza.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ex-8h5kEBpTvfp4hG4TEWw.png" /><figcaption><strong>Fig. 5 — Mappa mensile</strong>. Verde = mese positivo, rosso = negativo, intensita’ proporzionale all’ampiezza. La distribuzione e’ densa e diffusa: il profitto non si concentra in poche finestre temporali.</figcaption></figure><h3>Le tre componenti</h3><p>Le regole di ingresso e uscita restano proprietarie. Quello che posso documentare e’ il comportamento statistico di ciascuna e, soprattutto, il modo in cui interagiscono.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*usb2bwyqHQZk50m_R4Lm0A.png" /></figure><p>I profili sono deliberatamente diversi. La componente A vince spesso e poco, la B vince meno della meta’ delle volte ma con rapporto profitto/perdita elevato. Questa asimmetria non e’ un effetto collaterale: e’ il meccanismo che rende la combinazione superiore alle parti.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gxoxhrgr1MwAqqdjVRE5pw.png" /><figcaption><strong>Fig. 6 — Correlazione.</strong> La componente A e’ sostanzialmente indipendente dalle altre due. Quando una attraversa una fase sfavorevole, le altre tendono a compensare — ed e’ il motivo per cui il drawdown del sistema combinato risulta inferiore a quello di ciascuna componente presa singolarmente.</figcaption></figure><h3>Il vincolo che si e’ rivelato un vantaggio</h3><p><em>Quando la praticita’ coincide con la statistica</em></p><p>Una parte della ricerca e’ nata da un problema banale: un sistema che genera segnali nel cuore della notte non e’ eseguibile da chi vive in Europa e dorme.</p><p>Ho misurato la performance segmentata per fascia oraria aspettandomi di dover pagare un prezzo — meno rendimento in cambio di praticabilita’.</p><p>E’ successo l’opposto. Le fasce corrispondenti alla notte europea si sono rivelate le peggiori in assoluto, sotto la soglia di redditivita’. Escluderle ha migliorato il sistema su ogni metrica: Profit Factor in aumento, drawdown quasi dimezzato, e la quota di profitto concentrata in poche operazioni eccezionali scesa da oltre il 40% a meno del 20%.</p><p><strong><em>Non ho rinunciato a niente. Ho rimosso le ore che sottraevano valore.</em></strong></p><h3>Limiti dichiarati</h3><p><em>Una ricerca che non li elenca non e’ ricerca</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1C4I1qHcr9eKBjwXuguiPQ.png" /></figure><h3>Conclusione</h3><p>Il risultato numerico e’ un sistema con Profit Factor 1,488 su 1.024 operazioni. Non e’ un numero spettacolare, ed e’ deliberatamente cosi’.</p><p>Ogni configurazione che nel corso di questa ricerca ha prodotto risultati spettacolari — e ce ne sono state parecchie, con Profit Factor sopra 2, sopra 3, in un caso sopra 10 — si e’ rivelata alla verifica un artefatto. Un bias di allineamento, un costo non contabilizzato, un campione troppo piccolo, una metrica tecnicamente corretta ma fuorviante.</p><p>Quello che resta dopo aver rimosso tutti gli artefatti e’ modesto. Ma e’ misurato, e’ replicabile, ed e’ mio.</p><p><strong><em>Il valore di questo lavoro non sta in cio’ che ho trovato. Sta in cio’ che sono stato in grado di scartare.</em></strong></p><h3>E adesso?</h3><p>La ricerca prosegue: verifica su un secondo indice, forward test su dati reali, affinamento delle componenti a contributo marginale. Aggiornero’ con i risultati, positivi o negativi che siano.</p><p>Se vuoi partecipare al <strong>beta test</strong> e seguire il sistema mentre viene validato sul mercato, puoi trovare maggiori informazioni sul sito di CG Investment o all’interno della community.</p><p>L’accesso al beta è pensato proprio per chi vuole vedere il processo dall’interno: segnali, risultati, aggiornamenti e soprattutto cosa succede quando un sistema passa dalla ricerca alla realtà.</p><p><strong>Non promettiamo che funzionerà. È esattamente questo il motivo per cui lo stiamo testando.</strong></p><p>Sito ufficiale: <a href="https://cginvestment.it/">https://cginvestment.it/</a></p><p><em>CG INVESTMENT · RICERCA QUANTITATIVA<br>FX:NAS100 · 4H + Daily · gennaio 2010 — agosto 2026 · 1.024 operazioni verificate</em></p><p><em>Contenuto a scopo informativo ed educativo. Non costituisce consulenza finanziaria ne’ sollecitazione all’investimento. I risultati storici non sono indicativi di risultati futuri. Ogni attivita’ di trading comporta rischio di perdita del capitale.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15c59fe7a003" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Training a neural network Using Newton’s Method]]></title>
            <link>https://medium.com/swlh/training-a-neural-network-using-newtons-method-d02da8843133?source=rss-d2ca05e21155------2</link>
            <guid isPermaLink="false">https://medium.com/p/d02da8843133</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[newtons-method]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[CG_Musta]]></dc:creator>
            <pubDate>Sat, 20 Aug 2022 22:49:37 GMT</pubDate>
            <atom:updated>2022-08-20T22:49:37.636Z</atom:updated>
            <content:encoded><![CDATA[<p>The aim of this Blog is to understand if Newton’s Method can be used for optimisation in training a Neural network and compared with Gradient Decent. Neural networks are used for example in financial services for forecast, machine learning and artificial intelligence, representing algorithms that imitate the brain of a human using a large amount of data as input. The aim is to represent the connection between neurons and synapses in our brain.</p><p>A simple Neural Network is usually made by an Input Layer, a Hidden Layer (𝑵𝒏), and an Output Layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NEnCYCZ2KLncscXtzCqC-A.png" /></figure><p>Neural networks take some existing values and generate predictions based on these values or parameters. For example, if you want to train a machine to recognize a dog, you need to give the machine as much information about a picture of dogs and find a way to tell the machine that it is wrong when the guess is not the expected value and is right when the expected value is correct.</p><p><strong>Example of a Neural Networks</strong></p><p>In this example the values given to the Neural Network are width and length and based on these values, the next time is given only these two pieces of information should be able to guess if the object is a car or a motorbike.</p><p>In this example the Neural Network should be able to identify if a given object is a car or a motorbike by only receiving two inputs, width and length.</p><p>V= value (width, length) W = weight<br> B = bias term<br> P = prediction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*-0ry7Y5ZwGFF0Y5crxDm9g.png" /></figure><p>The parameter of (w1, w2 and b) are random and to find the right one the cost function can help. The cost function takes in current data and predictions and tells how far our prediction is from the given data set.</p><p>The given data set has to be minimized to tell if our prediction is close to the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*8BdW3so2GQRvitWCN8KO5w.png" /></figure><p>To get help in this part we are going o compare Gradient Descente and Newton’s method.</p><p><strong>Gradient Descent</strong></p><p>Gradient Descent is an optimisation Method, when fit a line with Linear Regression, it optimizes the intercept and Slope.</p><p>Example with a data set where the <strong>X-axis is the Weight </strong>and the <strong>Y-axies is the Height.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*KP3F9ih8OE1QMkYjS6keUg.png" /></figure><p>If we extend a line in the data set, we can use the line to predict some data. For example, if we have a weight of 1.5, we can say that the height is 1.9</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Re7ButThHsCPDwCAX1hfcA.png" /></figure><p>The Gradient Descent help to fit the line to data by finding the optimal values for the intercept and the Slope.</p><p><strong>Prediction of Y = Intercept + slope * Weight<br> </strong>We insert the <strong>0.64 </strong>as slope using the Least Squares estimate and we use the</p><p>method of Gradient Descent to find the best value for the intercept.</p><p>Fist step is to pick a random value for the intercept, this value is what gradient decent will use to improve the guess.</p><p>Starting value = 0<br>Now our line has a starting value of zero</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*j8Gs2LAvIlkWzzktoJ-edg.png" /></figure><p><strong>Prediction of Y = 0 + 0.64 * Weight</strong></p><p>Now to see how well the line fits in the data we use the <strong>Sum of the Squared Residuals which is a type of loss function.</strong></p><p>The first residual (x1, y2) (0.5, 1.4) give the prediction by plugging the Weight (X1) in the equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5iR7kptuUnprPrI20-nfg.png" /></figure><p><strong>Prediction of Y = 0 + 0.64 * 0.5 = 0.32</strong></p><p>The residual is given by calculating the <strong>Observed height </strong>and subtracting the <strong>Predicted Height</strong></p><p><strong>Residual = Height — prediction or<br> Residual = 1.4–0.32 = 1.1</strong></p><p>Using the residual of 1.1 we need to square it and sum it with the remaining residual to get the Sum of squared residuals.</p><p>𝑺𝒖𝒎 𝒐𝒇 𝒔𝒒𝒖𝒂𝒓𝒆𝒅 𝒓𝒆𝒔𝒊𝒅𝒖𝒂𝒍𝒔 = 𝑌𝑛 − (𝑦𝑛 − (𝑖𝑛𝑡𝑒𝑟𝑐𝑒𝑝𝑡 + 𝑠𝑙𝑜𝑝𝑒 ∗ 𝑤𝑒𝑖𝑔h𝑡)) 𝑺𝒖𝒎 𝒐𝒇 𝒔𝒒𝒖𝒂𝒓𝒆𝒅 𝒓𝒆𝒔𝒊𝒅𝒖𝒂𝒍𝒔 = (1.1)2 + (0.4)2 + (1.3)2 = 3.1</p><p>The below graph shows how a change in the intercept change the Sum of the Squared Residuals, increase from 0 to 1 gives a lower Sum Squared Residual, increase from 1 to 2 see an increase in the Sum Squared Residual.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNx2hmCzZCrnbBkl56V47w.png" /></figure><p>Gradient decent does less calculation when the value is far from the optimal solution and increase the number of calculation when getting closer to the best value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*h34cQJZkpzI9f4dobLciCA.png" /></figure><p>Now we take the derivative of the equation of the curve (𝑂𝑏𝑠𝑒𝑟𝑣𝑒𝑑 — 𝑝𝑟𝑒𝑑𝑖𝑐𝑡𝑒𝑑)2 to determine the slope at any value for the intercept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gc_WnKQ8Cu-rl8JezKH7-Q.png" /></figure><p>After taking the derivative of the sum of squared residuals, Gradient Descent can be used to find the lowest point for the Residuals. The value is found by taking small steps from the initial guess until it finds the best value. The closer the optimal value is from the intercept, the closer to zero is the slope. If the steps are to big the point may end up on the other side of the curve, if is step are too small it may take forever to arrive. To determines the Step Size Gradient Descent, multiply the Slope by a <strong>Learning rate </strong>for example 0.1.</p><p><strong>Step Size </strong>= Slope * Learning Rate<br> <strong>Next intercept </strong>= Old Intercept — Step Size</p><p>The algorithm will stop by using either a max iteration for example 1000 or when it gets close to zero</p><p><strong>Formula:</strong></p><p>Δ = diffrence between the predict and actual data point 𝑛 = 𝑛𝑢𝑚𝑏𝑒𝑟 𝑜𝑓 𝑑𝑎𝑡𝑎 𝑝𝑜𝑖𝑛𝑡</p><p>1𝑛 𝑀𝑒𝑎𝑛 𝑆𝑞𝑢𝑎𝑟𝑒𝑑 𝑒𝑟𝑟𝑜𝑟 𝑜𝑟 𝑐𝑜𝑠𝑡 𝑓𝑢𝑛𝑐𝑡𝑖𝑜𝑛:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*eaJldDfFkxQVBN-HM_7QRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*j-2Q0PjPx8ZSJ0tHNRKssA.png" /></figure><p><strong>Find partial derivative respect to m and b to get the slope</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*qG6Pink9cOqLJHG-h_lAXQ.png" /></figure><p><strong>Code:</strong></p><p>def gradiant_d(x, y): m=0</p><p>b=0<br> n_iterations = 10000<br> n = len(x)<br> learning_r = 0.08<br> for i in range(n_iterations):</p><p>pred_y = m * x + b<br> cost = (1/n) * sum([vl**2 for vl in (y-pred_y)])</p><p>md = -(2/n)* sum(x*(y-pred_y)) bd = -(2/n)* sum(y-pred_y)</p><p>m = m — learning_r *md b = b — learning_r *bd</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IMCJfuA-C1RczjQRkYpC8Q.png" /></figure><h3><strong>Newton Method</strong></h3><p>Newtons method is based on the observation that using a second derivative in addition to the first one can help to get a better approximation. The resulting function is no longer linear but quadratic.</p><p>To find the root it first starts by picking a random point <strong>(X1) </strong>and find out what the function evaluates at that value <strong>f(X1)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*5IktJgsqQaV3K8DQaASqFA.png" /></figure><p>Now when f(x = X1) is going to be equal to the height at point, the slope is going to be the derivative of this function evaluate at that point.</p><p>Slope = f’(x = X1)<br>Using the slope of the line we can find the second point (X2)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ERgDhY-3HSf_0u1490EG-g.png" /></figure><p>The next point is X2, to find it is going to be X1 minus the ∆𝑥 or the ratio between</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*wB0H-xZStWmeAc-ceTrhLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*NaNlKGYOQq1J-Xm21NXmkQ.png" /></figure><h3>Now to find the next point X3 the process can be repeated</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*DT-HfM4j4jy4v8BVDhUrcg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*Oe_dbDDFmHIhViBMLpfJUw.png" /></figure><p>Newton’s method when applied to Optimization gives a way to find the minimal or maxima. It considered a 2nd order method because it uses not only the first derivative and the gradient but also a 2nd derivative 𝑓′′(𝑥) also called the Hassien in a multivariable.</p><p>Instead to find the derivative of the 𝑓(𝑥) it tries to find the one at the derivative of the function evaluated at X.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*IFlw53TllhoWOHUeIzcA0w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*svfJR-BzoYPui4xqOkBxpQ.png" /></figure><p><strong>Code example:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RLxoU1zmqjk4VXC-EHPRBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gezI1sClsXNmUPtoeVM3bw.png" /></figure><h3><strong>Conclusion Newtons Method vs Gradient Descent</strong></h3><p>Gradient decent is a first order function that use the derivative of that function to find the minimal. Newton’s method is a root finding algorithm that use a second order derivative to find the minimal of that function. A second order derivative can be faster only if is known and can be computed easily, but most of the case this will require a lot of computation and can be expensive. If a 𝑁 is require for the first derivative a 𝑁2will be required to find the second one.</p><p>Gradient Decent is sensitive to the learning rate, and in case of a stationary points the algorithms will continuities to run. Newtons Method instead require to elaborate</p><p>𝑓′(𝑥)/𝑓′′(𝑥) 𝑓𝑜𝑟 𝑓′(𝑥) = 𝑓′′(𝑥) = 0, mean the program will stop with a division by zero error.</p><p><strong>Refrence</strong></p><p>Machine Learning Lecture 12 “Gradient Descent / Newton’s Method” -Cornell CS4780 SP17,</p><p>added by Kilian Weinberger. Available at URL [https://www.youtube.com/watch?v=o6FfdP2uYh4]</p><p>Rebentrost, P., 2022. <em>ShieldSquare Captcha</em>. [online] Iopscience.iop.org. Available at:</p><p>&lt;https://iopscience.iop.org/article/10.1088/1367-2630/ab2a9e&gt; [Accessed 2 January 2022].</p><p>Fletcher, R. (2005). “On the Barzilai–Borwein Method”. In Qi, L.; Teo, K.; Yang, X. (eds.). <em>Optimization and</em></p><p><em>Control with Applications</em>. Applied Optimization. Vol. 96. Boston: Springer. pp. 235–256</p><p>Avriel, Mordecai (2003). <em>Nonlinear Programming: Analysis and Methods</em>. Dover Publishing</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d02da8843133" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/training-a-neural-network-using-newtons-method-d02da8843133">Training a neural network Using Newton’s Method</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Queue Data Structure in Javascript — Interview questions]]></title>
            <link>https://medium.com/swlh/the-queue-data-structure-in-javascript-interview-questions-f4fb5a56fed0?source=rss-d2ca05e21155------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4fb5a56fed0</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[queue]]></category>
            <dc:creator><![CDATA[CG_Musta]]></dc:creator>
            <pubDate>Wed, 16 Dec 2020 21:50:34 GMT</pubDate>
            <atom:updated>2020-12-19T14:02:20.901Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Queue Data Structure in Javascript — Interview questions</h3><p>Data structures are all about runtime complexity, so before reading this article, I suggest you read my previous <a href="https://medium.com/swlh/what-is-the-runtime-complexity-or-big-o-notation-3ba90ecab904">blog</a> on time runtime complexity and Big O notation, <a href="https://medium.com/swlh/what-is-the-runtime-complexity-or-big-o-notation-3ba90ecab904">link</a>.</p><h3>What is Data Structures?</h3><p>When it comes to answering this question, there are two big points we need to consider:</p><ol><li>Data structures are a way for organizing information by using an optimal “runtime complexity” which involve adding, editing or removing records.</li><li>JavaScript offer natively several implementations of data structures. However, we still need to understand the “low level” one to be able to succeed in an interview.</li></ol><h3>Difference between an Array and a Queue</h3><p>In the below image, I’m comparing what an array in JS is capable to do with what a queue can do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*f1YHcVZP9idBEP5bR7oIrw.png" /></figure><p>We can say that the blue square is the capability of the JS array, and the small white square is the capability of the Queue. We can easily say that a JS array can definitely do whatever a queue can do plus a lot of more functionality. However, in an interview is really easy to be asked to implement a queue from scratch by considering all its limitation.</p><p>If you think about this concept, it doesn&#39;t make much sense. You may be wondering “I already have an array that can do whatever a queue can do, and you suppose to create a one our an array???”. Well, let see how we can give some sense to this interview question by building one and explain why a queue can be helpful in some situations.</p><h3>What is a Queue?</h3><p>A queue is like a container where data enter from one side and exit from the other side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*afmF1S0lZITkU_u3Ll04Bw.png" /></figure><p>A better way to think of a queue is pretended like data are people waiting to access into the theatre and to do that they need to first enter into a queue and exit from the other side. Each person entering into the queue need to wait his turn to exit. In a queue, there is no concept of cutting or skipping the line, the order you enter into the queue also determine the order in which you exit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*wfeHNYZXmsDxaOe5-33BoQ.png" /></figure><p>When you add something to a queue is referred to as Enqueuing or adding, and we referred to the exit process as Dequeuing or removing.</p><p>The queue follows a concept called <strong>FIFO</strong> or “First In First Out”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*EVQB3Kyu2IkRuUP03EK9Og.png" /></figure><p>Let say we have <strong>Data A</strong> and <strong>Data B</strong> that need to access a queue, at the moment our queue is empty we start by adding A.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*ssgtAhfnUQxJDIJJE1P2aA.png" /></figure><p>Now A is added tot he queue and we have 1 element inside, we need know to add <strong>Data B.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*Mgu2RyvF63HsHLUM96eYpg.png" /><figcaption>\</figcaption></figure><p>Now both elements are Enqueued, and the order appears as you can see in the picture we have first A and then B. Now we need to Dequeue the elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*mdJZbbKmV4YJSsrq-A1SFA.png" /></figure><p>A is the first element to exit as per FIFO concept First element to enter is the first element to exit. As you can see B now will be the last element to exit.</p><p>As you can see, a Queue is a rudimental implementation of an array. In JS to Enqueue or Dequeue element form an array, we use some pre-build method.</p><p>Add to a queue or Enqueue:</p><pre>array.unshift()</pre><p>Remove or Dequeue:</p><pre>array.pop()</pre><h3>Queue implementation</h3><p>Now that we know what a queue is and which method in JS can replicate the same behaviour, the rest is pretty straight forward. We are going to create a Class and initialize it with an empty array which is going to be our queue. In a classic Array we have different methods exposed to it such as shift, unshift, push, pop, splice and slice, but in this case, the only two methods that we are going to make accessible are unshift to add to the queue, and pop to remove.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*nuula4PosU4uaiFt177lTg.png" /></figure><p>So why would we need to limit an array by building a limited version of it?. First, this can be asked in an interview question, and you should be able to recreate a queue. Second, imagine you are working on a real project, and you come out with an algorithm that uses a queue to and by doing this algorithm much performs much better. However, you want to avoid that some other engineering comes and start to mess up your algorithm by treating the algorithm like a classing array and drop the performance of your hard work. This can be a good way to limit access to some of the functionality of a classic array.</p><h3>The code</h3><p>The first step is to create a class and initialize this class with an empty array</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*w6FW-3OTGr0P9iET5xi8sQ.png" /></figure><p>Now we need to add some methods to our class to interact with it by adding and removing records/data like in a queue, here is where we going use our unshift and pop JS methods from the array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*qpnWqt5NQjB_xDtIEwMl7A.png" /></figure><p>As you can see the implementation is not too difficult. The first method is the function inside our class is “add” which takes an argument and add at the beginning of the array the data we passed to it.</p><p>The second method is the “remove”, and same we call our array using “pop” method to remove the last element in the array.</p><p>Now we have our queue implemented in a few line of code and ready to be used, I hope you enjoyed my article and see you next week with a new blog ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4fb5a56fed0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/the-queue-data-structure-in-javascript-interview-questions-f4fb5a56fed0">The Queue Data Structure in Javascript — Interview questions</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Voice Note-Taking App in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/speech-recognition-javascript-create-vocal-note-taking-app-in-5-minutes-11444069d8e5?source=rss-d2ca05e21155------2</link>
            <guid isPermaLink="false">https://medium.com/p/11444069d8e5</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[speech-recognition]]></category>
            <category><![CDATA[vocal-command]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[CG_Musta]]></dc:creator>
            <pubDate>Mon, 14 Dec 2020 15:55:29 GMT</pubDate>
            <atom:updated>2020-12-14T16:44:11.355Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to use Speech Recognition in JavaScript</h4><p>Speech recognition does not require any libraries or external API, and we can implement this directly in the browser.</p><p>So what is speech recognition? Is a global variable that lives on of the windows object the browser. If you open any console in the browser and you type the following you can check that by yourself.</p><pre>window.SpeeechRecognition</pre><p>This works for Firefox, for Chrome, you need to use the following command:</p><pre>window.webkitSpeechRecognition</pre><p>First, we need to call it in our file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gSK8SmooEfEi-13k.png" /></figure><p>Now we need to create a new instance of the SpeechRecognition and assigned to a variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ejf89tcbMqNrLBPs.png" /></figure><p>To be able to see the result while speaking we need to set something called interimResults true:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uEDvQ3VImUDWTufM.png" /></figure><p>If you set it to false will wait until you finish speaking to show the results, but ideally, you want to see what are you saying while speaking, so it’s better to set this value to true.</p><p>Now to test if it works, you can create a button to start the event listener. Create a simple button in HTML and connect the HTML to your JavaScript file, give to the button element a class that you can target, for example, btn or mic.</p><p>HTML file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OLJtiJOGzHobFHwI.png" /></figure><p>I added a little emoji to my button to give some style.</p><p>Now select the mic class element in your JS file and store it in a variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U2ZyPxwLP0DJ0jfU.png" /></figure><p>Now we need to add an event listener to our button to start the SpeechRecognition, and our event is going to listen for a click in this case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DYGx-U-yB3fdCNG2.png" /></figure><p>Inside the event listener, we call the recognition. start() method to start recording. It’s all set now, but to see and be able to work with the result, we need to add an event listener to our recognition instance as well.</p><p>In this case, we are listening to a result event:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vks5ZsXu-cLoJeXs.png" /></figure><p>For the moment we can console log the result in our browser to see if it works. Now open index.html on the browser, when you click the button you may get a message like the below, click allow to start recording.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>Now if you speak to the mic, you should see in the console some event running, like the below example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>Amazing! now we have been able to add this function to our app, to access to the result and see if what you are saying is recorder properly</p><pre>e.results[0][0].transcript</pre><p>Event access to the results index zero of index zero, and you will find this in the transcript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/0*M56RmZP-cErh6g_j.png" /></figure><p>Now do the same and speak, and you should see the result instead of the event, I am going to say something like “ Hope you like my blog.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>Cool!</p><p>Now we are going to display this in the HTML and create a simple vocal note-taking app.</p><p>First, we need to create a &lt;div&gt; element in our HTML and give the class of words.</p><p>HTML:</p><pre>&lt;!DOCTYPE html&gt;&lt;html lang=&quot;en&quot;&gt;&lt;head&gt;&lt;meta charset=&quot;UTF-8&quot;&gt;&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;&lt;script defer src=&#39;index.js&#39;&gt;&lt;/script&gt;&lt;title&gt;Document&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;div class=&quot;words&quot;&gt;&lt;/div&gt;&lt;button type=&quot;button&quot; class=&quot;mic&quot; &gt;🎤&lt;/button&gt;&lt;/body&gt;&lt;/html&gt;</pre><p>In our JavaScript file, we need to grasp this element and create a p element, and we are going to insert our result inside this p element and append it to the div element to be able to see our result in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>Now we can test this in our browser and see if it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>Thank you for reading. I hope you found this useful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11444069d8e5" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/speech-recognition-javascript-create-vocal-note-taking-app-in-5-minutes-11444069d8e5">Create a Voice Note-Taking App in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The right strategy to easily make money investing in the stock market,]]></title>
            <link>https://mmcryptogem.medium.com/the-right-strategy-to-easily-make-money-investing-in-the-stock-market-535eb2e0468c?source=rss-d2ca05e21155------2</link>
            <guid isPermaLink="false">https://medium.com/p/535eb2e0468c</guid>
            <category><![CDATA[investment]]></category>
            <category><![CDATA[easy]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[money]]></category>
            <category><![CDATA[stock-market]]></category>
            <dc:creator><![CDATA[CG_Musta]]></dc:creator>
            <pubDate>Tue, 08 Dec 2020 00:18:45 GMT</pubDate>
            <atom:updated>2020-12-08T09:16:59.988Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*f-3G3jDC8k0ic25v9FJ-AQ.png" /></figure><p>I have been investing for over 7 years, and I invested in Options, Cryptocurrency, Forex, stocks, day trade, swing trade etc...</p><p>I basically made any possible investment online in the stock market, I lost money, and made money, and finally, I found a way to low the risk and get a good yearly return. In this article, I will give you some of my experience and tips I wished I had when I started my investment journey.</p><p>First a little bit about my self, I did so many jobs that sometimes I even struggle to remember where did I start and what I have done. My first job was in resorts as an entertainer, after two years I opened a bar in my hometown, after 1 year I sold it and started an export agency car with one of my friends for 4 years.</p><p>When the economic crisis started to hit the country, I had to leave and emigrate in UK where I start working as a bartender and waiters. I later moved to the hotel industry where I start a new career from the receptionist to supervisor and in final as Duty Manager in Hilton. My career in hospitality ended at Jumeria group as HOD Head of the department.</p><p>During this time, I was always investing every day every week every month. I love it and loved the challenge to understand this world of investment all these charts, the financial news and how this influenced our world. I spent hours looking at charts and start seeing some pattern on how investor think and feel about a particular stock or currency.</p><p>By gaining experience, you stop losing money, and you start to achieve the break-even point and slowly see some profit increasing over time. It’s more or less like when you have your own business, you need to invest money, and you don&#39;t call this a loss, but an investment. Until you reach, after 1 year or sometimes 2 years, the break-even point and start to see some profit, the same happens in the stock market, you need to invest some money but on your knowledge, and this will build up in time until you start to see some good Return On Investment (ROI).</p><h3>Why you need to start investing now</h3><p>let’s start to talk about how and when to start to invest.</p><p>The “when” it’s easy, as soon as you can. If you have some cash sitting in the bank and you are afraid to invest and lose them, I have bad news for you, because YOU ARE ALREADY LOSING MONEY. Every year your money lose around 2% in value, and this happens for something called inflation.</p><p>You may be wondering ok 2% is not that much, ok so let’s put it in this way. If you have $1000 and you are losing 2% yearly in 20 years this money worth $673. On the other hand, if you are just able to match the annual 2%, this money would worth $1484. Well, now multiply this for whatever money you have in the bank this can be 5, 10, 15, 20, 30, 40, 50 or 100 thousand, does it still sound like not much money?.</p><p>Investing is easy but not simple, you need to follow the rules, and just a few people can stick to the rules. You need to think long term, but people are impatient, you need to use the money you don&#39;t need, and people use the money they cannot hold for long term or afford to lose.</p><h3>Let’s start with the money management strategy</h3><ol><li>Start by investing between 25% and 35% of your money, NOT 100%.</li><li>In each stock, you buy invest the same amount, 2–3%.</li><li>Keep 10–20% of the money invested in cash to buy in deep (I will explain this later).</li><li>Hold at least 10–15 different assets/stocks.</li><li>Diversify your investment (technology, finance, health, insurance etc..)</li></ol><p>Simple rules, right? Well people, including me, struggle to follow them at the beginning until they realise the only way to gain profit over time.</p><h3>Where to invest?</h3><p>This is something that really depends on your style, but I can give my experience and stocks and index funds are the best investment you can do for long term investment. People think that is easy as a day trader to make money but if you think long term and you invest in a growing company and wait you may even double the profit that a day trader does and with less effort. But if you have a lot of time to invest in learning and looking at the chart, you can try with the forex and the day trade, but in my opinion, is too much effort, too risky and too stressful.</p><h3>Important rules!!!!</h3><p>NEVER USE LEVERAGE, if you don&#39;t know what is leverage check <a href="https://fbs.eu/en/analytics/guidebooks/leverage-and-margin-27?gclid=CjwKCAiAwrf-BRA9EiwAUWwKXqHobZAVzDT71QaLrBSFPIPrwVL3S15Vnb8hCFtGPYUiZRA_nk-D9BoCDYoQAvD_BwE">here</a>. This is where brokers want to bring you and push you to use leverage so you can expose your portfolio to high risk with the promise to have a high return, does it worth??, absolutely no. I know so many people burning their entire portfolio by using leverage. You cannot time the market, and if you think you can, you are a fool.</p><h3>Overview of the strategy</h3><p>So let’s talk about how did I manage to have low risk and high return.</p><ol><li>First of all, half of my capital is invested in an index fund. My favourite one is the FTSE100. But any of the most important indexes are a good choice, S&amp;P500 also another good one. Having something like the FTSE index gives you the chance to invest in the best 100 companies in the UK or USA or any other country you would prefer. Plus you earn dividends every year.</li><li>Invest in growing companies, Google, Amazon, Netflix, Apple etc.… These are just a few but you need also to look for companies that everyone talks about, which aim to can change the way we live. If a company has a unique business model and can change society, business, culture etc. is the right stock to buy</li><li>I usually read a lot and monitor investors’ websites which are not free, unfortunately, but many are free and you can use them, but If you want the best websites that can give you a good overview of a company etc you have to spend money. I prefer to pay because sometimes in a few days I can recover the money I pay for 5 years subscription if I can read properly the info given.</li><li>Hold at least 10–15 stocks in your portfolio.</li><li>Don’t panic when the market goes down 10–20% if you did your research and company is solid it will come back 100%.</li><li>Buy deep, means that if your stocks go down, don’t freak out, the market is just giving you a chance to buy your favourite stock a lower price if you can catch the opportunity buy more and hold.</li></ol><h3>Visualize the concept</h3><p>Let say we have a portfolio of $100, we decided in advance the money management, and important is to stick to the plan, if you sai to invest a certain amount stick to that amount don&#39;t put everything in one go.</p><p>We want to invest 50%, and 50% keep it in case the market fall to buy in deep.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*js1CCK_9SPmwOCpmo46hBQ.png" /></figure><p>After one month we have the following situation, 3 stock are up a total of 60%, and 2 are down 50%. We are still in gain, and this is because we have good money management. If one of the stock had a higher % to another, we could risk to have that stock down and compromise the entire portfolio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*9txK6NAuPVlTX9XLcPvoMg.png" /></figure><p>This strategy is good. If one of your stock is up you can sell it if you aim to a particular % like 10%. However, I suggest always to hold for a long time. If a company is performing well can do even 100% Its initial value, this is why I always hold a stock for at least 1 to 3 years.</p><p>Another good reason to keep some cash on the side, imagine that the two stock down is Apple and Amazon. We all know that these companies are solid and are not going out of business anywhere soon. Well, this is a good time to buy these amazing stocks at a lower price and just wait for the market run-up again to double your profit.</p><p>Now we double on our losing stocks, I usually do that when I have a solid stock that went down, and I am sure it will recover, and as I said the first rule is to invest in good stocks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*ujbxRR7rVi-h6IyKNH2ZtQ.png" /></figure><p>Let say we double our investments on the losing stocks, and one month later this happens. The stocks that up went down and the one down went up. But we are still in Green because we used a good strategy, good companies, and not penny stock or IPO, and we stuck to the plan.</p><p>I saw many people losing money because they buy and once it goes red they sell, and later that stock recover and go even further. Another reason to lose money is to believe in rumours and put all your money or a big chunk of your money in 1 stock, and this stock does not perform as it should too and even having all the other stock in green you have your portfolio down, I call this bad money management.</p><p>And remember not just becue you lost an opportunity does not mean that next week or next month you won’t have the similar or even better opportunity. So wait, think long term, relax and enjoy the ride. Investment is fun and profitable, don’t turn this into a race and stressful environment for you</p><h3>Learn how to invest in the right companies without effort</h3><p>You may be wondering, well, I don’t want to do research or west time reading and look at charts every day etc. Well you don’t have to I am happy to share all my stocks in real-time with you, and if you don’t want even to open your account to trade, e-toro offer a good way to copy other investors.</p><p>You can deposit your money wait and earn passive income by leaving the hard work to other traders like me, this is called copy trade and many people are earning good profit by doing basically nothing just investing in other people portfolio which can be mine or someone else.<br>If you want to follow me and check my portfolio below the affiliate links if you use it to deposit and register you can copy me, and I will give you full access to my strategy and signals</p><p>How? follow the link and after you registered you can contact me on <a href="https://www.facebook.com/profile.php?id=1286523066">Facebook</a> or <a href="https://www.linkedin.com/in/mustafa-mohamed-mahmoud-77631295/">Linkedin</a>.</p><p>I hope you enjoyed this overview on investment, and if you want to learn more get in touch.</p><p><a href="https://etoro.tw/30Fgt2P">https://etoro.tw/30Fgt2P</a></p><p><a href="https://etoro.tw/30Fgt2P">faraon88 @faraon88 - eToro</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=535eb2e0468c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is the Runtime Complexity or Big ‘O’ Notation?]]></title>
            <link>https://medium.com/swlh/what-is-the-runtime-complexity-or-big-o-notation-3ba90ecab904?source=rss-d2ca05e21155------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ba90ecab904</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[run-time-complexity]]></category>
            <dc:creator><![CDATA[CG_Musta]]></dc:creator>
            <pubDate>Sun, 06 Dec 2020 00:05:32 GMT</pubDate>
            <atom:updated>2020-12-06T17:33:52.360Z</atom:updated>
            <content:encoded><![CDATA[<p>You probably heard a lot about runtime complexity and how this can help you to build better code and solution, but what is the run time complexity???</p><p>You probably experience in your coding journey moments where you had to implement a function to solve a problem in your project, or maybe you solved some challenges using a solution and later seeing a hundred of different solutions. So what is the difference between the solutions and how can you measure which one is best then another? .This is where runtime complexity comes in play.</p><p>Runtime complexity is way to describes the performance of an algorithm, or how much more processing power/time is required to run the algorithm, and what happens if we double the input?. Runtime complexity compares different solutions to a given problem or different algorithms.</p><p>This is one of the most common and often asked questions, and you should be able to identify the run time complexity of the solutions you implemented and how can you improve where is possible.</p><h3>Linear runtime O(n)</h3><p>Let see a simple example of finding the right dog for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tk6JKCCKpYHo6tYLhDFnqg.png" /></figure><p>To solve this challenge, we are iterating into each dog one time, and this means that for each dog added to our array, the filter method has to do some additional work. So 1 dog = 1 extra step.</p><p>We can say that it is a solution that has a complexity of “N” or “linear” runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*uhmYg7E0zcde5e6Sf-EOOQ.png" /></figure><h3>Quadratic runtime o(n²)</h3><p>Let’s see another challenge the steps algorithm, that you can find <a href="https://moustafamm.medium.com/data-structure-and-algorithm-common-interview-questions-part-3-393b1098df60">here</a>,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*sJLegAyZ8WuZV1x-XpWXVA.png" /></figure><p>In this challenge we have and N input, and based on this input, we have 2 nested loops. This means that for each “N” input we have to do some additional work, but this time we have two for loop has to iterate through our input. But how much work we have to do this time?.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9p40XhWKP1b1OjX6blmqvA.png" /></figure><p>In this example, our solution for an input N= 2 has to do 4 things and for the input of N =3 the work increased from 4 to 9, and if insert an input N =4, the steps to do increased to 16.</p><p>In this solution, every time we increase the input by one, we have to do a significant amount of additional steps and is clear that is not a 1 to 1 relation between the input and the algorithm. We can say that the amount of work had to do N squared O(n²) = (2², 3², 4²) or quadratic runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*noYxSdioM8UJ3hvR1T9BGg.png" /></figure><h3>Other types of common run time</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*EIZ0vgp1aOv7jnAuZ-h9KQ.png" /></figure><p>So far, we saw and discuss many different types of time complexity, but another way to referencing this topic is the Big ‘O’ Notation. It’s really common to hear both terms, and you need to know that are bot refereeing to the time complexity or the efficiency of your algorithm, Example:</p><p>Linear time = O(n)</p><p>Constatn time = O(1)</p><p>Quadratic time = O(n²)</p><p>The O, in this case, stand for Big ‘O’, because is literally a big O.</p><p>Now I want to share some tips to identify the run time complexity of an algorithm. This is not a rule that you must follow, but a simple little guide that can help or direct you in the right way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*3IvijkQet-iVgCc9n4nw4g.png" /></figure><p>I hope you enjoyed my little introduction to Big O notation, in case, please leave a clap and share your feedback :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ba90ecab904" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/what-is-the-runtime-complexity-or-big-o-notation-3ba90ecab904">What Is the Runtime Complexity or Big ‘O’ Notation?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Structure and Algorithm Common Interview the Matrix Spiral]]></title>
            <link>https://medium.com/swlh/data-structure-and-algorithm-common-interview-the-matrix-spiral-e55e4fbc4b41?source=rss-d2ca05e21155------2</link>
            <guid isPermaLink="false">https://medium.com/p/e55e4fbc4b41</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <dc:creator><![CDATA[CG_Musta]]></dc:creator>
            <pubDate>Sun, 29 Nov 2020 13:54:42 GMT</pubDate>
            <atom:updated>2020-12-01T06:15:36.721Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Structure and Algorithm Common Interview question the Matrix Spiral.</h3><p>Please check my past <a href="https://medium.com/swlh/data-structure-and-algorithm-common-interview-the-pyramid-and-find-the-vowels-challange-2922755ffb5c">blogs</a> series for more exercise.</p><p>The challenge we are discussing here is probably one of the toughest to understand and even tougher to explain, and you will probably see why as soon as I explain it.</p><h3><strong>The question</strong></h3><p>Write a function that accepts an integer N and returns an NxN spiral matrix.</p><p>Examples</p><pre>matrix(2)</pre><pre>[[1, 2],<br> [4, 3]]</pre><pre>matrix(3)</pre><pre>[[1, 2, 3],</pre><pre> [8, 9, 4],</pre><pre> [7, 6, 5]]</pre><pre> matrix(4)</pre><pre>[[1, 2, 3, 4],</pre><pre>[12, 13, 14, 5],</pre><pre>[11, 16, 15, 6],<br> <br>[10, 9, 8, 7]]</pre><p>It&#39;s not really clear the above explanation and example, so let’s first try to visualize what the solution should look like. We are getting and N number in our function, and we are required to return and NxN Spiral Matrix.</p><p>We need to create an array that takes some subarrays and returns the number inside the subarray in a way to create something like the below spiral. So our counter should follow the spiral partner.</p><p>For example, we are going to use N = 3. If you look at the below shape and then at the output of the example considering that N = 3 you will have a clear picture of the challenge requirement now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2l3_MboAOl60xpKYAdroMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mmn1-rtFv65C7yS2ExygwA.png" /></figure><h3>The Solution</h3><p>To solve this challenge, we require multiple steps. I will draw step by step in which point of the code and solution we are for a better understanding.</p><p>We need to visualise the solution In a Matrix and assgin variable to start row and end row, and same for the column we need to assign variable to start column and end column.</p><p>In the below example, you have the Matrix of the solution, plus I added the numeric value to each variable directly on the picture so you can follow step by step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YFFNBtDmDx4OZVLLW0WsYA.png" /></figure><ol><li>Create a result variable and assgin an empty array</li><li>Push in the result array a number X of the nested array equal to the N value input.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*C_cioRkTtdC5Tn4kvYSS3g.png" /></figure><p>Now we should start to solve our challenge with a result array that looks like this:</p><pre>[[ ],[ ],[ ]]</pre><p>3. create 5 variable, one of the counter starting at 1 a startCoumn starting at 0 and a startRow starting at 0. To find the endColum and the endRow we need to do N -1. In this case, our input example is 3, so we have [3–1 = 2].”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*mQPZjFv24ttP4DsyqT0jLQ.png" /></figure><p>4. Now we need a while loop that keeps running until our start column is less or equal to the end column &amp;&amp; start row is less or equal to the end row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*msFQoAA-Bp06Chm90P_ewA.png" /></figure><p>Now we need to start put some value in our nested arrays and increment the value of the variable created.</p><p>5. First we need to take care of our top row in the solution;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WiWDKl-FTKukF49A_FAMrQ.png" /></figure><p>We need to write multiple for loop, and the first one will take care of this top row.</p><p>We are going to iterate from the start column to the end column and increment the start column inside our loop. And in the meantime push, the counter value in our first nested array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*FWyBjixejKg29RKET6mRVQ.png" /></figure><p>This loop will fill up our first row and in the end increment the row variable by 1.</p><p>At this point, our array result looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3HQ7ECmPBKgxT7qlEi-43w.png" /></figure><p>We solved the top row, and our start row now is incremented by one, and our counter is now equal to 3.</p><p>6.Now we need to take care of the right-hand side column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7mgq5yRo0tenOyDhG7gBgw.png" /></figure><p>Our second loop will start from start row, which is equal to 1 now and loop to the end row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*o4_YfObNoC6AH6pbNw_UJQ.png" /></figure><p>Now we are targeting the last two nested array, and we want to push the value at the last index of each nested array. result[i] will grab the array at the index 1 which is the value of our starRow, and result[i][endColum] is going to push the result of the counter in the last index equal to 2 of our nested arrays. In the end, we need to decrement the endColumn variable by 1.</p><p>Now our result array looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70dmosQXd1EmuKZ5Yb98Aw.png" /></figure><p>As you can see, we solved the right column, and our end column now is decremented by one.</p><p>7.Now we need to solve the bottom row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*URSzJIyi_zQ-ZcjZ8BSMrQ.png" /></figure><p>For this for loop, we are going to iterate from our end column which starts at 1 through the start column equal to 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*bDBJeZcrj5sCfiZLSJ1IUw.png" /></figure><p>Results [endRow] will target the last nested array, and results[endRow][i] will push the result into the middle index and decreased the result until to fill up all the bottom row. In the end, we need to decrease our end row by 1</p><p>Now our result array looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yuZZH3ILkMCPnFNFzFJODA.png" /></figure><p>You can see that the bottom row now is completed and we moved up to one our end row to target the middle part of our matrix diagram.</p><p>8. In this for loop we need to take care fo the left side column;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rT0-e8sQaNUvmB8Jsly8Zw.png" /></figure><p>This last for loop will iterate from the end Row which is now equal to 1 through the start row in this case equal to one so in this case we are going to make just one single loop. In the end, we need to increment the start column by 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kYsmE7tu9BVuhTuJvJSwqg.png" /></figure><p>results[i] should give us the middle nested array at index 1 and results[i][startColumn] will place the counter result in index 0 of the nested array.</p><p>Now our result looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jipLV2840oMiMSkaWAxmVw.png" /></figure><p>Now our while loop will run one more time and will fill up the missing middle value, the only for loop that will runt this time is the first one and after that will exti our while loop, and we return the result array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TJ7iSEDnz8JYPMRBrjrpQ.png" /></figure><p>The full code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2H8nO5FNganukGU0pVBpmA.png" /></figure><p>I hope you enjoyed my matrix challenge, and you could follow the logic of the solution. If you have an any better solution, please leave feedback in the comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e55e4fbc4b41" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/data-structure-and-algorithm-common-interview-the-matrix-spiral-e55e4fbc4b41">Data Structure and Algorithm Common Interview the Matrix Spiral</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Structure and Algorithm Common Interview the Pyramid and Find the Vowels Challange.]]></title>
            <link>https://medium.com/swlh/data-structure-and-algorithm-common-interview-the-pyramid-and-find-the-vowels-challange-2922755ffb5c?source=rss-d2ca05e21155------2</link>
            <guid isPermaLink="false">https://medium.com/p/2922755ffb5c</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[CG_Musta]]></dc:creator>
            <pubDate>Sun, 22 Nov 2020 14:57:08 GMT</pubDate>
            <atom:updated>2020-11-23T08:19:31.088Z</atom:updated>
            <content:encoded><![CDATA[<p>Please check <a href="https://moustafamm.medium.com/data-structure-and-algorithm-common-interview-questions-part-3-393b1098df60">part 3</a>of this blog for more exercise.</p><p>In this 4th part of my weekly interview question blog, we going to explore 2 important questions: <strong>Pyramid and Find The Vowels.</strong></p><h3>Pyramid</h3><p>This challenge is probably one of the most difficult ones to explain and solve if you never saw the solution before, I will do my best to explain the solution but it would probably take you some times to figure out the logic by yourself. However, if you followed part 3 of this series of blogs, the step question is similar to this one, and I suggest you take a look at it before to try solving the following challenge.</p><p>The Question:</p><p>Write a function that accepts a positive number N. The function should console log a pyramid shape with N levels using the # character. Make sure the pyramid has spaces on both the left *and* right-hand sides</p><p>Examples</p><pre>pyramid(1)</pre><pre>‘#’`</pre><pre>pyramid(2)</pre><pre>‘ # ‘<br> <br>‘###’<br> <br>pyramid(3)</pre><pre>‘ # ‘</pre><pre>‘ ### ‘</pre><pre>‘#####’</pre><p>As you can see is similar to the step one in the previous blog but you need to create a pyramid shape in this one and where you don&#39;t have the # sign you need to add a space “ ”.</p><h3>Solution 1</h3><p>Example using an input of 3 in our function:</p><ol><li>The best way to visualize the solution is by drawing down what happens inside the output, as you can see we have some column and rows. The first things to find is the patter between N row and N of the column. The number of rows is pretty easy as it’s equal to the N number. For the number of columns, the relation is (N*2 -1), we need to double our input and subtract 1 and we get the number of columns.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ta0uDL5lySX-IzjoSCg3bA.png" /></figure><p>2. We need to find the middle point and save it into a variable, and we can find the middle with the flowing calculation: Math.floor((2 * n -1)/2)</p><p>3. Create a for loop from 0 to N, to be able to loop through the rows.</p><p>4. Inside the first loop we create the variable solution or Pyramid whatever you prefer, and this is going to be the solution that we will console.log to the user.</p><p>5. now we need a second for loop, to loop through the number of columns.</p><p>6. Now we need to figure out which condition to write to make sure that we add a # or space ‘ ’ where we need. I will show you the code first and then with a table, I will try to explain the logic of the code.</p><pre>for(let column = 0; column &lt; 2 * n -1; column++){</pre><pre>   if(midPoint - row &lt;= column &amp;&amp; midPoint + row &gt;= column){</pre><pre>      level += &quot;#&quot;</pre><pre>    } else {</pre><pre>     level += &quot; &quot;</pre><pre>}</pre><p>Here we are checking if our midpoint minus the current row is smaller or equal to the current column we are iterating &amp;&amp; if the midpoint plus the current row is greater or equal to the current column.</p><p>Best way to visualize the solution here is with the current table I created which use the operator &amp;&amp; to find where to place the #. Remember that both conditions need to be met to add the # else we are going to ad space “ ”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U7Ndi_ipGDf_Z1CDVoND0Q.png" /></figure><p>Hopefully is not too confusing for you, but we are going to analyse together this table. First, we consider that our N number is 3 and our middle point is 2 on the first 2 columns you can see the condition we are looking for with our if statement and since the condition is 2 for each loop I created to a different row if both are met I designed a circle around, as you can see some are met and some are not but when both are met we place our # and if you take a close look to our circle where both conditions are met you can see a Pyramid shape, and if you compared to the first table that shows our output you can see are similar.</p><h3><strong>The Code:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yeLrMJtf60C1Hsdn3Y8Uw.png" /></figure><h3>Find The Vowels</h3><p>Now is time to take a more easy challenge after the previous one.</p><h3>The question:</h3><p>Write a function that returns the number of vowels used in a string. Vowels are the characters ‘a’, ‘e’ ‘i’, ‘o’, and ‘u’.</p><p>Examples</p><pre>vowels(‘Hi There!’) → 3</pre><pre>vowels(‘Why do you ask?’) → 4</pre><pre>vowels(‘Why?’) → 0</pre><p>we need to consider also the lower and the upper case in this solution.</p><h3>The Solution</h3><ol><li>Create an array where to store all the Vowels we want to check in our string.</li><li>Take our input string and transform it into an array that we can iterate.</li><li>Create a variable that counts the number of Vowels we find inside our array.</li><li>Use for loop to iterate into the array and for each element we need to lowercase it and check if is included in our array using the Includes method.</li><li>If a vowel is found add 1 to our count otherwise don&#39;t do anything and return the count in the end.</li></ol><h3>The code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*ezFG0n1LTA1HeQHcfJNQKw.png" /></figure><p>I hope you enjoyed these new challenges we analysed together in this blog, if you have a better solution, which I am sure exists, please comment below :).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2922755ffb5c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/data-structure-and-algorithm-common-interview-the-pyramid-and-find-the-vowels-challange-2922755ffb5c">Data Structure and Algorithm Common Interview the Pyramid and Find the Vowels Challange.</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>