fabiochiu/medium-articles huggingface dataset:
Solving Maximum Subarray
By: Bryam Vicente
Tags: Leetcode, Algorithms, Arrays, JavaScript

Intro:

This blog will be about solving the LeetCode problem #53. Maximum Subarray. Note that this problem will be solved in JavaScript!

The question is asking us to find the elements that are contiguous that add up to the max sum and then return the max sum. The examples do a great job at explaining what the input and output should be and why. There are many ways to solve this problem, I was able to solve this problem with a time complexity of O(n). Please feel free to reach out or leave a comment on this blog if there are better solutions for this problem!

Because we have to return the largest sum from a contiguous subarray, I created a variable that represents the large sum and set that equal to the first element of the nums array. This is what my code looks like at this moment:

The next step is to iterate over the nums array to check for each element. For this step, I will be using a for loop statement!

When creating a for loop statement, the variable i would be set to zero, but in this case we will start from one. Starting from one means that the iteration would start on the first index not the zeroth index. If we have an array [1,2,3,4] , that means that the for loop would start at 2 instead of 1.

Now that the logic for the for loop is written, we need to think about what’s supposed to go on inside of this for loop. Based on the prompt and the examples, we need to think about how we’re going to get the largest sum when adding up the elements inside the array. I believe we can get that number by using the current number being iterated on the nums array and the variable that I created largeSum . The current number ( nums[i] ) being iterated inside the nums array should be equal to the maximum number between nums[i] and the sum of nums[i] plus the previous number. I know that sounded complex, but here’s how the code should look like at the moment:

Let’s say we have an array [1,2,-5,4] , the code on line 6 is stating that nums[i] should be equal to the largest number between 2 and 2 + 1. The largest number between the two is three! On the next loop cycle, the next number is now -5 and nums[i] will now be the max number between -5 and -5 + 3 which is -2.

The last step is changing the value of largeSum and then return it after the for loop ends. largestSum needs to be able to keep track of the highest number which is why I decided to use Math.max() . Here’s the solution of the problem and the expected outputs for the LeetCode examples:

It’s always best practice to use different test cases to ensure that the solution is working properly! For more info on the Math library, and for loop statements, make sure to check out the links below!

Resources:
PowerShell, checking for multiple files
By: John Case
Tags: Arrays, Powershell

In PowerShell, checking for a file is as simple as using the Test-Path command with the file path. Followed by an if statement, this is a great tool to act when a file exists. If the result of Test-Path is stored in a variable, this can be used to evaluate the result and proceed, as necessary.

But what if multiple files are needed before acting? The Test-Path command can accept an array with each path being separated by commas. While checking the result for a single file is a simple True/False statement, checking the result of a Test-Path array is more difficult. When the result of a Test-Path array is stored in a variable, it stores the result of each file path check. All the file paths may evaluate to True, False, or a combination of both. This means, when checking the result, it is necessary to accept one desired outcome and discard all others.

For example, to accept only an outcome where all file paths evaluate to True, the -notcontains $false modifier can be used on Test-Path. This will ignore any outcomes that are false meaning the whole Test-Path statement will only be True when all file paths in the array are True. The same logic can be used in reverse if the desired outcome is for all of the paths to be False.

Here is an example of how to use an array with Test-Path. In this example the $result variable will only be true if all paths in the array exist.

$filecheck = “File Path 1”, “File Path 2”, “File Path 3”

$result = ($filecheck | Test-Path) -notcontains $false
Reduce: The Powerful and Mighty
By: Suhail Ahmed
Tags: ES6, Programming, Arrays, JavaScript

“Every developer who specializes in any programming language will tell you there’s a powerful tool the language provides that they rarely use and wish they knew more about. For me, it’s Array.prototype.reduce .”

What is Reduce ?

The reduce() method is used to apply a function to each element in the array to reduce the array to a single value.

The syntax looks like this

const reduced=arr.reduce((acc,val,ind,srcArr)

reduce() takes a callback with 4 arguments

Accumaltor(acc) : the accumulator accumulates all of the callbacks returned values.

2. currentValue(val) : The current element being processed in the array.

3. index(idx): The index of the current element being processed in the array. Starts from index 0 if an initialValue is provided. Otherwise, starts from index 1.

4. sourceArray(srcArr) The array on which reduce() is being called.

Example For Reduce :

You can think of reduce() as a for loop, that is specifically for using the values of an array to create something new. Consider the following code:

const arr=[1,2,3,4,5] const reduced=arr.reduce((acc,val)=>acc+val); ///15 //Array has been reduced to a single value

Passing initial value to reduce

we can pass initial value to reduce for Example:

const arr=[1,2,3,4,5] const reduced=arr.reduce((acc,val)=>acc+val,100); ///115 //First value in accumulator is 100

Pretty cool huh? With just one line of code we can take the number 100 and add it to the sum of an entire array!

Reduce can return objects

Methods like forEach and map were created to avoid side effects, and reduce is no exception. In this case, however, reduce can return an Object other than an Array

let’s take an example for Counting Array Elements and returning it in Object

var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];



var countedNames = names.reduce(function (allNames, name) {

if (name in allNames) {

allNames[name]++;

}

else {

allNames[name] = 1;

}

return allNames;

}, {} ); // counted Names is:

// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

Note that the {} , which is the last argument to reduce , is starting/default object to be returned. If there were no items in the array, {} would be returned. Also appreciate that an array method returns an object literal and not a modified array!

Awesome!

