Code Bug Fix: setTimeout within for loop doesn’t return expected result

Original Source Link

My code is

for(let i =0; i<10; i++) {
  const timer = (i*1000);
  setTimeout(() => console.log(i, timer), timer)
}

**My code returns each log only 1s apart from previous. But, expected is

  • when i=1, print after 1s;
  • at i=2 print after 2s;
  • at i=3, print after 3s

**

You can keep track of the timeout time that was last set and add to it each iteration:

let timer = 0;
for (let i = 0; i < 10; i++) {
  timer += i * 1000;
  const thisTimer = timer;
  setTimeout(() => console.log(i, thisTimer), timer)
}

A more readable option would be to await the resolution of the timeout:

(async () => {
  for (let i = 0; i < 10; i++) {
    const timer = i * 1000;
    await new Promise(resolve => setTimeout(resolve, timer));
    console.log(i, timer);
  }
})();

Your current code doesn’t work because the timeout being passed to setTimeout is only being incremented by 1000 each time, so every callback runs 1000 ms apart, rather than 1000 then 2000 then 3000, etc. apart.

SetTimeOut() does not stop the code from running. You basically set 3 timeouts at the same time with 1s, 2s, and 3s so each goes off 1s apart from previous.

If you want execute console.log after each other with time delay you can use a recursive function:

function timerLog(start, end) {
    const timer = (start * 1000);
    if (start == end + 1) {
        return;
    }
    setTimeout(() => {
        console.log(start, timer);
        timerLog(start + 1, end);
    }, timer);
}
//
timerLog(1, 3);

Tagged : / / /

Code Bug Fix: What is this subset of a n-ary tree called?

Original Source Link

Given an n-ary tree, put the root node in a list. Repeat the following procedure:

Take an arbitrary node in this list and replace it with its immediate child nodes in the tree.

At each step, the resulting list represents a subset of the three with some interesting properties:

  • No two nodes in the list are direct or indirect descendants of each other
  • Any path that I walk from the root node, I will end up at a node in this list

Is there a name for this kind of subset of an n-ary tree?

enter image description here

Tagged : / /

Code Bug Fix: Is there a way to initialize a SortedMap with values already included in Java?

Original Source Link

I’d like to do something like so

SortedMap<Integer, String> stuff = new TreeMap<Integer, String>({1:"a",2:"b"});

much like you would do in python but is that possible in Java, or is the only way to call .put() twice?

Starting Java 9, you could do:

SortedMap<Integer, String> stuff = new TreeMap<>(Map.of(1, "a", 2, "b"));

Javadoc links:

TreeMap(Map<? extends K, ? extends V> m)

Map<K, V> of(K k1, V v1, K k2, V v2)

The following holds true according to the Javadoc of SortedMap from both Java-8 and Java-14. It reads for a SortedMap :

The expected “standard” constructors for all sorted map
implementations are:

  1. A void (no arguments) constructor, which creates an empty sorted map
    sorted according to the natural ordering of its keys.

  2. A constructor
    with a single argument of type Comparator, which creates an empty
    sorted map sorted according to the specified comparator.

  3. A constructor
    with a single argument of type Map, which creates a new map with the
    same key-value mappings as its argument, sorted according to the keys’
    natural ordering.

  4. A constructor with a single argument of type
    SortedMap, which creates a new sorted map with the same key-value
    mappings and the same ordering as the input sorted map.

and on the basis of (3), you can simply initialize a SortedMap implementation wrapping another Map initialization as a constructor argument. There are a lot of options in this Q&A that match with other suggestions here.

There’s double brace initializers:

Map stuff = new TreeMap<Integer, String>() {{
    put(1, "a");
    put(2, "b");
}};
System.out.println(stuff);

You can write this in one line if you want.

Although, I do not recommend this. Read here.

In Java 8:

Stream.of(new SimpleEntry<>(1, "a"), new SimpleEntry<>(2, "b"))
    .collect(
        Collectors.toMap(
            Entry::getKey, Entry::getValue,
            (a, b) -> { throw new IllegalStateException(); },
            TreeMap::new);

(Yuk).

The answer by M Anouti holds good for only up to 10 entries. If you want to do it for more than 10 entries, you need to use Map.ofEntries(Map.entry(k, v), Map.entry(k, v) ...) as shown below:

import static java.util.Map.entry;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        SortedMap<Integer, String> stuff = new TreeMap<>(
                Map.ofEntries(entry(1, "a"), entry(2, "b"), entry(3, "c"), entry(4, "d"), entry(5, "e"), entry(6, "f"),
                        entry(7, "g"), entry(8, "h"), entry(9, "i"), entry(10, "j"), entry(11, "k"), entry(12, "l")));
        System.out.println(stuff);
    }
}

Output:

{1=a, 2=b, 3=c, 4=d, 5=e, 6=f, 7=g, 8=h, 9=i, 10=j, 11=k, 12=l}

