## #StackBounty: #reactjs #data-structures #refactoring #javascript-objects #solid-principles How to refactor a react component that is ha…

### Bounty: 50

I’d like to apply SOLID principles with a react component that’s handling too many ‘use cases’. As an example let’s say I have a component that’s main responsibility is to render a table like so:

return (
<Table dataSource="" name={tableName} />
)


This is a very simplistic representation of that table. But the main point of complexity is the prop dataSource. Inside this <Table> component, I actually have a lot of logic/if-else condition that’s catering for the dataSource flag littered within the component because the dataSource can take in many different shapes / object structure. Some are very similar that they can be abstracted, while some are quite specific (and may even just differ by one key).

For example:

const tableName = \${
dataSource === 'dataSourceA'
? dataSourceName
: dataSourceName.name
};


This is just one example. Imagine some dataSource has its name property nested 3 levels deep. Then other dataSource will even have different names for the keys (although the resulting data that I need to render are actually the same). Not only that, depending on the dataSource, I may need to call a different endpoints to execute some functionalities (again, the function is doing the same purpose, just the endpoint can be different). Hence within the same component I’ll have a function like:

const exportTable = () => {
if(dataSource === 'dataSourceA') {
// use endpoint A
} else if (dataSource=== 'dataSourceB') {
// use endpoint B
} else {
// use endpoint C
}
}


What is the best way to refactor this kind of component and make it easier to maintain? Later on, we can have 10 types of dataSources and I can’t be doing if-else conditions within the component to cater for their differences.

Get this bounty!!!

## #StackBounty: #algorithm #data-structures #hash #hashcode Why do we have double hashing function as [(hash1(key) + i * hash2(key)) % TA…

### Bounty: 50

I learned the notation of double hashing [(hash1(key) + i * hash2(key)) % TABLE_SIZE] couple days ago. There is a part I couldn’t understand after thinking about it and searching for answer for days.

Why don’t we discard the [hash1(key)] part from the double hashing function and simply make it as [(i * hash2(key)) % TABLE_SIZE]?

I couldn’t find any downside of doing this, except all the hashcodes would start from 0 (when i = 0).
The main purpose of using double hashing, avoiding clusters, can still be achieved.

It will be super thankful if anyone can help:D

Get this bounty!!!

## #StackBounty: #java #algorithm #optimization #data-structures #greedy Gridland Metro HackerRank

### Bounty: 50

I was solving this question on hackerRank. I have gone through the whole discssions section, tried all the suggested test cases with expected results. I think I might be doing some silly code mistake as I’m sure I’ve thought/considered every scenario in the implementation. could you please help me out pointing if there is any mistake in my code.

public static void main(String[] args) throws IOException {
double n = Double.parseDouble(strNum[0]);
double m = Double.parseDouble(strNum[1]);
double k = Double.parseDouble(strNum[2]);

Map<Double, TreeMap<Double, Double>> map = new HashMap<>();
while (k > 0) {
double r = Double.parseDouble(strNum[0]);
double c1 = Double.parseDouble(strNum[1]);
double c2 = Double.parseDouble(strNum[2]);
TreeMap<Double, Double> innerMap = map.get(r);
if (innerMap != null) {
innerMap.put(c1, c2);
} else {
innerMap = new TreeMap<Double, Double>();
innerMap.put(c1, c2);
map.put(r, innerMap);
}
k--;
}
double count = (n - map.size()) * m;
for (Map.Entry<Double, TreeMap<Double, Double>> e : map.entrySet()) {
TreeMap<Double, Double> innerMap = e.getValue();
double start = innerMap.firstKey();
double end = innerMap.firstEntry().getValue();
for (Map.Entry<Double, Double> e2 : innerMap.entrySet()) {
double x = e2.getKey();
double y = e2.getValue();
if (y > end) {
if (x > end) {
count += ((x - end) - 1);
}
end = y;
}

}
count += (m - (end - start + 1));
}
System.out.println(String.format("%.0f", count));
}


25/31 test cases are failing. Any help is much appreciated.

Get this bounty!!!

## #StackBounty: #data-structures #arrays #abstract-data-types Formal definition of the Dynamic Array – what is the Dynamic Array

### Bounty: 50

I’ve researched quite a bit about this topic. Since I’m kind of a fan of Exact Sciences, I love everything to have a crystal-clear and determined definition, without any ambiguous or dubious points.

Dynamic Array, according to the Wikipedia’s article, is a Data Structure. Article states, that:

Dynamic array (also called as growable array, resizable array, dynamic
table, or array list) is a random access, variable-size list data
structure that allows elements to be added or removed.