let’s see one more example where we group an array of people’s info with age

with Quokka.js plugin

Reduce makes our life easier It’s crazy that I’ve not used reduce more.

Learn More :

Thanks
[Swift] Value Type의 메모리 주소
Tags: Swift, Value Type, Copy On Write, Memory Address, Array

[Swift] Value Type의 메모리 주소

Value Type은 cow를 한다면서 왜 Array만 동일 instance에 대해 같은 주소를 반환할까요? naljin Mar 13·6 min read

들어가며

흠.. 제목이 딱 맘에 들진 않네유.. 부제에 집중해주세요! (이걸 제목으로 쓰기엔 너무 길었어요 흑흑)

튼 오늘은

Value Type은 cow를 한다면서 왜 Array만 동일 instance에 대해 같은 주소를 반환할까?

에 대한 이야기입니다. 무슨 말이냐고요? 일단 스크롤을 내려봅시다 ㅎㅎ 그럼 고고링~!

의문의 시작

얼마전 Swift의 Type에 대해 공부하다가 OptimizationTips 문서에서 기본 Value Type은 copy on write 최적화를 사용한다는 것을 보았습니다.

All standard library containers in Swift are value types that use COW (copy-on-write) to perform copies instead of explicit copies. In many cases this allows the compiler to elide unnecessary copies by retaining the container instead of performing a deep copy.

대충 Swift에서 Value Type은 할당될때 바로 copy를 하는게 아니라 write가 될 때 찐 copy 를 한다는 얘기임다 ㅇㅇ (copy on write)

직접 확인해보기 위해 변수 a 에 [1,2,3] 을 할당하고, 다시 b 라는 변수에 a 를 할당했습니다. 그리고 각각의 메모리 주소를 출력해봤어요!

func address(of object: UnsafeRawPointer) -> String{

let address = Int(bitPattern: object)

return String(format: "%p", address)

}

​

//same memory address

var a = [1, 2, 3]

var b = a

address(of: &a) //0x600002b74c20

address(of: &b) //0x600002b74c20

​

b.append(2)

address(of: &a) //0x600002b74c20

address(of: &b) //0x600001d509d0

결과는 a 와 b 모두 같은 메모리 주소를 출력합니다!! 홀뤼몰뤼~~ 물론 b.append(4) 와 같은 변경을 주면 바로 b 의 메모리 주소는 바뀌지만요 ㅎㅎ

뚜둔 여기서 그치지 않고 Dictionary , Set , String 등에서도 실험을 해보자구요~~

//String

var c = "1b"

var d = c

address(of: &c) //0x10eaec670

address(of: &d) //0x10eaec680

​

//Dictionary

var e = ["hi" : 3, "bye" : 3]

var f = e

address(of: &e) //0x10eaec690

address(of: &f) //0x10eaec698

​

//Set

var g: Set = [1, 2]

var h = g

address(of: &g) //0x10eaec6a0

address(of: &h) //0x10eaec6a8

오잉또잉…..???????? 보이시나요????? 아까와는 다르게 같은 instance 일지라도, 각각 다른 주소를 출력하는게 아니겠어요!?!?!?!

이.. 이런 벱은.. 없는겨..

그래서 이유가 뭐라고요??

흠 침착하고 Stack Over Flow에 파파고의 도움을 받아 질문을 올렸습니다.

제 애완동물입니다

그랬더니 이게 도움이 되겄니?? 하면서 How to prove “copy-on-write” on String type in Swift를 링크로 주더라구요.

따봉 스택오버플로우야 고마워!

역시 세상엔 나와 비슷한 사람이 있었군 ㅎㅎ!

답변을 찬찬히 해석해보자면

func address(of object: UnsafeRawPointer) -> String

이 함수가 Array 에 대해서는 같은 값을, String 에 대해서는 다른 값을 return 하는 이유는 아래와 같다고 합니다.

unsafe pointer를 인자로 받는 함수에 array 를 전달 하는 것은 첫번째 어레이 인자의 주소를 전달 하는 것입니다. 따라서 array들이 같은 저장공간을 사용한다면 동일한 값이 나오게 됩니다.

하는 것은 하는 것입니다. 따라서 array들이 같은 저장공간을 사용한다면 동일한 값이 나오게 됩니다. unsafe pointer를 인자로 받는 함수에 string 을 전달하는 것은 string을 나타내는 임시 UTF-8 의 pointer를 전달하는 것입니다. 따라서 이 주소는 같은 string일지라도 매 호출마다 달라질 수 있습니다.

😮😮😮😮😮😮😮!!!!! 사실 설명도 완전히 이해하지 못했지만(임시 UTF-8의 포인터라뇨 선생님,,,) 어쨌든 포인트는 type 에 따라 어떤 주소를 전달하는지(?)에 대한 메커니즘이 다른가 보군요 🤔 아니 족굼 어이 없는 부분…

얼렁뚱땅 마무리

답변에서는 String 만 설명해줬지만, 다른 타입들도 비슷하게 동작하기 때문에 다른 주소가 나오는거였겠죠?? ㅎㅎ 일단 흐린 눈하고 이 정도로 넘어가도록 하겄습니당. 아니라면 알려주세요!
The Cost of Array.Sort() in JavaScript
By: Shubham Gupta
Tags: Quicksort, JavaScript, Arrays, Chrome, Sorting Javascript Engine

Sorting Techniques

The sort() is an inbuilt method provided in Javascript for arrays. We simply use it quite often but we often did not worry about the cost and the complexity of this and what is going behind the curtains.