Tagged : / / / /

Code Bug Fix: How a linear datastructure can be used to implement a non linear datastructure [duplicate]

Original Source Link

Basically my questions is how list and matrix can be used to represent the graph, as list and matrix is linear data structure and graph is a non-linear data structure

So in matrix representation, we only change the value of a particular cell when the vertex represented by column and row number are connected. And list is simply the list for all the neighbors of a particular vertex. In matrix, we store zeroes for pair of vertices not connected and is extra space.

Tagged : / / /

Code Bug Fix: Compare and merge data from two array in JavaScript

Original Source Link

Hello everyone I am newbie in data structure, I have been practising few array operations in JavaScript. I want to do following

var classes = [{id : 1, class:'first'},{id : 2, class:'second'},{id : 3, class:'third'},{id : 4, class:'fourth'}]
var students =[{classId : 1, count:30}, {classId : 3, count:46}, {classId : 2, count:52}]

and I am expecting following output

classes = [
{id : 1, class:'first', count:30},
{id : 2, class:'second', count:52},
{id : 3, class:'third', count:46},
{id : 4, class:'fourth', count:0}

]

I have tried following code for same

for (var i = 0; i < classes.length; i++) {
    for (j = 0; j < students.length; j++) {

        if (classes[i]["id"] == students[j]["classId"]) {
            classes[i]["count"] = students[j]["count"]


        } else {
            classes[i]["count"] = 0
        }

        if (i == classes.length - 1) {
            console.log(classes);
        }

    }

}

But no luck, is there any better way other than for loop? can anyone help me with this?

Thanks in advance

Using .map() and .find() combination:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

The find() method returns the value of the first element in the provided array that satisfies the provided testing function.

Code snippet, possible solution:

const classes = [{id : 1, class:'first'},{id : 2, class:'second'},{id : 3, class:'third'},{id : 4, class:'fourth'}]
const students =[{classId : 1, count:30}, {classId : 3, count:46}, {classId : 2, count:52}];

const result = classes.map(e => {
  const found = students.find(s => s.classId === e.id);
  return {
    ...e,
    count: found ? found.count : 0
  }
});

console.log(result);

I hope this helps!

try using this solution

for(let class in classes){
console.log(classes[class]);
}

what you are doing here is going through ever index of the array classes, and storing the index in class. then you console.log the index.

Tagged : / / / /

Code Bug Fix: Why I am getting Segmentation fault while printing elements of BST?

Original Source Link

I was creating a function to print the elements of BST in level order and I got a segmentation fault.
Here is the print function. It is not giving me the segmentation fault while printing full binary tree.

void printbst(node* root){
  node* arr1[100];
  node* arr2[100];
  node** parent;
  node** child;
  arr1[0] = root;
  bool isempty = false;
  int counter = 0;
  while(!isempty){
    if(counter%2 == 0){
      parent = arr1;
      child = arr2;
    }
    else{
      parent = arr2;
      child = arr1;
    }
    int j = 0;
    isempty = true;
    for(int i = 0; i<pow(2,counter); i++){
      if(parent[i] == NULL){
        printf(" ");
      }
      else{
        printf("%d ",(parent[i])->value);
        child[j++] = (parent[i])->left;
        child[j++] = (parent[i])->right;
        isempty = false;
      }
    }
    printf("n");
    counter++;
  }
}

Insert Function:

node* insert(node* head, int value){
    if(head == NULL){
        head = create(value);
    }
    else if(head->value > value){
        head->left=insert(head->left,value);
    }
    else{
        head->right=insert(head->right,value);
    }
    return head;
}

And you may also need main function, main function:

int main()
{
    node* head = NULL;
    head = insert(head,8);
    insert(head,4);
    insert(head,10);
    insert(head,1);
    insert(head,6);
    insert(head,9);
    insert(head,12);
    insert(head,11);
    insert(head,0);
    insert(head,3);
    insert(head,14);
    printbst(head);
    clear(head);

    return 0;
}

Please help me.

Tagged : / / /

Code Bug Fix: How to write a tree class where nodes can be accessed by position?

Original Source Link

I aim to write a class representing a general tree where nodes can be accessed by giving positions given that new nodes can be added as child to existing and so on.Also positional access has to be written in O(1) time. So far I have decided to write a node and a tree class. Node class for starters is as follows:

class node:
    def __init__(self,data):
        self.data=data
        self.children=[]
    def __str__(self):
        return str(self.data)
    def add_child(self,n,pos=-1)#pos describes position of new child
        if not pos:
            pos=len(self.children)
        if not type(n)==type(node()):
            n=node(n)
        self.children.insert(n)

Positional access means that in following tree:

                  1
             2         3
           4   5         6

position 1 has value 1, position 2 has value 2 and so on?

Tagged : / / / /