somjit{} 60 Junior Poster in Training Featured Poster

It's funny to see ASAP coming from someone apart from one's stingy boss :D

somjit{} 60 Junior Poster in Training Featured Poster

The last time a major change happened, i remember in a community chat few people (including me) were saying that the new changes looked a bit girly :P That won't work this time though. This is so totally different from vintage Daniweb. Also, i see some stuff probably not working right :

daniweb_changed.png

These never were my favourite places to post. I would doubt that i even posted there... ever!
I guess a lot of people are already talking about the change, well, count me in too.

somjit{} 60 Junior Poster in Training Featured Poster

Getting a private auto-message for an sponsored post, and coming here to find homework.. just screwed my mood.

Dani commented: Just came across this post. Sorry DaniWeb failed you :( We'll do better +32
somjit{} 60 Junior Poster in Training Featured Poster

Apparantly,i had put the vertex count wrong. That led to a null pointer exception.. and a crash. Needed to code the whole thing in java to realise this. Code works perfectly :)

somjit{} 60 Junior Poster in Training Featured Poster

My Program is about Directed Graphs. It reads a list of edges like : 25 589 , and puts 589 into the adjacency list (a linked list) of 25. My input file has about 5 Million such v w edges, with about 800K nodes/vertices, for each of which there will be a linked list(adjacency list) containing edges going outward from that node.
My program wants to read this one edge per line input file, and create a adjacency list view of the graph.

So if the ip file be like :

25 589
27 881
4689 36
25 77489

then the output should be something like :

25   | 589 77489
27   | 881
4689 | 36

Now my program works for smaller inputs. But the above big file crashes my program at about 4.6 Million edge mark. I tried catching calls to malloc() and calloc() , to see if heap space is filled up, but perror() doesnt say anything , even though the program keeps crashing.

Below is the header file and the source file :

/*
 * Bag.h
 *
 *  Created on: 14-Feb-2015
 *      Author: Somjit 
 */

#ifndef WEEK4_BAG_H_
#define WEEK4_BAG_H_

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

typedef struct node{
    long item;
    void *next;
}node;

typedef struct Bag{
    long size;
    node *first;
}Bag;

Bag *new_Bag(){
    Bag *b = malloc(sizeof(Bag));
    if(b==NULL){
        perror("malloc fail 2");
        exit(EXIT_FAILURE);
    }
    b->size = 0;
    b->first = NULL;
    return b;
}

void add_node(Bag *bag,long item){
    node *old = bag->first;
    //create a new …
somjit{} 60 Junior Poster in Training Featured Poster

I work in it now, its kinda hard to work on , given its wanton use of GOTO , its difference from everything i know (save for assembly perhaps , but i only remember less than 10 commands there anyways :P ) , and the fact the its entire online repository is one wiki page. No i am not asking this to pester any veteran with questions on MAPPER , just curious :)

Waiting for the hands :)
Som.

somjit{} 60 Junior Poster in Training Featured Poster

Well , i knew that sizeof(array) returns memory occupied , but if somebosy had asked me why thats happening , wouldn't have been able to answer properly i guess. Now i know what to say :) thanks :)

somjit{} 60 Junior Poster in Training Featured Poster

Noting, of course, that an array is not a pointer. Though an array name in most contexts is converted to a pointer.

Can you elaborate that part a bit ?

Regarding the cast , kept it out coz felt like its a different pond ( or lake , or sea ) altogether.. but thanks for seamlessly joining that in. Couldn't have done it near as well !

somjit{} 60 Junior Poster in Training Featured Poster

The below post is just something i thought of contributing here for young( or old ) members starting out in C.
In (effectively) 3 lines of code , i hope to give an intro about pointer arithmetic and how endian-ness in windows affects the output.

#include<stdio.h>
int main(void){
    int a = 66561;
    char *c = &a;
    int i;
    for(i=0 ; i < 4 ; i++) printf("%d\n",*(c+i));
}

This gives an output of

1
4
1
0

Why ?
Well , 66561 in binary is 00000000-00000001-00000100-00000001. (iv separated each byte with a '-' )
But , in windows , which is a little endian system , the above binary is stored in reverse order ( little end coming first ) in memory as :

00000001-00000100-00000001-00000000.

So , when you go reading one byte at a time , it is read as 1 , 4 , 1 and 0.

However , you'll notice that i did this using a character pointer , not by creating any character array. Well , that's because you dont need to do that.

If u write : int arr[5] , then arr is same as saying &arr[0] they both point to the starting address of the memory occupied by what we take as an array. In the same way , if u say int *a = 5 , then a is the same as arr or &arr[0]. its just a pointer that points to a certain memory.