The default implementation of sort() function is in increasing order like:-

Array.sort((a, b) => a - b);// Increasing Order

We can also change the order in decreasing order as well:-

Array.sort((a, b) => b- a);// Decreasing Order

In V8 chrome the logic behind the sort() is hybrid mixture of Quick Sort and Insertion Sort.

What really happens behind the curtains is

Sort(arr){

if(arr.length<10){ // if array elements is less than 10 than insertion sort

Insertion Sort()

}

else{ // in this case quick sort happens

Quick Sort()

}

}

Incase of sorting of mixture of numbers and characters first the numbers are sorted and then the characters are being sorted out.

let arr = [1,3,"a","d",2,"z",5,4]

arr.sort() results

arr=[1,2,3,4,5,"a","d","z"]

This is an infamous trick in Javascript up the sleeve.😉

INSERTION SORT

Worst Case Time Complexity [ Big-O ]: O(n2)

Best Case Time Complexity [Big-omega]: O(n)

Average Time Complexity [Big-theta]: O(n2)

QUICK SORT

Worst Case Time Complexity [ Big-O ]: O(n2)

Best Case Time Complexity [Big-omega]: O(log n)

Average Time Complexity [Big-theta]: O(n log n)

Space Complexity: O(log n)

In Mozilla Firefox the logic behind the sort() is simple Merge Sort Algorithm

MERGE SORT

Worst Case Time Complexity [ Big-O ]: O(n log n)

Best Case Time Complexity [Big-omega]: O(n log n)

Average Time Complexity [Big-theta]: O(n log n)

Space Complexity: O(n)
Weird Things I Encountered In My Development Journey Explained
By: Shan Shaji
Tags: Ruby, Web Development, Arrays, Ruby on Rails, Hash

Weird Things I Encountered In My Development Journey Explained

This might seem repetitive for those who read Part 1 in this series because I am going to continue to focus on the same concepts and the dangers behind them if we are not careful.

So, my friend and I were trying to build a grocery store data structure to get used to Ruby’s hash. I explained to him that I want a key/value pair data structure that returns an array when I try to access it. He enthusiastically did so by creating a hash that returns an array as the default argument. So even if I access something which is not available, it will return an array [] instead of nil . I was really happy about this because the code wouldn’t break even if I decided to make some profit selling stationery items in my grocery store.

grocery_store = Hash.new([])

grocery_store[:fruits]

=> []

This amazement faded into amusement when I tried adding fruits by doing grocery_store[:fruits] << “Apples” and looked at my grocery_store hash.

grocery_store[:fruits] << "Apples"

=> ["Apples"]

grocery_store

=> {}

WTF! Where did my apples go dude? Well, I pushed it into my array and it worked because I saw it return an array with apples [“Apples”] , but sadly, the array was not assigned to the key. I thought I will add one more fruit to my grocery store, this time some oranges. I learned my mistake last time - so I thought I will assign it this time instead. But I didn’t want to give up on my “Apples” just yet. So I did:

grocery_store[:fruits] = grocery_store[:fruits] << "Oranges"

grocery_store

=> {:fruits=>["Apple", "Oranges"]}

Well to my surprise, it worked! Or so I thought until I wanted to add vegetables to my grocery store. Since at this point I am practically a changed man, I didn't want to make my past mistake by not assigning the value to the hash. I used the short-hand version of the shovel operator like how we would add to the same variable( a += 2 ).

grocery_store[:vegetable] <<= "Onions"

grocery_store

=> {:fruits=>["Apple", "Oranges", "Onions"], :vegetable=>["Apple", "Oranges", "Onions"]}

Yep, the same array. When we created the hash with a default argument array, the array was created only once in the memory, and when we used shovel operator (<<) we were mutating the same array. We can confirm this by looking at the object_id of the arrays.

grocery_store[:vegetable].object_id

=> 200

grocery_store[:fruits].object_id

=> 200

One quick workaround for this is to pass a block when passing the default arguments. This will return a new array every time. We can confirm it by checking their object_id.

grocery_store = Hash.new{[]}

grocery_store[:fruits].object_id

=> 220

grocery_store[:vegetable].object_id

=> 240

In conclusion, when defining a hash with default arguments, make sure that you pass the default argument as a block so as not to manipulate the same object.
Demystifying Linked List
By: Juan Samuel
Tags: Programming, Computer Science, Arrays, Linked Lists, Data Structures

Structure of Linked List

A linked list is a data structure that is based on dynamic memory allocation. Basically, Linked List is made of nodes and links. We can create a simple structure that consists of a container to store the value and the pointer to the next node.

In the ListNode structure, the int item is declared to store the value in the node while struct _listnode *next is declared to store the address of the next node. If it is the last node, then the next will point to NULL.

Nice! Now, we can track the second node by the first node, as well as the third node by the second node. But how do we keep track of the first node? Without the address of the first node, the second and third nodes won’t be accessible. Therefore, we will introduce the head pointer. The head pointer is not a node, instead, it is a pointer that stores the address of the first green block which is the first node.

Linked List Example

We have finally defined the structure of Linked List and how it works. Now, let’s start the coding part. I will guide you through a simple code.

Here is the result of the Linked List after executing the code.

