DEV Community

Cover image for Menyelesaikan soal "Plus Minus" di HackerRank
Aris アリス
Aris アリス

Posted on

5 2

Menyelesaikan soal "Plus Minus" di HackerRank

Soal 1Soal 2
Pada soal di atas kita diminta untuk menghitung jumlah bilangan positif, negatif, dan nol dalam sebuah array. Kali ini saya akan membagikan cara saya menyelesaikan soal tersebut menggunakan bahasa pemrograman javascript. Berikut kode pemrogramannya:

function plusMinus(arr) {
    const counts = [
        arr.filter(el => el > 0).length,
        arr.filter(el => el < 0).length,
        arr.filter(el => el === 0).length
    ];

    for (const count of counts) {
        const ratio = (count / arr.length).toFixed(6);
        console.log(ratio);
    };
}
Enter fullscreen mode Exit fullscreen mode

Pada kode di atas saya membuat variabel counts yang berisi jumlah elemen dari bilangan positif, negatif, dan nol yang terdapat pada array arr. Di bawahnya saya melakukan perulangan dari variabel counts. Di dalam perulangan saya menghitung rasio dari masing-masing bilangan (positif/negatif/nol) dari jumlah elemen pada array arr. Rasio tersebut kemudian saya bulatkan maksimal 6 angka di belakang koma menggunakan method toFixed(). Terakhir, saya tampilkan hasilnya pada konsol.

Top comments (0)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️