Applying …

somjit{} 60 Junior Poster in Training Featured Poster

My assignment says :

Write a program to perform following stack operations : Create a stack with item code and quantity

Itemcode    Quantity
    111     450
    112     0
    113     487
    114     101
    115     500
    116     0
    117     359

and then Delete the items having quantity zero and update the stack.

My code is :

#include<stdio.h>
#define LEN 7
struct item { int* num ; int* q; }

int main(void){
    int length = LEN,i,j;
    struct item data[LEN];

    // read input data into struct
    for(i=0 ; i < LEN ; i++){
        printf(" %d . enter item-code : ",i);
        scanf("%d",data[i].num);
        printf(" %d . enter quantity : ",i);
        scanf("%d",data[i].num);
    }

    // Delete the items having quantity zero and update the stack
    for(i=0 ; i < length ; i++) if(*data[i].q == 0){
        for(j=i+1;j<length;j++) 
            data[j-1] = data[j]; // update by overwriting
        data[j] = NULL;
        length--;
    }

    // display stack
    for(i=0 ; i < length && data[i]!= NULL; i++){
        printf(" %d > item : %d , quantity : %d\n",i,*data[i].num,*data[i].q);
    }

    return 0;
}

Its the 1st time i'm working with structs in C . The errors i get are :

StructStack.c:5: error: two or more data types in declaration specifiers
StructStack.c: In function 'main':                                                                   
StructStack.c:21: error: incompatible types when assigning to type 'struct item' from type 'void *'  
StructStack.c:26: error: invalid operands to binary != (have 'struct item' and 'void *')             
StructStack.c:30: error: incompatible types when returning type 'int' but 'struct item' was expected

Any help would be great.

regards
Somjit.

somjit{} 60 Junior Poster in Training Featured Poster

how do i solve this ?

somjit{} 60 Junior Poster in Training Featured Poster

If we have something in a div block , how come it can flow out of the div block as if nothing's even there ?
For example , here :

<!DOCTYPE html>
<html>
    <head>
        <link type="text/css" rel="stylesheet" href="box.css"/>
        <title>Result</title>
    </head>
    <body>
        <div>
            <p>one</p>
            <p>two</p>
            <p>one</p>
            <p>two</p>
            <p>one</p>
            <p>two</p>
        </div>
    </body>
</html>

the <p> stuff flows out of the <div> so easily. Why is that ?

stylesheet:

* {
    border: 1px dashed black;
}
div {
    height: 50px;
    width: 100px;
    border: 4px solid #FF0000;
    border-radius: 5px;
    background-color: #308014;
    margin:10px 10px 10px 10px;
    padding:40px;
}
div p{
    background-color:yellow;
    /*display:inline;*/
}
somjit{} 60 Junior Poster in Training Featured Poster

create an inner list Node , which will have 3 feilds : prev ,next and data . If your creating a singly linked list , you can do with only data and next. next and/or previous will refer/point to the next/prev node in the list.

somjit{} 60 Junior Poster in Training Featured Poster

Your code is very hard to read . Not only are the names of the methods non-descriptive , but also , there aren't any comments for them. Also , your assignment speaks to implement recursion where-ever possible , but i dont see you doing that. Recursion is bad for a lot of things , but it really makes things simple when it comes to trees. As for example , in your printInOder() method , if you implemented that using recursion , here is what it can be changed to :

    public Iterable<Key> keys(){
        Queue<Key> q = new Queue<Key>(); // queue implements iterable , so contract is valid
        inorder(root, q); // call the recursion
        return q
    }

    private void inorder(Node x, Queue<Key> q) {

        if (x == null)
            return; // will signify the end of recursion , all the stacks starts
                    // returning hereonwards

        inorder(x.left, q);

        q.enqueue(x.key); // as stacks start evaluating , nodes will be put into
                            // the queue starting from the left most leaf , ie , the
                            // smallest node , ending with the root

        inorder(x.right, q); // and now enqueue all the nodes to the right
    }

So all you do is call print on keys() and it takes care of all the traversing and printing. Resulting in cleaner , better , lesser (amount of) inspection needed when something goes wrong. like now.

( comments are what i understand of the code , i can be wrong though. )

Also , reagrding your …

somjit{} 60 Junior Poster in Training Featured Poster

One thing that i find a bit hard , is that the use of "key" here. Key is generally accompanied by a corresponding value , but your node does not have a key-value pair , only a key. Perhaps you could make that change . Yes it may not directly solve your problem , but it clears things.

also , what is your new version for this : binRoot = delete(binRoot); ?

somjit{} 60 Junior Poster in Training Featured Poster