As you can see from the code, Linked List relies heavily on the malloc() function to allocate some memory for new nodes dynamically. The reason why we need to use the temporary variable is that we don’t want to change the address stored in the head pointer. Subsequently, after this code executes, the head pointer will still point to the first node whereas the temporary pointer will point to the last node.
SOLUTIONS TO CODERBYTE CHALLENGES
By: Harriet Obwogo
Tags: Algorithms, Arrays, Data Structures

I got a chance to interview for the Microsoft LEAP apprenticeship program and I’m thrilled to say that it was a success. The past two months have been involving and the growth is real and immense. one thing I learned is that as a software engineer problem-solving skills are a major requirement. If you don’t have that then developing products that have high productivity isn’t really going to happen.

As a software engineer, your work is to solve problems and sometimes solving problems doesn’t necessarily mean writing code all the time, sometimes it might involve getting rid of code. “To create something original you must first identify the problem, break it down, and then develop different ways to approach and learn from it. Problem-solving is an art” and as a developer, there’s no shortcut around that.

I will be publishing some algorithmic challenges from coderbyte and their solutions to help anyone who comes across them and is stuck.

I’ll be using C# and for a start, I’ll do some easy challenges. the trick is to just wrap your head around the problem, understand the logic, write it down on paper and test it before writing the actual code

1.Consecutive

Have the function Consecutive(arr) take the array of integers stored in arr and return the minimum number of integers needed to make the contents of arr consecutive from the lowest number to the highest number. For example: If arr contains [4, 8, 6] then the output should be 2 because two numbers need to be added to the array (5 and 7) to make it a consecutive array of numbers from 4 to 8. Negative numbers may be entered as parameters and no array will have less than 2 elements.

check for the edge cases i.e if the array is within the limits provided Loop through the array, find the maximum and minimum elements in the array. This will give you a range within which your numbers lie. Find and return the difference between the Min and Max and the array Length.

2.LargestFour

Have the function LargestFour(arr) take the array of integers stored in arr, and find the four largest elements and return their sum. For example: if arr is [4, 5, -2, 3, 1, 2, 6, 6] then the four largest elements in this array are 6, 6, 4, and 5 and the total sum of these numbers is 21, so your program should return 21. If there are less than four numbers in the array your program should return the sum of all the numbers in the array.

One way to go about this is to sort the array in ascending order and extract the subarray starting from the fourth index, find the sum and return the sum.

1. First, check for edge cases, return 0 or -1 if the array is empty. otherwise, if it has less than four elements, find their sum and return it.

2. sort the array

3.loop through the array

4. take the subarray of the last four elements and store them in an array

5.find their sum and return.



Time Complexity O(n), space complexity O(n)

I’ll leave it at that for today. Comment down below if you want more of this and how better we can do it.
Kotlin: Arrays
By: Mj Manaog
Tags: Arrays, Kotlin, Beginners Guide

Arrays in Kotlin are represented by the Array class that has get and set functions, and size property, along with a few other useful member functions.

Simple array declaration

Line 3 — if you wish to simply declare an array of integer

Line 4 — if you wanted to specify the type of the array

Line 5 — array in Kotlin can handle Any value

value Line 6 — we just get the index 1 of the randomSurname array

of the array Line 11 — to simply iterate random array.

Primitive Type Arrays

Kotlin also has specialized classes to represent arrays of primitive types

Line 3 — declaring an “empty” but not totally empty integer array with the size of 5

Primitive type array classes have no inheritance relation to the Array class, but they still have the same set of methods and properties. DoubleArray , ShortArray , LongArray , etc. is also available.

Array Constructor

Line 2 — we’ve declared an empty array and reassign values at Line 3

Line 5 — Using the Array constructor, we can pass a lambda expression to initialize the array evenNumbers . What this declaration do is we have an array with a size of 20, inside the lambda expression, we’re getting the index ( it )of the array and for each of its index, we’re multiplying it by 2. So the output will be: 0, 2, 4, 6 … 38

What if we want to create an Array that consists of nulls?
What are three dots (…) in Javascript
By: Muhammad Hasan
Tags: Arrays, JavaScript, React, Three Dots

three dots in javascript

The spread syntax is a new addition to the set of operators in JavaScript ES6. It takes in an iterable (e.g an array) and expands it into individual elements.

The spread syntax is commonly used to make shallow copies of JS objects. Using this operator makes the code concise and enhances its readability.

Syntax

The spread syntax is denoted by three dots, … .

let array = [...value]

Examples

Since the array data structure is widely used, it will be considered in all the subsequent examples.

1. Copying an array

The array2 has the elements of array1 copied into it. Any changes made to array1 will not be reflected in array2 and vice versa.

If the simple assignment operator had been used then array2 would have been assigned a reference to array1 and the changes made in one array would reflect in the other array which in most cases is undesirable.

let array1 = ['h', 'e', 'l', 'l', 'o'];

let array2 = [...array1];

console.log(array2); ['h', 'e', 'l', 'l', 'o'] // output

2. Inserting the elements of one array into another

It can be seen that the spread syntax can be used to append one array after any element of the second array. In other words, there is no limitation that desserts can only be appended at the beginning of the end of the desserts1 array.

let desserts = ['cake', 'cookie', 'donut'];

let desserts1 = ['icecream', 'flan', 'frozen yoghurt', ...desserts];

console.log(desserts); //Appending baked_desserts after flan

let desserts2 = ['icecream', 'flan', ...desserts, 'frozen yoghurt'];

console.log(desserts2); // output

[ 'cake', 'cookie', 'donut' ]

[ 'icecream', 'flan', 'cake', 'cookie', 'donut', 'frozen yoghurt' ]

