| I found this interesting boomerang puzzle that many people could get wrong the first time. | Especially if you ask them to do it in one line — as we're going to try to do. | const arr = [4, 9, 4, 6, 3, 8, 3, 7, 5, -5, 5]; console.log(countBoomerangs(arr)); // 3
| It's all about counting the "boomerangs" in a list. Can you do it? | Maybe you first want to do what the hell a boomerang is right? | Okay so it's like, any section of the list with 3 numbers where the first and last digits repeat: like[1, 2, 1] : | So how many boomerangs can you see in [4, 9, 4, 6, 3, 8, 3, 7, 5, -5, 5]? | … | It's 3 | [4, 9, 4] [3, 8, 3] [5, -5, 5]
| So the puzzle is to write an algorithm to find this pattern throughout the list. | But here's where it gets tricky: The algorithm should also count overlapping boomerangs — like in [1, 5, 1, 5, 1, 5, 1] we have FIVE boomerangs — not two — I even thought it was three at first — no it's freaking five. | So how do we go about this? | My first instinct is to loop through the list and and then when we get up to 3 items we can do the calculation. | It's one of those situations where we need to keep track of previous values in the loop at every step of the loop. | So in every loop we'll have one value for the current item, the previous items, and the one before that. | How do we keep track of all the items? | For the current items it's super easy of course -- it's just the current iter variable: | countBoomerangs([1, 2, 1, 0, 3, 4, 3]); function countBoomerangs(arr) { let curr; for (item of arr) { curr = item; console.log(`curr: ${curr}`); } }
| What about keeping tracking of the previous variable? | | Writer RAG tool: build production-ready RAG apps in minutes | RAG in just a few lines of code? We've launched a predefined RAG tool on our developer platform, making it easy to bring your data into a Knowledge Graph and interact with it with AI. With a single API call, writer LLMs will intelligently call the RAG tool to chat with your data. | Integrated into Writer's full-stack platform, it eliminates the need for complex vendor RAG setups, making it quick to build scalable, highly accurate AI workflows just by passing a graph ID of your data as a parameter to your RAG tool. | Learn more about our production ready RAG tooling here. | | There's a reason 400,000 professionals read this daily. | Join The AI Report, trusted by 400,000+ professionals at Google, Microsoft, and OpenAI. Get daily insights, tools, and strategies to master practical AI skills that drive results. | Sign up now for free and work smarter, not harder. | Best, The Coding Beauty team |
|
0 Komentar untuk "Are you sure you can solve this "boomerang" coding puzzle?"