teleren/devto huggingface dataset:
#2 - Leetcode - Kids with the greates number of candies solution
Published: 2023-11-07 00:00:00

---
title: "#2 - Leetcode - Kids with the greates number of candies solution"
description: "Kids with the greates number of candies solution"
published: true
date: "2023-07-11"
---

Original post: [brsjsk.github.io] (https://brsjsk.github.io/posts/leetcode-greatest-number-of-candies)
Github [url](https://github.com/BrsJsk/2-kids-with-the-greatest-number-of-candies)
Leetcode [url](https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/)

---

There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have.

Return a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise.

Note that multiple kids can have the greatest number of candies.

Example 1:

```
Input: candies = [2,3,5,1,3], extraCandies = 3
Output: [true,true,true,false,true]
Explanation: If you give all extraCandies to:
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
```

---

# Solution 1

```
/**
 * @param {number[]} candies
 * @param {number} extraCandies
 * @return {boolean[]}
 */
module.exports.kidsWithCandies = (candies, extraCandies) => {
    const largestNumber = Math.max(...candies);

    return candies.map(candie => candie + extraCandies >= largestNumber);
};
```

This is a very simple one-liner solution..but, it's slower to execute then a good old for loop.

```
Runtime: 136 ms, faster than 5.86% of JavaScript online submissions for Kids With the Greatest Number of Candies.
Memory Usage: 36.7 MB, less than 10.89% of JavaScript online submissions for Kids With the Greatest Number of Candies.
```

# Solution 2

```
/**
 * @param {number[]} candies
 * @param {number} extraCandies
 * @return {boolean[]}
 */
module.exports.kidsWithCandies = (candies, extraCandies) => {
    const largestNumber = Math.max(...candies);
    let items = [];

    for (let i = 0; i < candies.length; i++) {
        items.push(candies[i] + extraCandies >= largestNumber)
    }

    return items;
};
```

```
Runtime: 76 ms, faster than 46.11% of JavaScript online submissions for Kids With the Greatest Number of Candies.
Memory Usage: 37.1 MB, less than 7.66% of JavaScript online submissions for Kids With the Greatest Number of Candies.
```

# Difference

Difference in execution speed is quite noticable.
![](https://brsjsk.github.io/static/4a0ca2e0091c77554423ffa8d47e2d19/e751c/ms_speed.png)

But difference in memory usage? Ehh, not so much noticable..
![](https://brsjsk.github.io/static/73d9f1c68de3593cd061d28e1f4fd623/62a6a/mb_usage.png)
What is a memberwise initializer in Swift?
Tags: swift
Published: 2023-11-15 17:10:00

This is a heuristic I, a front-end developer learning SwiftUI, used to mentally map this intimidating term.

###Mapping each word:###

- Initializer: A function that initializes an instance of an object, in this case, a structure, a.k.a. struct
- Member: Members is another term for the properties of the struct
- Wise: Knowledgable about the struct members/properties and capable of generating code 

###Putting it together:###
A memberwise initializer is an initializer function that the Swift compiler conveniently auto-generates for you when you define a struct. This saves you the mundane task of writing an initializer function for structs.

###A visual:###
![A screenshot of the struct code below with Xcode's code completion popup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ct106nfjnzabu3nn5gia.png)
See the suggested completion for the Song struct. It shows you the memberwise initializer’s function signature. Notice I did not type out an init function.

###Try it yourself:###
```swift
struct Song {
    let bpm: Int
    let artist: String
}
let greatestHit = Song( // code completion pops up here
```

I encourage you to build a deeper understanding of the term by [reading Bart Jacobs' article on memberwise initializers](https://cocoacasts.com/swift-fundamentals-what-is-a-memberwise-initializer) and following along with his code examples in XCode’s Playground. It’s also always a good idea to [read the official Apple documentation, for now on memberwise initializers](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/initialization/#Memberwise-Initializers-for-Structure-Types), for the freshest information, as Swift is updated about twice yearly.

Thanks for your time. Let me know if you have questions or suggested improvements to this post.
Is it worth keeping your CSS DRY - pros and cons
Tags: css, maintainability, consistency, scalability
Published: 2023-11-15 17:04:07

You can avoid repetition in CSS through techniques like using classes, inheritance and preprocessors like Sass. Here are three pros and three cons associated with avoiding repetition:

**Pros**

Maintainability: By minimizing repetition, your code becomes more maintainable. If you need to make a change, you only have to do it in one place, reducing the risk of errors and making updates faster and more efficient.

Consistency: Reducing repetition helps ensure consistency across your styles. If a particular style is applied consistently through classes or inheritance, it's less likely to deviate from the intended design.

Scalability: Code that avoids repetition is generally more scalable. As your project grows, maintaining a [DRY (Don't Repeat Yourself)](https://webglossary.info/terms/dont-repeat-yourself/) codebase becomes increasingly important. It allows for easier expansion without a proportional increase in complexity.

**Cons**

Less intuitive code: Over-reliance on abstraction methods (like using mixins in preprocessors or [UDJO (using declarations just once)](https://webglossary.info/terms/using-declarations-just-once/)) can result in code that is less intuitive, especially for developers who are not familiar with the specific abstractions or conventions used in the project.

---

It seems that the pros far outweighs the cons. That is avoiding repetition in CSS has benefits in terms of maintainability, consistency and scalability. However, it can result in less intuitive code.

What are your thoughts? How do you avoid repetition and keep your CSS DRY?
Getting Your Coin Balances with JavaScript
Published: 2023-11-15 17:01:08

Alice, a proactive investor, ventured into the volatile yet exciting world of cryptocurrencies. She meticulously spread her investments across various networks to minimize risk and maximize potential gains. Aware of the importance of security, Alice backed up her private key, ensuring a layer of safety for her digital assets.

However, upon transitioning to a new computer, Alice faced a minor setback. Her trusty MetaMask, which once offered a seamless view of her portfolio, was not yet installed. The initial sense of panic was quickly subdued by her technical acumen; she realized it was an opportunity to create a personalized solution.

Alice decided to develop a small application to monitor her diverse coin holdings across different networks. She envisioned a tool that would not only display her balances in real time but also provide alerts for significant market movements.

**The Code**

```
function getBalances() {
    const walletAddress = "<WALLET_ADDRESS>";
    const networks = [
        {
            name: "Polygon Mumbai",
            rpc: "https://polygon-testnet.public.blastapi.io/",
        },
        {
            name: "Fantom Testnet",
            rpc: "https://rpc.ankr.com/fantom_testnet/",
        },
        {
            name: "Binance Smart Chain Testnet",
            rpc: "https://data-seed-prebsc-1-s1.binance.org:8545/",
        },
    ];

    networks.map(async (network) => {
        const web3 = new Web3(network.rpc);
        const balance = await web3.eth.getBalance(walletAddress);
        console.log(network.name, "balance", Web3.utils.fromWei(balance.toString(), "ether"));
    });
}
```

If you are not sure about the networks where you have coins, you can go to [ankr](https://www.ankr.com/rpc/)and add all of the RPCs to check.

You can try [DevWeb3.co](https://devweb3.co) and see what they offer as a tool for checking wallet balances across multiple networks. This utility is part of a broader toolkit aimed at assisting Web 2.0 developers in exploring and integrating Web3 technologies into their workflows.
🚀 Exciting Update: 'Mastering Dynamic Programming with LeetCode's 'Counting Bits'!' 🎥
Tags: leetcode, codenewbie, learning, techtalks
Published: 2023-11-15 16:55:51

Hello, tech enthusiasts! I'm delighted to share my latest video where I tackle the challenge of LeetCode problem 338 - 'Counting Bits' using dynamic programming techniques. Join me as we explore an efficient dynamic programming approach to count bits in an array.

🎥 Watch the video here: https://youtu.be/-DUB-c7uxog
🔗 Access the code on GitHub: https://github.com/Vinay352/Leetcode/tree/main/0338-counting-bits
🔗 Explore the LeetCode question: https://leetcode.com/problems/counting-bits/

Your thoughts and comments are highly valued, so feel free to share your insights below. Let's continue our collective journey of learning and coding! 💡👨‍💻

Stay connected:
🎥 YouTube: hhttps://www.youtube.com/@VinayJainDev3097/
📚 Medium: https://medium.com/@vinay.j3097
📝 Dev.to: https://dev.to/vinay_jain_dev
🔗 GitHub: https://github.com/Vinay352
🐦 Twitter: https://twitter.com/vinayj3097
📸 Instagram: https://www.instagram.com/vinay_jain_dev/
📘 Facebook: https://www.facebook.com/vinayj3097/
Summit Electrical Solutions llc
Published: 2023-11-15 16:47:50

Summit Electrical Solutions LLC, the premier electrical contractor in Gillette. Our dedicated team of skilled professionals is committed to delivering top-notch electrical services for both residential and commercial clients. With years of experience, we specialize in wiring, repairs, lighting installations, electrical panel upgrades, and generator installation services. We take pride in providing reliable solutions that ensure the safety and efficiency of your electrical systems. Whether you need a residential electrician for home improvements or a commercial electrician for complex projects, we have you covered. Our commitment to quality craftsmanship and customer satisfaction sets us apart in the industry.
Business Address: 518 N HWY 14-16 SUITE B, Gillette, WY 82716, USA
Business Phone Number: 307-228-7778

Website: [https://www.summitelectricalsolutions.com/](https://www.summitelectricalsolutions.com/)

Business Hours: [Mon-Sat 8AM–5PM, Sat-Sun Closed]
It's something™
Tags: hacktoberfest23
Published: 2023-11-15 16:39:24

---
title: It's something™
published: true
tags: hacktoberfest23
---

### Intro

This is my first time really attending a hacktoberfest.

In fact more than half of the PRs are sent to my own repositories including side projects. But the changes are serious.

### Highs, no Lows

- The most meaningful PR is perhaps mine to [opendal](https://opendal.apache.org/). This is my 2nd Rust PR in my life and the reviewers were really friendly.
  - There is a long story about why I wanted to contribute to Python binding of opendal, 2 languages I don't know or use much. I'm not telling here :facepalm: .

### Growth

I'm a learning by doing person. It feels even more interesting if while learn something new I can build something useful.
Placeholder Contributor
Tags: hack23contributor
Published: 2023-11-15 16:31:55

<!-- ✨This template is only meant to get your ideas going, so please feel free to write your own title, structure, and words! ✨ -->

### Intro
<!-- Share a bit about yourself as a contributor. Is this your first Hacktoberfest, or have you contributed to others? Feel free to embed your GitHub account by using {% embed LINK %} -->

### Highs and Lows
<!-- What were some of your biggest accomplishments or light-bulb moments this month? Did any problems come up that seemed impossible to fix? How did you adapt in those cases?  -->

### Growth
<!-- What was your skillset before Hacktoberfest 2023 and how did it improve? Have your learning or career goals changed since working on these new projects? -->
🌟 토토사이트추천! Pong Bet - 다양한 혜택과 다채로운 게임으로 여러분을 초대합니다! 🎉
Published: 2023-11-15 16:21:57


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t4kkrt31acd50pux85ng.png)
🎁 입플 이벤트 진행 중!

✨ 신규가입시 첫충건 40%, 매충전 15% 이벤트로 여러분을 환영합니다!
🌈 다채로운 이벤트로 더 즐겁게 즐기세요!

🕒 투타임 이벤트: 특정 시간대에 배팅하면 더 큰 혜택이 여러분을 기다립니다!
🔄 리베이트 이벤트: 손실금액의 일부를 현금 또는 보너스로 환급받을 수 있는 리베이트 이벤트가 진행 중입니다!
🍽️ 두끼 이벤트: 배팅이 맛있게! 특별 보너스로 게임을 더욱 풍성하게 즐기세요!
🎯 다양한 배팅종목으로 즐거운 시간을 보내세요!

🏀 스포츠 및 라이브스포츠: 현장감 넘치는 스포츠와 라이브스포츠로 즐거운 시간을 보장합니다.
🎰 카지노 및 슬롯머신: 10가지 이상의 다양한 카지노 게임과 2000가지 이상의 슬롯머신이 여러분을 기다립니다.
🎲 미니게임, 토큰게임, 지뢰찾기: 다양한 미니게임과 독특한 토큰게임으로 여러분의 선택을 기다립니다!
🌐 찾아가기: pong-aa.com
🆔 가입코드: A T

🌟 토토사이트추천 Pong Bet으로 특별한 혜택과 다채로운 게임을 경험하세요! 여러분의 행운이 가득할 것입니다. 지금 바로 참여해보세요! 🚀



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pmxvfp2d8g25wooy95qw.jpg)
Shipping Faster with Hackerplates
Tags: webdev, development, tools, saas
Published: 2023-11-15 11:05:39

_This is the first post in the series, ‘Shipping Faster with Hackerplates’. Today we’re going over our goals when developing Hackerplates and why a good boilerplate is an essential tool for modern web developers._ Checkout [Hackerplates](https://hackerplates.com).

## What are Hackerplates?

**Hackerplates is a set of templates designed to allow web developers to hack a web application together quickly and reliably.**

> The inspiration behind Hackerplates comes from Pieter Levels’ MAKE book and our need to develop a reliable solution we can return to for all our products.
> 

Unlike Pieter's reliance on PHP, we at Hackerplates have tailored our platform for those immersed in the JavaScript/TypeScript ecosystem. Although this space is ever-changing, with new tools emerging regularly, we, like Pieter, believe in sticking with the tools that you feel most adept with.

## Why Speed Matters

In today’s fast-paced tech world, where user expectations are high and the competition is fierce, being able to ship products fast is a significant advantage. Hackerplates enhances your ability to iterate rapidly without sacrificing the quality of your code.

## **One Core, to Rule Them All**

Hackerplates is more than a single template; it's a versatile toolkit developed with a unified core architecture, ensuring that no matter what platform you are developing for, you can do so without having to learn a new skill set.

### Core Architecture Highlights

- **TypeScript for Less Bugs**: We embrace TypeScript for the added reliability it brings. Speed isn't only about pushing code out faster; it's also about the speed of code maintenance and bug resolutions. TypeScript significantly reduces these overheads.
- **Next.js for Framework Consistency**: With a plethora of JavaScript frameworks to choose from, our unwavering pick is Next.js. Our commitment over the last three years has proven its worth, and we encourage you to do the same. If you have different preferences, such as Vue or NestJS, Hackerplates remains adaptable to your needs.
- **Tailwind CSS for Style and Speed**: We settled on Tailwind CSS for two main reasons: efficiency and consistency. It accelerates the process of writing CSS and experimenting with styles, and it allows us to maintain a cohesive look without the overhead of developing a full design system.
- **Future-Proof Goodies**: Our package includes more features that we'll elaborate on in the next chapters.

# **Looking Ahead**

As we continue to enhance Hackerplates, we listen to your feedback and anticipate integrating more features that cater to evolving web development trends. Stay tuned for the next post in this series, where we will delve into specific use cases and the additional tools bundled with Hackerplates.
Uninterrupted Processes in Linux: disown and nohup
Tags: tutorial, linux, beginners, bash
Published: 2023-11-15 16:14:53

### The gist of it:

Using `&` causes the program to run in the background, so you'll get a new shell prompt instead of blocking the current shell until the program ends. E.g. sending `sleep 1000` in the background:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pli6hm7q4ii7wmgxivfi.png)


### Keep the process running:

When the controlling terminal is closed the `HUP` signal is sent to the process.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eh82cq4f2fe8x27jvp92.png)
 
Now if you would like to keep the process running even if you log out of the system or close the terminal, `nohup` and `disown` might be handy. `nohup` and `disown` are largely unrelated; they suppress `SIGHUP` (hangup) signals so the program isn't automatically killed when the controlling terminal is closed.

`nohup` - run a command immune to hangups
`disown`-  remove a job from the table of active jobs for the current shell. It is useful when you want to end a background process without killing it.

### Conclusions

Summarizing all of the above, it will look something like this:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9nfjnymw5at6mrf3d2sl.png)

You can use this mechanism (`nohup`, `disown`) to run scripts or long-running processes, and if you want to check what is the output of your process you can `tail -f ~/nohup.out`
Engage with Our Expert Developers & Designers Today
Tags: developers, designers, hiredevelopers, expertdeveloper
Published: 2023-11-15 15:56:06

Whether you're in search of [expert app developers](https://www.technbrains.com/services/hire-developer/) or skilled designers, **TechnBrains** offers tailored solutions to meet your specific requirements. With a track record of connecting talented technical resources with businesses and startups, we facilitate growth by aligning skills effectively. Whether it's the best software developer, expert mobile app developers, or professional web developers, we're here to assist you in finding the perfect fit for your needs.
[프로그래머스] JadenCase 문자열 만들기 (Lv.2)
Published: 2023-11-15 15:53:49

## 문제 주소

[JadenCase 문자열 만들기](https://school.programmers.co.kr/learn/courses/30/lessons/12951)


---

## 문제에 대한 첫인상

이걸 풀 때 대략 정답률이 78%였다. 그래서 쉽게 접근해본 거 같다.

문제가 원하는 것은 간단하게 첫 문자가 대문자로 되도록 바꾸게 하는 것이다.

---



## 첫번째 풀이

그냥 단순하게 띄어쓰기를 먼저 구해보기로 했다.


```python
def solution(s):
    l = []
    for i in range(len(s)):
        if i == 0:
            l.append(i)
        elif s[i] == " ":
            l.append(i)
    print(l)
```



근데 문제를 잘 읽어보니 다음과 같은 조건이 있었다.



```markdown
- s는 알파벳과 숫자, 공백문자(" ")로 이루어져 있습니다.
  - 숫자는 단어의 첫 문자로만 나옵니다.
  - 숫자로만 이루어진 단어는 없습니다.
  - 공백문자가 연속해서 나올 수 있습니다.
```



공백문자가 연속해서 나오는 것을 감안한다면 다시 짜야될 것 같다. 

그럼 아예 띄어쓰기를 검사하지 말고 앞에 띄어쓰기 혹은 0번째인 문자 그러면서 영소문자인 문자를 검사하는 것이 좋을 것 같다.



```python
def solution(s):
    l = []
    for i in range(len(s)):
        if i != 0 and s[i - 1] != ' ':
            continue
        if s[i] >= 'a' and s[i] <= 'z':
            l.append(i)
    print(l)
```



그럼 그 문자들을 대문자로 바꿔주면 끝!



```python
def solution(s):
    l = []
    for i in range(len(s)):
        if i != 0 and s[i - 1] != ' ':
            continue
        if s[i] >= 'a' and s[i] <= 'z':
            l.append(i)
    temp = list(s)
    
    for i in l:
        temp[i] = temp[i].upper()
    return "".join(temp)

```



근데 틀렸다고 나왔다.

보니까 대문자도 소문자로 바꿔야한다고 한다. 🤣

그래서 그냥 전체를 소문자로 바꿨다.

그리고 그냥 처음부터 리스트로 바꿔서 풀었다.


---
{% spoiler 답 %}
```python
def solution(s):
    temp = list(s.lower())
    for i in range(len(temp)):
        if i != 0 and temp[i - 1] != ' ':
            continue
        if temp[i] >= 'a' and temp[i] <= 'z':
            temp[i] = temp[i].upper()
    return "".join(temp)
```
![정답결과1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vl9x8m4hn7t66puivk8x.png)
{% endspoiler %}

---


## 하지만 아름답지 않아

하지만 풀이가 아름답지 않았다.

그래서 두번째 풀이로 람다식으로 한 방 풀이를 하기로 했다.

알고리즘을 정리하면 다음과 같았다.


```markdown
1. 소문자로 바꾼다.
2. 맨 첫글자인지 아니면 띄어쓰기가 있는 지 검사한다.
3. 소문자를 대문자로
```




근데 2번이 까다롭길래 그냥 앞에 띄어쓰기를 하나 붙이 문제를 풀었다. 😎

그 다음은 `map` 과 함께 문자를 만들어가도록 했다.

숫자의 경우는 `upper()`를 해도 아무일도 일어나지 않아서 검사하지 않았다. 😏


```python
solution = lambda s: (x:=f" {s.lower()}", "".join(map(lambda t:t, range(1,len(x)))))
```


이제 `lambda t:t` 자리에 코드를 작성하면 된다.

`x := ` 이 문법은 할당 **표현식**으로 할당 **선언**과는 다른 문법이다.

할당 표현식을 쓰면 튜플 안에서 할당한 값을 뒤의 튜플에서 쓸 수 있다.

따라서 한 줄 코드에서 매우 중요한 문법이다. 🤔 

그리고 구조가 튜플이기에 마지막에는 `[1]`을 써서 2번째 값을 리턴해야 한다.

---

{% spoiler 답 %}
```python
solution = lambda s: (x:=f" {s.lower()}", "".join(map(lambda t:x[t].upper() if x[t - 1] == " " else x[t], range(1,len(x)))))[1]
```
![정답결과2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zmoownprmysofyf7frc3.png)
{% endspoiler %}

---


## 마지막은 정규표현식

정규표현식은 파이썬에서 모듈을 `import` 해야 돼서 아름답지 않다. 😞

그래도 써본다면 다음과 같이 쓸 수 있을 것 같다.

> 앞글자가 처음 시작이거나 공백인 소문자

위의 조건대로 찾아서 대문자로 바꾸도록 하면 간단하게 풀릴 것 같다.


---

{% spoiler 답 %}
```python
import re
def solution(s):
    p = r"(^|\s)[a-z]"
    subfun = lambda t:t.group(0).upper()
    return re.sub(p, subfun, s.lower())
```
![정답결과3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ydis2xss4zw89gfaqloa.png)
{% endspoiler %}

---