3. Array to arguments

function multiply(number1, number2, number3) {

console.log(number1 * number2 * number3);

}

let numbers = [1,2,3];

multiply(...numbers);

Instead of having to pass each element like numbers[0] , numbers[1] and so on, the spread syntax allows array elements to be passed in as individual arguments.

//Passing elements of the array as arguments to the Math Object

let numbers = [1,2,300,-1,0,-100];

console.log(Math.min(...numbers));
NumPy Basics Cheat Sheet (2021), Python for Data Science
By: Christopher Zita
Tags: Machine Learning, Arrays, Numpy, Python, Data Science

The NumPy library is the core library for scientific computation in Python. It provides a high-performance multidimensional array object and tools for working with arrays.

Check out the different sections below to learn the various array functions and tools NumPy offers.

Creating Arrays

A NumPy array is a grid of values, all of the same type. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension.

In this section, you’ll learn how to create these various types of arrays.

1-dimensional array

>>> a = np.array([1,2,3])

array([1, 2, 3])

2-dimensional array

>>> b = np.array([(1.5,2,3),(4,5,6)], dtype = float)

array([[1.5, 2. , 3. ],

[4. , 5. , 6. ]])

3-dimensional array

>>> c = np.array([[(1.5,2,3),(4,5,6)],[(3,2,1),(4,5,6)]], dtype = float)

Array of zeros

>>> np.zeros((3,4))

array([[0., 0., 0., 0.],

[0., 0., 0., 0.],

[0., 0., 0., 0.]])

Array of ones

>>> np.ones((3,4))

array([[1., 1., 1., 1.],

[1., 1., 1., 1.],

[1., 1., 1., 1.]])

Array of evenly spaced values (step value)

>>> np.arange(10,25,5)

array([10, 15, 20])

Array of evenly spaced values (number of samples)

>>> np.linspace(0,2,9)

array([0.0, 0.25, 0.5 , 0.75, 1.0, 1.25, 1.5 , 1.75, 2.0])

2x2 identity matrix

>>> np.eye(2)

array([[1., 0.],

[0., 1.]])

Array with random values
Firestore Arrays, Lists and Sub-collections
By: Deepak Prasad
Tags: Android, Java, Cloud Firestore, Arrays, Kotlin

Firestore doesn't support storing sub-collections into Objects as List<Object> nor does it support operations on sub-collections to filter current documents.

Sample Firestore Database

Consider the example in the picture above. It has Orders as collections and each Order needs to have Quotations (from many retailers).

Suppose we need to filter if a certain Retailer (say retailer_one) has submitted a quotation or not. Firestore doesn’t allow to perform queries on subcollections to filter out parent documents.

Also the “quotations” subcollections are not automatically stored in a ArrayList.

Filter Parent Collection using Sub — collections

To perform this operation, we need a to perform some simple hacks and reconstruct our Data.

Consider this scenario : We want to filter if retailerJohn has added a quotation or not to the current order.

We can add a field “hasJohnQuoted” and set it to true whenever John quotes this order.

Also we can create a Firestore Arrays( demonstrated below ) and append to the array all the retailers who have quoted the order.

Firestore Arrays and Maps

To store a Sub-collection, we can use Firestore Arrays and store Maps in them. Consider the following example.

A sample Sub-collection in Array with Maps as elements

Firestore has two Operations on Arrays — arrayUnion and arrayRemove. Below is an example of arrayUnion where a new quotations is created and added to the existing quotations Array.

Here is and example of arrayRemove where an existing quotation is removed from the quotations Array.

I hope this tutorial helps you in some way or other. Feel free to give some feedback.

Thanks for reading.
Ruby Arrays For Beginners: three useful array methods
By: Ifeoluwa Akinremi Wade
Tags: Software Development, Ruby, Programming, Arrays, Software Engineering

Photo by Joshua Fuller on Unsplash

What are Ruby arrays, anyway?

Ruby arrays are basically lists of strings, integers, hash, or even other arrays. These items you find in arrays are called objects, or elements. The elements would also be enclosed inside two square brackets ([ ]). Arrays can be manipulated with array methods, which allow us to create, delete, inspect, or change elements in an array. This following blog will delve into three useful array methods.

is_a?

is_a? is an array method you would use to retain certain elements of a specific data type within an array. ie:

If I wanted to retain only the integers (whole number) of an array, I would utilize is_a? in this way:

In the image above, I am declaring a variable called numbers and initializing it with an array of elements consisting of strings and integers. I’m iterating through that array with the method keep_if (which I will discuss later in the blog). What this code is stating is: “Go through every element (num) in the numbers array and keep that element if the element is an Integer”. What will be returned is an array of elements that are of the Integer data type. The reverse result would happen if I was to inquire to keep an element if it is a String (characters enclosed with quotes, “ ”). What would then be returned is an array of strings.

is_a? can also be used as a boolean expression, an expression that evaluates to either true or false:

The above reads as: “23 Is a Float (decimal)”. Which then returns false because 23 is an Integer, a whole number.

delete_if

delete_if, to simply put it, deletes an element based on a condition. It is literally the opposite of keep_if.

ie:

Above I am declaring the variable thirties_club, and initialized it with an array of Integers. The code is stating: “delete any element if that element is less than 30”. What is returned is an array of integers that are 30 and above.

Just for fun though! How would I write this if 40 was in the same array?

it now states: “delete any element if that element is less than 30 or (||) greater than 39