This/above definition, surprisingly coincides with the definition of the Dynamic Array provided in the Data Structures and Algorithms Made Easy book (Chapter 3.5), by Narasimha Karumanchi.

However!,

We know, that the Data Structure, by its formal definition, is a specialized implementation of the Abstract Data Type (ADT), but I have never seen, in any programming language ever, any specialized Data Structure called Dynamic Array, nor can I find any ADT which is implemented by Dynamic Array.

For instance, we have several Data Structures, in Java, which implement List interface (and interface constitutes an ADT, in this case, as similarly to the concept of ADT, it declares the abstract behavioural characteristic of What must be done, and – says nothing about How), and Dynamic Array is defined (as shown above) as a Data Structure implementing a concept of the Array with the functionality of adding and removing elements in/from it. Many resources (including books provided) define the model of the Dynamic Array as implementations of List – namely ArrayList and LinkedList in the case of Java.

So,

1. if the Dynamic Array is a Data Structure, then what is the ADT
implemented by that Data Structure?
2. Maybe Dynamic Array suits more the concept of ADT where the implementations of it are provided in a different ways (example in Java is classes implementing List)?
3. What is the formal definition of Dynamic Array? is it ADT? is it Data Structure? as I find the definitions in the books/articles, quite contradictory and they oppose each other.

I, personally, think of defining it as a special type of Array Abstract Data Type, in which, structure is not a fixed-sized. I’d call it a special type of Array ADT, which makes it also ADT. Because, it’s obvious, that if the Data Structures implementing the Dynamic Array (as said in the provided resources) are very concrete classes like LinkedList and ArrayList then the Dynamic Array itself is no longer a Data Structure, but rather it’s some special kind of Array ADT.

What is the Dynamic Array? how it should be correctly and formally defined? Maybe it’s just a concept of non-fixed-sized array, which is a conceptual model and has nothing to do with any ADT or DS?

Get this bounty!!!

## #StackBounty: #algorithms #data-structures #search-algorithms Search for maximal value smaller than V in an array composed of K linear …

### Bounty: 50

Sorry for the lack of clarity in the question description.

I have an array composed of length $$N$$ composed of $$K$$ linear subarrays. We define a linear subarray as a contiguous subarray of the array $$[l,r]$$ where $$A[i]-A[i-1] = C$$, a constant, for all $$l. (Note: $$C$$ may be different for different subarrays; the elements of the array are integers.) Please note that the linear subarrays are not disjoint (there is one element intersection between any pair of adjacent linear subarrays). For example, [1,3,5,4,3,2] has two linear subarrays: [1,3,5] and [5,4,3,2]. [1,3,5,1,2,3] would have three: [1,3,5], [5,1], [1,2,3].

I wish to find multiple queries for the maximal value that is less than a queried value $$V$$ in sublinear time per query, such as $$O(logK)$$, or even $$O(logN)$$. I am fine with any preprocessing in time such as $$O(K)$$, $$O(KlogK)$$, but not $$O(N)$$. (Assume that the array has already been stored in terms of the K linear subarrays, perhaps in terms of the constant C and length of each subarray, with the subarrays ordered. Therefore, you are given the array with the starting and ending points of all the linear subarrays, as well as the linear constant C, as described before.)

Of course, a balanced binary search tree (BBST) or simply sorting achieves the purpose, but it requires $$O(NlogN)$$ preprocessing, which is too much. Checking the largest valid value within each subarray takes $$O(K)$$ per query, which is again too much. Would it be possible for something to combine both of these, perhaps?