No problem. But can you explain the role of the two argument delete() as compared to the previous one ?

edit : i see that you implemented the pattern somewhat that i posted ,missed it at first. lets see whats happening...

somjit{} 60 Junior Poster in Training Featured Poster

regarding deletion , here are 4 steps to it

Save a link to the node to be deleted in t. (n in your case)
Set x to point to its successor min(t.right).
Set the right link of x (which is supposed to point to the BST containing all the keys larger than x.key) to deleteMin(t.right), the link to the BST containing all the keys that are larger than x.key after the deletion.
Set the left link of x (which was null) to t.left (all the keys that are less than both the deleted key and its successor).

probably you have implemented this , but your delete code looks a bit complicated.

The implementation for the above description is something like this :

    public void deleteMin() {
        root = deleteMin(root);
    }

    private Node deleteMin(Node x) {
        if (x.left == null)
            return x.right;
        x.left = deleteMin(x.left);
        x.N = size(x.left) + size(x.right) + 1;
        return x;
    }

    public void delete(Key key) {
        root = delete(root, key);
    }

    private Node delete(Node x, Key key) {
        if (x == null)
            return null;
        int cmp = key.compareTo(x.key);
        if (cmp < 0)
            x.left = delete(x.left, key);
        else if (cmp > 0)
            x.right = delete(x.right, key);
        else {
            if (x.right == null)
                return x.left;
            if (x.left == null)
                return x.right;
            Node t = x;
            x = min(t.right); 
            x.right = deleteMin(t.right);
            x.left = t.left;
        }
        x.N = size(x.left) + size(x.right) + 1;
        return x;
    }

    private Node min(Node x)
    {
        if (x.left == null) return …
somjit{} 60 Junior Poster in Training Featured Poster

its a lot of code to go through , lets see..

What if you put the elements in a sorted manner inside the BST ? does that comply with your assignment rules ?

if yes , you can use buffered reader , read a line , .split() it , sort the string array , and then put each entry in the order they come in the string. Its not realted to your question perhaps , but i feel having things sorted makes 'em easy.

somjit{} 60 Junior Poster in Training Featured Poster

Update : turns out to be simple enough , just need an interface. something like this.

public class Summation {

    public Double calc(int lower, int upper, Function f) {
        double acc = 0;
        while (lower <= upper) {
            acc += f.definition(lower++);
        }
        return acc;
    }

    public static void main(String[] args) {
        Summation sigma = new Summation();

        // implement definition(double) according to your mathematical function
        // this one does a sum of integers
        System.out.println(sigma.calc(1, 19, new Function() {

            @Override
            public double definition(double x) {
                return x; // this can be more complex
            }
        }));
    }
}

Where Function is a basic interface

public interface Function {
    public double definition(double x);
}
somjit{} 60 Junior Poster in Training Featured Poster

Remember High-school maths ? there was this greek letter Sigma ( if i remember correctly ) , followed by an algebraic function like f(n) , where n = a to b would be short-formed as a below the sigma , and b sitting on top of it. I want to make a program version of that. I dont want code , just the idea how that can be done. I tried it out using scala , and it works . This is the working scala version :

object MySum {
  /**
   * Summation takes in a function f , that returns a type double
   * we calculate that function with each value from a to b ,
   * increasing 1 at a time
   */
  def Summation(f: Double => Double, a: Double, b: Double): Double = {
    // tailwise recursion
    def tailwiseSummation(accumulator: Double, count: Double): Double = {
      if (count > b) accumulator
      else tailwiseSummation(accumulator + f(count), count + 1)
    }
    // accumulator starts with f(a) , so count starts from a+1 to remove off-by-one error
    tailwiseSummation(f(a), a + 1)
  }

  def Factorial(num: Double): Double = {
    def tailwise(accumulator: Double, deprecator: Double): Double = {
      if (deprecator == 0) accumulator
      else tailwise(accumulator * deprecator, deprecator - 1) // deprecator deprecating 1 unit at a time
    }
    tailwise(1, num)
  }

  def main(args: Array[String]) {
    println(MySum.Summation(Factorial(_), 2, 7));
  }
}
somjit{} 60 Junior Poster in Training Featured Poster

Good idea . will do. in fact , right now :P

somjit{} 60 Junior Poster in Training Featured Poster

i was hoping for a more "alive-and-kicking" sort of users. I'm sure they are alive , but apparantly not on daniweb it seems.

somjit{} 60 Junior Poster in Training Featured Poster

just asking...

somjit{} 60 Junior Poster in Training Featured Poster

well..... i feel like saying that my original post was only congratulatory in nature. just for the record.

somjit{} 60 Junior Poster in Training Featured Poster

I saw a tutorial from a site where it showed the use of ArrayBlockingQueue as a thread-safe concurrent data-structure . Just for learning purposes , i tried to build something similar using synchronized and wait-notify methods in java. I'm hoping someone could guide me to some improvements and point out the bad parts of this code i wrote :

import java.util.ArrayList;
import java.util.Random;

public class LowLevelProducerConsumer {
    ArrayList<Integer> list = new ArrayList<Integer>();
    private final int size = 10;
    private int elems = 0;
    Object lock = new Object();
    Random r = new Random(System.currentTimeMillis());

    public void producer() {
        while (true) {
            synchronized (lock) {
                try {
                    while (elems < size) {
                        list.add(r.nextInt(100));
                        elems++;
                    }
                } finally {
                    // allows consumer to remove an entry
                    lock.notify();
                }
            }
        }
    }

    public void consumer() throws InterruptedException {
        Thread.sleep(100); // any better way to ensure producer runs first ?
        int ran = 0;
        while (true) {
            // consumer tries to acquire lock here , but it can do so only after
            // producer has called notify
            synchronized (lock) {

                // do i need a lock.wait() here somewhere ?

                ran = r.nextInt(10);

                if (ran == 7) { // just an arbitrary condition

                    int loc = r.nextInt(list.size());
                    int data = list.remove(loc);
                    System.out.format(
                            "%d removed from index %d , size : %d\n",
                            data, loc, list.size());
                    // decrementing elems to let the producer work again
                    elems--;
                    Thread.sleep(300);
                }

                // release the lock so that producer can fill things up again
                lock.notify();
            }
        }

    }

    public static void …
somjit{} 60 Junior Poster in Training Featured Poster

Get an electronic drum kit

  1. expensive
  2. massive import duty on top of that

i wish guitars and lenses came as cheap as they do in US... i love schecters , especially the corsair and the hellraiser series , #$%@-ing import duties kill everything.

somjit{} 60 Junior Poster in Training Featured Poster

hmm.. i think i read somewhere that endorsements are treated as something detached from the ranking procedure . hence no list.

somjit{} 60 Junior Poster in Training Featured Poster

he probably didn't count back then , so he used "lot" instead .. :/
so who has the highest count anyway ?

somjit{} 60 Junior Poster in Training Featured Poster

Ummm....

well , i meant you getting back your account after it got deleted mysteriously...

somjit{} 60 Junior Poster in Training Featured Poster

viewed <M/>'s profile ... dude has 105 endorsements !
Congratulations :D

<M/> commented: Thanks, but i don't agree with that number... +0
somjit{} 60 Junior Poster in Training Featured Poster

i'm currently developing a belly on a skinny body. i like to run when the weather is nice and i can get up early in the morning.

btw , congratz on getting resurrected ( i think i made a typo ... )

somjit{} 60 Junior Poster in Training Featured Poster

i have about 18 years of expirience banging tables :P only reason i dont have a drumkit at home is because of how quiet my neighborhood is , and how much the neighbors would like to keep it that way. I played guitar , until the neck bent and now tunes drop even with half-hours strumming. :(

somjit{} 60 Junior Poster in Training Featured Poster

update :

However, if the system is initialized to a perfectly symmetric state, like all philosophers holding their left side forks, then the graph is cyclic at the outset, and their solution cannot prevent a deadlock.

Okay , so i guess that is a caveat , and

Initializing the system so that philosophers with lower IDs have dirty forks ensures the graph is initially acyclic.

This is the workaround , However , I'm not sure about how to do this part in code. till now , i have a immutable fork class .

public class Fork {

    public final boolean isClean;
    public final int id;

    public Fork(int id , boolean isClean){
        this.id = id;
        this.isClean = isClean;
    }
}

perhaps this should all be in a new thread ?

somjit{} 60 Junior Poster in Training Featured Poster

I am trying it out , However a question :
The wiki talks about the Chandy-Misra solution , in the 3rd point of that algorithm , it says :

When a philosopher with a fork receives a request message, he keeps the fork if it is clean, but gives it up when it is dirty. If he sends the fork over, he cleans the fork before doing so

Why does this not lead to a deadlock ? if one philosopher has one clean fork , and waits to get another clean fork from a neighboring diner/philosopher , who in turn is waiting for a fork as well , this can cumulate to a deadlock right ? one philosopher always waiting for a fork from the other ?

somjit{} 60 Junior Poster in Training Featured Poster

How do I know to only pull the rest of the line that has draw in it though?

as your current txt stands , draw is always at the begining , so after split()-ing a line , check if the 1st entry equals draw , if so , you know that the rest will also be picture details.

somjit{} 60 Junior Poster in Training Featured Poster

there is a bit that you have justify here : will the "draw" tag be always followed by picture details , if so , the pass the following split()-ed tags to a drawing function that takes them in to draw a picture , instead of having switch cases for each picture description tag.

somjit{} 60 Junior Poster in Training Featured Poster

i never used JUint , i use eclipse debugger for most cases. You can also just have assert() statements at strategic locations in your code , and enable assertion when you want to test it.

somjit{} 60 Junior Poster in Training Featured Poster

your text file looks pretty ordered to me. The only place where you might need scanner for input parsing purposes is when there may be unexpected lines in-between two valid lines , or a valid line has garbage in between two valid key words. split() works there too , but then you have to put in more checks. So unless you have a dirty , unordered file , go with the split-switch method.

Also , If you do decide on using scanner , (though its a bad idea if your file is always like this) , check more into the condition for hasNext() to return false. you can say that it knows there is a wall in front of it only after it has hit it ;)

somjit{} 60 Junior Poster in Training Featured Poster

I like the look of the colours on the black background,

that's exactly what got me started with it. as much as i was comfortable with notepad++ , the colors weren't as "sublime". However , now that i use it , i really like the build feature in it. does anyone know of how to have a similar build feature in notepad++ ?

For example , i use this JSON build for my java code :

{
    "cmd": ["javac","-d","../bin","$file"],
    "file_regex": "^(...*?):([0-9]*):?([0-9]*)",
    "selector": "source.java"
}

takes in the current file location ( which is almost always in the src folder of the current eclipse project) and compiles it into the bin folder.

somjit{} 60 Junior Poster in Training Featured Poster

I think i have understood the basic locks , synchronized statements and methods etc etc . I would like to actually program something that used all this. Something that is prone to breaking if one is not careful , also would love if there is swing involved ( i read that swing has a lot of relation with java concurrency , but that is almost all i know of ). Can someone suggest some project focused around concurrency ? I know there is a projects sticky , but there were so many options there and i didnt know which one to go with.

somjit{} 60 Junior Poster in Training Featured Poster

also if you are a hardcore functional language guy (javascript , python) , java may not be more difficult , but it very well might be a lot more laborious.

somjit{} 60 Junior Poster in Training Featured Poster

DLL<SLL> mydll = new DLL<SLL>()

If you have some expirience with generics , try making DLL take in generic type , and then above line will work. Maybe post your code here full so we can see whats going on ?

somjit{} 60 Junior Poster in Training Featured Poster

The singly cannot exist without the doubly.

In java terms , that can be said as singly being an inner class of doubly.
But your diagram to me all the more strenthens the idea that DLL is a memory space that holds objects of type SLL. And i dont see anything wrong with that. (Except for cases where data is big and memory as well as execution time are important design factors)

somjit{} 60 Junior Poster in Training Featured Poster

its hard to believe that someone downvoted a joke like that :D :P (this is the lounge after all ) .

The post was short , I should have mentioned how cool it occured to me to be actually programming back in 1985 , on an OS that a lot of kids these days haven't even heard of , and on top of that , to have a cool looking text editor ! @Jim , yeah this is a sublime thread , but its also a lounge :) its good to have a loose discussion. :)

somjit{} 60 Junior Poster in Training Featured Poster

Okay , so for life on the heap , what i guess this means is that Your DLL is a datastructure that hold elements of type SLL ?

Perhaps that makes it easier to understand whats going on and how things can be improved ..

somjit{} 60 Junior Poster in Training Featured Poster

thanks, but I am not looking for career advice from you.

  1. the statement was uncalled for. because
  2. your not even sure which one you want - run or review.
somjit{} 60 Junior Poster in Training Featured Poster

Is there any deepCopy() method in the api ? Also , why make a copy of a copy ? since both the instances are of the same object , and the same type of array , ie chess[][] array is being copied , what does it mean to say deepCopy given this specific example ?

somjit{} 60 Junior Poster in Training Featured Poster

what makes a language hard ? the same things i can use to say that makes c++ hard can be used by a veteran in the language as what makes it powerful (for specific purposes). However , i do feel that the api , and how much the "principle of least astonishment" it follows goes a long way in saying a language is harder/easier comparatively.

somjit{} 60 Junior Poster in Training Featured Poster

any language is easy with enough time and dedication. anyways , I'm not sure if this is a question , perhaps you posted in the wrong place ?

somjit{} 60 Junior Poster in Training Featured Poster

why say deep ? it looks like plain simple copy. However , you might want to add checks for the size of other , instead of hardcoding it to 8.