or:

it can also be written like this: “delete any element if that element is less than 30 or (||) equal (===) to 40

keep_if

Unlike delete_if, keep_if retains — or keeps, an element based on a condition. If I was to use the same code used above, but instead used keep_if, the result would be as follows:

Aboves reads: “keep any element if that element is less than 30 or (||) equal (===) to 40. What is returned is an array that contains integers that are either less than 30 or equal to 40.

In my opinion, arrays are the most fun part of Ruby. Learning all of the array methods available only increases the fun by a thousand.
JavaScript Array Methods: Part 1
By: Kayla Budzeak
Tags: Array Methods, Coding, Junior Developer, JavaScript, Arrays

This week and next I’ll be covering some fundamental array methods within JavaScript! This week will cover: .push(), .unshift(), .pop(), and .shift(). Let’s begin!

It’s important to remember that all of these methods are actually callback functions; some of which require something to be provided to it. These functions have already been defined for you within JavaScript, and so are available for you to call.

I will also try to point out which methods are “destructive”, meaning they alter the original array in place, or “non-destructive”, meaning the original array is left unaltered.

I’ll start with an array, myArray = [1,2,3] and build or destroy on it through these methods.

.push()

This method will add the element that is provided to the end of the array. On its own, it is a “destructive” method.

myArray.push(4)

//myArray === [1,2,3,4]

It can be made into a non-destructive method by using the spread operator!

newArray1 = […myArray, 5]

//newArray1 === [1,2,3,4,5]

//myArray === [1,2,3,4]

.unshift()

This method will add the provided element to the beginning of the array it’s called on; it is also destructive.

myArray.unshift(‘A’)

//myArray === [‘A’,1,2,3,4]

This one can also be turned into a non-destructive method like so:

newArray2 = [‘B’, …myArray]

//newArray2 === [‘B’,’A’,1,2,3,4]

//myArray === [‘A’,1,2,3,4]

.pop()

This method will remove and return the last element in an array destructively; it does not require an element to be provided.

myArray.pop()

//4

//myArray === [‘A’,1,2,3]

.shift()

This method will remove and return the first element in an array destructively; it does not require an element to be provided.

myArray.shift()

//’A’

//myArray === [1,2,3]

Technically both .pop() and .shift() could be made into non-destructive methods, by first creating a copy of our original array, and then calling these methods on the copy. Just be sure to keep in mind any changes made to the original array after the copy is made, will not apply to the copy.

newArray3 = [...myArray]

newArray3.pop()

//newArray3 === [1,2]

//myArray === [1,2,3]

Be sure to tune in next week for .slice(), .splice(), .filter(), and .reverse()!
Search jsonb objects in PostgreSQL Array of objects using Ruby on Rails
By: Gustavo Henrique Smaniotto
Tags: Json, Query, Arrays, Postgres, Rails

At Donamaid we have some problems with to JSONB array in PostgreSQL. We look up for two options, a PostgreSQL Array of jsonb objects or and PostgreSQL jsonb that contains an array of objects.

We select the PostgreSQL Array of jsonb objects because using this strategy, and we could figure out our problem. This approach allows us to use PostgreSQL Array and jsonb methods to query what we need. We follow the PostgreSQL Array functions and this Rails/PostgreSQL tutorial to build our solution.

Our context:

The array stores jsonb objects like:

{ token: "89203q47h928q73craaw", id: "SERVICE_ID"}

{ token: "733asdas8asdf9as", id: "OTHER_SERVICE_ID" }

Our problem:

We receive an webhook from some service. The webhook message has an authorization token. We need to check if some account have this token in their external_credential array

Our solution:

By this way, we can search if some of our accounts have the specific token stored in their external_credentials array.

João Fernandes' founded this solution’.
How to declare array in python
By: Amansingh Javatpoint
Tags: Python, Array, Declare

Arrays are a great way of storing our numeric values into a variable in continuous locations. For declaring an array in C language, we used to specify the size of the array and then specify the elements it will hold.

The difference between an array and a list is that a list can hold multiple values of different data types whereas an array holds multiple values of the same data type.

In this article, we will discuss how we can declare an array in python.

Arrays and matrices have a special significance in the world of scientific calculations, image processing, and computer vision. The pixels of a picture are represented in the form of matrices for a better understanding of operations on the image.

Arrays can be declared in Python by importing the package numpy.

import numpy as np

Using numpy

The following program illustrates a simple way of declaring an array in python.

import numpy as np #importing the package

x=np.array([1,2,3,4]) #array declaration

print(x) #printing the array

print(type(x)) #type of x

print(x.ndim) #dimension of array

INPUT-
Two-dimensional array in c and array types
By: Kamran Abbasi
Tags: 2 Dimensional Array In C, Array In C With Example, Arrays, Two Dimensional Array C, 2d Array C Plus Plus

Two-dimensional array in c and array types

Array in c programming examples:

For understanding the arrays properly, let us consider the following program:

main( )

{

int x ;

x = 5 ;

x = 10 ;

printf ( “

x = %d”, x ) ;

}

No doubt, this program will print the value of x as 10. Why so? Because when a value 10 is assigned to x, the earlier value of x, i.e. 5, is lost. Thus, ordinary variables (the ones which we have used so far) are capable of holding only one value at a time (as in the above example). However, there are situations in which we would want to store more than one value at a time in a single variable.

For example, suppose we wish to arrange the percentage marks obtained by 100 students in ascending order. In such a case we have two options to store these marks in memory:

a) Construct 100 variables to store percentage marks obtained by 100 different students, i.e. each variable containing one student’s marks.

b) Construct one variable (called an array or subscripted variable) capable of storing or holding all the hundred values.

Obviously, the second alternative is better. A simple reason for this is, it would be much easier to handle one variable than handling 100 different variables. Moreover, there is a certain logic that cannot be dealt with, without the use of an array. Now a formal definition of an Array — An array is a collective name given to a group of ‘similar quantities’.

These similar quantities could be percentage marks of 100 students, or salaries of 300 employees, or ages of 50 employees. What is important is that the quantities must be ‘similar’. Each member in the group is referred to by its position in the group. For example, assume the following group of numbers, which represent percentage marks obtained by five students.

complete this article in this link https://protechcoder.com/2021/06/02/two-dimensional-array-in-c-and-array-types/kamranabbasi9145/
JavaScript Arrays: Some(), Every(), and forEach()
By: Kunal Tandon
Tags: Coding, Programming, JavaScript, ES6, Arrays

JavaScript Arrays: Some(), Every(), and forEach()

The Some() Method

The some() method iterates through elements and checks if any value in the array satisfies a condition. The some() method accepts a boolean expression with the following signature:

(element) => boolean

The element is the current element in the array whose value is being checked.

The boolean denotes that the function returns a boolean value.

Consider the following array of integers:

let arr = [1, 2, 3, 4, 5, 6, 7, 8];

We will be using the some() method to check if at least one element is in the array.

arr.some((value)=> { return (value%2 == 0); });

Output:

true

The array contains elements divisible by 2 , so the some() method returned true .

When you use the some() method to find negative numbers:

arr.some((value)=> { return (value < 0); });

The output is:

false

It is false because there are no numbers in the array that are negative.

The some() method stops iterating as soon as the element is found, which satisfies the required boolean expression.

arr.some((value) => {

index++;

console.log(index);

return (value % 2 == 0);

});

Output is:
#2 Daily Problems
By: Arun Pandian M
Tags: Coding, Java, Arrays, Problem Solving, Problems And Solutions

As I already mention in previous post, I have planned to do solve one problem per day.

Problem:

For s = "abacabad" , the output should be

firstNotRepeatingCharacter(s) = 'c' .

, the output should be . There are 2 non-repeating characters in the string: 'c' and 'd' . Return c since it appears in the string first.

non-repeating characters in the string: and . Return since it appears in the string first. For s = "abacabaabacaba" , the output should be

firstNotRepeatingCharacter(s) = '_' .

, the output should be . There are no characters in this string that do not repeat.

Input/Output

[input] string s

A string that contains only lowercase English letters.

Guaranteed constraints:

1 ≤ s.length ≤ 105 .

. The first non-repeating character in s , or '_' if there are no characters that do not repeat.

My Solution:

char firstNotRepeatingCharacter(String s) { HashSet<Character> hS=new HashSet<>(); String tS=s; for (int i=0;i<s.length();i++){ if(!hS.contains(s.charAt(i))) hS.add(s.charAt(i)); else tS= tS.replace(""+s.charAt(i),""); } if (tS.length()>0) return tS.charAt(0); else return '_'; }

Again hi guys, please just see my solution and help me to improve this if you have any suggestion for me
Parsing of JSON into a heterogeneous array
By: Inventi Labs
Tags: Json, Swift, Parsing, Arrays, Decoding

As mobile developers almost on every project we deal with parsing of data coming from APIs and with the reflection of these data in the UI of our apps.

Background

On one of our projects we have an API data source with the list of items, which should be displayed in a form of a list in the app, but that list may contain different types of items: video, audio and standard articles. All the types of data are packed into one JSON array with similar data structures for each item. Technically what we need to come up with in the final code is called a heterogeneous array:

A heterogeneous array is an array in which all the elements are not of the same type.

Task

For the start, we need to design an initial data structure. We use Protocol to define a common piece of data, that will be stored in the final array.

Then we define types of data, that our JSON source can contain:

Swift 4 came with a useful addition of Coding protocol, that allows parsing all the data from JSON into appropriate objects in Swift with a minimal amount of repetitive code. After migrating this project to Swift 4 we needed to decide how to parse the data coming from API with a minimal amount of boilerplate code into a heterogeneous array of instances of Audio, Video and Article classes. After googling of “heterogeneous array Swift” and similar requests I’ve found out, that this topic is not so perfectly covered.

After a number of tries and failures, I came up to a pretty simple and brief solution for our problem — a container class to parse all the data. This container class should contain all the logic that recognizes either a currently parsed object is Audio, Video or Article (or even parsing logic can be outsourced out from the model). Then we’re able to map all the results from a container class to the protocol class before using them in the project.

To check the workability of this approach I created a simple playground, that you can find by a link at the end of the article. Code for testing and tests of the implementation in the playground:

Outcome

Hope this small tip will help somebody to speed up their work or education of possible approaches of parsing JSON data using Swift.

Link to the source code:
splice() mutable JavaScript. Continuing the last lesson, splice() is…
By: Soyoung Chung
Tags: Splice, JavaScript, Array

Continuing the last lesson, splice() is the method to remove and add elements from array.

1. splice(): mutable

splice() method removes elements from array.

array.splice(start, deleteCount, item1, item2, …)

start: index number of element that will be removed.

deleteCount: the number of element that will be removed from start.

item1, 2, …: those items will be added in the index where original elements are removed already.