(EDIT: To be clear, the complexities I wish for are $$o(K^2)$$ for pre-processing and $$o(N)$$ and $$o(K)$$ per query. Please note that this is not inclusive of $$O(N)$$ etc for pre-processing and $$O(K)$$ etc for query. To be more clear, I wish for the total of $$K$$ queries plus pre-processing to run practically in time faster than the $$O(K)$$ per query solution. Also only if possible, it would be nice if the solution worked with queries on decreasing-length suffixes of the array as well, like the BBST and $$O(K)$$ solutions do.

Randomised algorithms are okay as long as they always achieve the correct answer and work fast enough in the average case, though deterministic algorithms are preferred.

Thanks for any and all responses. I was wondering if there was any research in the question, maybe? It does not seem like too obscure a topic, but unfortunately my searching has not been competent enough.

EDIT: A method that seems useful.

Here was my line of thinking after I asked the question; I wonder if this would help somehow. It uses the idea of modulo as well.
Initialise V=0, and allow each linear subarray to be stored as L,R; where L is the minimal value of the subarray and R is the maximal value. When we are given a query for V, we somehow disinclude elements where L>V and R<V (perhaps by using multiple dimensions?) A supplementary data structure stores the minimal theoretical difference of the element in the array, which is something like L - V mod c[i]. So essentially, we now need to be able to run a range add on this data structure, but if the value of any element becomes <0 or >=c[i] it needs to be reset (eg. if an element becomes equal to -1 with c[i]=5 it would be reset to 4; if an element becoming equal to 6 with the same c[i] would be reset to 1); and also run range minimum queries.

If such a data structure can be made, the problem is solved. The trouble is the modulo, as range add and range minimum query can be easily done with a segment tree and lazy propagation; as well as the disinclusion of certain elements.

Get this bounty!!!

## #StackBounty: #algorithms #data-structures #computational-geometry Creating a priority search tree to find the number of points in the …

### Bounty: 50

A priority search tree can be constructed on a set of points P in O(n log(n)) time but if the points are sorted on the y co-ordinates then it takes O(n) time. I find algorithms for constructing the tree when the points are not sorted.

I figured out a way to do this as follows:

1. Construct a BST on the points.
Since the points are sorted then it will take O(n) time

2. Min-Heapify the BST on the x-coordinates
This will take $$theta$$(n) time

So total time complexity will be

O(n) + $$theta$$(n) = O(n)

Is this a valid approach to construct a Priority Search Tree in O(n) time, from a set of points sorted on the y-coordinates??

Get this bounty!!!

## #StackBounty: #generics #design-patterns #data-structures #types #dart How to store a collection path for a model?

### Bounty: 50

I’m building models for my app in Dart/Flutter. Here’s how a model looks like:

abstract class Model {
/// A unique identifier of the model.
/// Gets generated by Firestore.
final String id;

Model(this.id);
}

class MyModel extends Model {
final String name;
final String description;
final int order;

MyModel(String id, this.name, this.items, this.order) : super(id);
}


Those models would be stored in Google Firestore in mymodels collection:

mymodels/abc
mymodels/def
...


To fetch a list of these models from Firestore I need to store the collection path (mymodels) for MyModel type somewhere. So I could use it later when fetching models:

Future<List<T>> fetchList() {
// How to know path by knowing T?
_firestore.collection('path').getDocuments()
}


Where to store that collection path? I was thinking to declare a static property in Model interface, but Dart doesn’t seem to allow override static properties.

Would Dart annotations be a good fit for that?

Get this bounty!!!

## #HackerEarth: #BattleOfBots 9: Taunt

Problem

Taunt is a two player board game which is played on a 10X4 grid of cells and is played on opposite sides of the game-board. Each player has an allocated color, Orange ( First Player ) or Green ( Second Player ) being conventional. Each player has nine piece in total. The players move their pieces towards to his / her opponent’s area by moving their pieces strategically. Each piece has a different moving feature and is one of the 3 types of pieces.

Piece 1: It can move to horizontally or vertically adjacent cell, if the cell doesn’t contain a piece of same color.

Piece 2: It can move to horizontally adjacent cell or can move two steps forward, if the cell doesn’t contain a piece of same color (except the piece itself).

This type of piece can move to its own position if its in the second last row of the grid and going downward or if its in the second row of the grid and going upward.

Piece 3: It can move two step diagonally in the forward direction, if the cell doesn’t contain a piece of same color (except the piece itself).

This type of piece can move to its own position if its in the second last row of the grid and going downward or if its in the second row of the grid and going upward.

Players take turns involving moves of pieces as mentioned above and can captures opponent’s piece by jumping on or over opponent’s pieces.

Note: Forward direction for first player is downward and for second player is upward.

If a piece (except piece 1) is moving downward and touches the last row, its direction will change i.e. now it will move upward. Similarly, once if a piece (except piece 1) is moving upward and touches the first row, its direction will change i.e. now it will move downward.

Rules:

• Player can only move according to the moves mentioned above.
• A player may not move an opponent’s piece.
• A player can captures opponent’s piece by jumping on or over opponent pieces.

The game will end after 100 moves ( 50 moves for each player ) or when any of the players don’t have any move left. At the end of the game the player with majority of pieces will win.

We will play it on an 10X4 grid. The top left of the grid is [0,0] and the bottom right is [9,3].

Input:
The input will be a 10X4 matrix consisting only of 0,1or2. Next line will contain an integer denoting the total number of moves till the current state of the board. Next line contains an integer – 1 or 2 which is your player id.

In the given matrix, top-left is [0,0] and bottom-right is [9,3]. The y-coordinate increases from left to right, and x-coordinate increases from top to bottom.

A cell is represented by 3 integers.

First integer denotes the player id (1 or 2).
Second integer denotes the type of piece (1, 2 or 3).
Third integer denotes the direction of the piece (0 (upward) or 1 (downward)). When the piece is of first type, direction doesn’t matter as the piece is free to move to horizontally or vertically adjacent cell, if the cell doesn’t contain a piece of same color.

Empty cell is represented by 000.

Output:
In the first line print the coordinates of the cell separated by space, the piece you want to move.
In second line print the coordinates of the cell in which the piece will jump.
You must take care that you don’t print invalid coordinates. For example, [1,1] might be a valid coordinate in the game play if the piece is able to jump to [1,1], but [9,10] will never be. Also if you play an invalid move or your code exceeds the time/memory limit while determining the move, you lose the game.

Starting state
The starting state of the game is the state of the board before the game starts.

131 131 131 121
121 121 111 111
111 000 000 000
000 000 000 000
000 000 000 000
000 000 000 000
000 000 000 000
000 000 000 210
210 210 220 220
220 230 230 230


First Input
This is the input give to the first player at the start of the game.

131 131 131 121
121 121 111 111
111 000 000 000
000 000 000 000
000 000 000 000
000 000 000 000
000 000 000 000
000 000 000 210
210 210 220 220
220 230 230 230
0
1


SAMPLE INPUT
000 000 000 000
000 000 000 111
000 000 111 130
000 000 000 000
000 000 000 000
000 220 000 000
131 000 000 000
121 000 210 000
000 210 131 000
000 210 000 000
58
1
SAMPLE OUTPUT
8 2
8 0


Explanation

This is player 1’s turn, and the player will move the piece at [8,2] and will take two steps diagonally in downward direction and will be at [8,0]
After his/her move the state of game becomes:

000 000 000 000
000 000 000 111
000 000 111 130
000 000 000 000
000 000 000 000
000 220 000 000
131 000 000 000
121 000 210 000
130 210 000 000
000 000 000 000
59
2


Note: Direction of the piece is also changed from 1 to 0 as the piece was moving downward and touches the last row. This state will be fed as input to program of player 2.

Here is the code of the default bot.

Time Limit:1.0 sec(s) for each input file.
Memory Limit:256 MB
Source Limit:1024 KB

Sample Game

## HackerRank: Repeated String

### Problem

Lilah has a string, s, of lowercase English letters that she repeated infinitely many times.

Given an integer, n, find and print the number of letter a‘s in the first letters of Lilah’s infinite string.

### Input Format

The first line contains a single string, s.
The second line contains an integer, n.

### Constraints

• 1<=|s|<=100
• 1<=|n|<=10^12
• For 25% of the test cases, n <= 10^6

### Output Format

Print a single integer denoting the number of letter a’s in the first letters of the infinite string created by repeating infinitely many times.

aba
10

7

### Explanation 0

The first n = 10 letters of the infinite string are abaabaabaa. Because there are 7 a‘s, we print on a new line.

a
1000000000000

1000000000000

### Explanation 1

Because all of the first n=1000000000000 letters of the infinite string are a, we print 1000000000000 on a new line.

## HackerRank: Circular Array Rotation

### Problem

John Watson performs an operation called a right circular rotation on an array of integers, [a(0),a(1).a(2)...a(n-2),a(n-1)]. After performing one right circular rotation operation, the array is transformed from

[a(0),a(1).a(2)...a(n-2),a(n-1)]

to

[a(n-1),a(0),a(1).a(2)...a(n-2)].

Watson performs this operation k times. To test Sherlock’s ability to identify the current element at a particular position in the rotated array, Watson asks q queries, where each query consists of a single integer, m, for which you must print the element at index in the rotated array (i.e., the value of a(m)).

#### Input Format

The first line contains space-separated integers, n, k, and q, respectively.
The second line contains space-separated integers, where each integer i describes array element a(i)(where 0 <= i <= n).
Each of the q subsequent lines contains a single integer denoting m.

#### Constraints

• 0 <= i <= 10^5
• 0 <= a(i) <= 10^5
• 0 <= k <= 10^5
• 0 <= q <= 500
• 0 <= m <= N-1

#### Output Format

For each query, print the value of the element at index m of the rotated array on a new line.

##### Sample Input
3 2 3
1 2 3
0
1
2

##### Sample Output
2
3
1


#### Explanation

After the first rotation, the array becomes [3,1,2].
After the second (and final) rotation, the array becomes [2,3,1].

Let’s refer to the array’s final state as array b. For each query, we just have to print the value of b(m) on a new line:

• m=0 , so we print 2 on a new line.
• m=1 , so we print 3 on a new line.
• m=2 , so we print 1 on a new line.