So, deleteCount number of element will be removed from start index.

array.splice(start)

array.splice(start, deleteCount)

array.splice(start, deleteCount, item1, item2, ...)

splice() returns a new array of removed elements and mutates original array.

2. splice() removes 1 original element at the index [2].

var arr = ["인덱스0", "인덱스1", "인덱스2", "인덱스3"]; var spliced = arr.splice(2, 1); console.log(spliced); // ["인덱스2"] console.log(arr); // (3) ["인덱스0", "인덱스1", "인덱스3"]

3. splice() removes 1 original element at the index [2] and adds 3 elements at the index [2].

var arr = ["인덱스0", "인덱스1", "인덱스2", "인덱스3"]; var spliced = arr.splice(1, 2, "새로운 원소1", "새로운 원소2", "새로운 원소3"); console.log(spliced); // (2) ["인덱스1", "인덱스2"] console.log(arr); // (5) ["인덱스0", "새로운 원소1", "새로운 원소2", "새로운 원소3", "인덱스3"]

Reference
Kids With the Greatest Number of Candies
By: Jen Lindner
Tags: Leetcode Easy, Algorithms, JavaScript, Arrays, Leetcode Solution

The Solution

If you didn’t fully understand the instructions the first time reading through, don’t worry — I was confused after reading their instructions too. Essentially, for each element in candies, we need to determine whether or not its value can become the maximum value in the array once the amount from extraCandies is added to it. For each value in candies, we need to fill in an array with true or false depending on whether it can be the maximum or not.

We can come to our solution by finding the current maximum number of candies listed in the given candies array, then looping through candies, each time comparing the current element + extraCandies to the maximum number of candy to determine what we’re adding to our result array.

To start, we can create a result array that’s equal to the length of candies and pre-filled with a false value at each index. During each loop, we can change the value at the current index of result to true depending on the value of the current element of candies. Alternatively, we could create an empty result array and then push true or false into the array as we loop through candies.

Next, let’s find determine the maximum element in the candies array and set it to a variable, which we’ll call max. To find this value, we can use the Math.max() function and use a spread operator on the candies array to allow us to compare the values of its elements without requiring a second parameter.

Now that we found our current maximum amount of candies, we can start looping through the candies array to figure out if any kids have the same or more candies than the maximum amount, after adding the extra candies. As we loop, we just need to add the value of the extra candies to the current element of candies and then compare it to max. If it’s greater than or equal to max, we’ll change the current element of result to true from its original value of false. If the value is less than max, we can move onto the next element without making any changes to result, since the current element is already false.

All we need to do now is return our result array and we’re done! Let’s check out our completed solution, with O(n) runtime.

Problem solved!

You can find this problem on LeetCode — feel free to give it a try!

A girl can dream…
Passing an Object or Array to Stencil through markup
By: Scott M Gerstl
Tags: Typescript, Arrays, JavaScript, Stenciljs

Common Code

export interface SomeValue {

name: string;

value: string;

}

Passing an Object

import { Component, Prop, Watch } from '@stencil/core';

import { SomeValue } from './some-value.interface'; @Component({

tag: 'object-sample',

styleUrl: '...',

shadow: true

}) export class ObjectSample { private _objectData: SomeValue;

@Prop() objectData: SomeValue | string;



@Watch('objectData')

objectDataWatcher(newValue: SomeValue | string) {

if (typeof newValue === 'string') {

this._objectData = JSON.parse(newValue);

}

else {

this._objectData = newValue;

}

} componentWillLoad() {

this.objectDataWatcher(this.objectData);

} render() {

return (

<div class='object-data'>

<span>{this._objectData.name}</span>

<span>{this._objectData.value}</span>

</div>

);

}

} // Implementation

<object-sample

object-data='{"name": "Bird", "value": "Chirp"}'>

</object-sample>

Passing an Array

import { Component, Prop, Watch } from '@stencil/core';

import { SomeValue } from './some-value.interface'; @Component({

tag: 'array-sample',

styleUrl: '...',

shadow: true

}) export class ArraySample {



private _arrayData: SomeValue[];

@Prop() arrayData: SomeValue[] | string; @Watch('arrayData')

arrayDataWatcher(newValue: SomeValue[] | string) {

if (typeof newValue === 'string') {

this._arrayData = JSON.parse(newValue);

}

else {

this._arrayData = newValue;

}

}



componentWillLoad() {

this.arrayDataWatcher(this.objectData);

} render() {

return [

<div class='array-size'>{ this._arrayData.length }</div>, this._arrayData.map(x =>

<div class='row'>

<span>{x.name}</span>

<span>{x.value}</span>

</div>

)

];

}

} // Implementation

<array-sample

array-data='[{"name": "Cat", "value": "Meow"}, {"name": "Dog", "value": "Woof"}]'>

</array-sample>

Key Concepts

The @Prop() datatype must contain string if a type is defined

datatype must contain if a type is defined Use a @Watch() function to parse the json string value

function to parse the json string value Call the @Watch() function in the componentWillLoad() function for the first parse of the json data

- The @Watch() function does not fire on the first load of the component

function in the function for the first parse of the json data - The function does not fire on the first load of the component The value passed to the @Prop() must follow strict json syntax

Version Consideration

These examples are Stencil One. If you are using @stencil/core@one Check out the Breaking changes document to see what updates are needed to get this sample to work for you in the beta

Special Thanks

to Sean Bannigan for helping me figure out the actual code to put these examples together.