invisal 381 Search and Destroy

What a scary project you are aimming? Anyway, if you want to build a toy OS, you can try Cosmos. Cosmos is like a OS lego.

invisal 381 Search and Destroy

177 - 77 = 100

invisal 381 Search and Destroy

what programming language they are using

You can use any programming language. AI is no different from other program.

when learning it self on something new for him and for humans too

AI is trying to replicate how human learn. Human learn based on obversation. Here is how you to learn when you were a kid. You do an action. If your action is bad, your parent gives you a punishment. If your action is good, your parent gives you a reward. You can do the same with computer.

if have some knowledge about this CRAZY stuff

Don't believe the movie. We have no mean to create AI with ability to learn like human yet. Most of the AI nowaday is designed to fullfill one particular task. We have AI for playing chess. We have AI to translating from one language to another language, We have AI to predict what movie you want to watch...

It is hard to convincing you that AI is not something mystery (it is difficult subject, but not some kind of dark magic) without giving you some examples. BUT, AI is very wide subject, it is not possible to give you one fit all example. Let examine three simple examples:

Playing Chess
One of the most simple way to write an AI to playing chess is Minimax algorithm. Minimax algorithm is about minimize the gain from your enemy and maximize your gain. First, we need to have a …

invisal 381 Search and Destroy

web hosting costs are over $5000/mo

Are you sure you spend $5000 per month for hosting? I am running a website with as much as traffic as Daniweb (if not more) and it costs around $300 per month.

  • We are storing our images in DreamObjects. Have over 3 million of images (around 300gb). Then using Cloudflare to cache the images to reduce the bandwidth costs. It costs roughly $30. 7 terrabytes of bandwidth for image per month.

    Screen_Shot_2015-12-22_at_8.19_.29_PM_.png
    (This is bandwidth of our image server only)

  • We are using 8 servers from DigitalOcean. Some are $10 server, some are $20 server. some are $80 servers. It costs around $300. Our database is not big. It is around 3gb of data. 3 terrabyte of bandwidth per month.

    Screen_Shot_2015-12-22_at_8.28_.22_PM_.png

jkon commented: for sharing data and prices +0
invisal 381 Search and Destroy

You can use Fermat Test. It has high probability of getting the right answer. We know that if a^(n-1) mod n != 1, then n must be a composite number.

def ModPowerRecursive(a, p, m):
    if p == 0:
        return 1
    elif p % 2 == 0:
        return (ModPowerRecursive(a, p >> 1, m) ** 2) % m
    else:
        return (a * ModPowerRecursive(a, p - 1, m)) % m

def FermatPrimeTest(n):
    if n == 1:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False

return ModPowerRecursive(2, n - 1, n) == 1

Testing 100+ digits prime

 Fermat(18532395500947174450709383384936679868383424444311405679463280782405796233163977)
 # return True (in less than second)

Noted again that, this algorithm does not guarantee to give the right answer, but the chance of getting the wrong answer is very slim. For number below 100,000, there is 0.078% chance of getting wrong answer. For number below 1,000,000, there is 0.024% chance of getting wrong answer. As number grow, the chance is getting slimmer and slimmer.

invisal 381 Search and Destroy

How large is your prime number? The fastest way (if not the fastest) to determine if N is a prime number is to have a pre-calculated of all prime number below sqrt(N). Then, it takes only O(sqrt(N)/ln(sqrt(N))) to determine the prime by mod with all prime below sqrt(N).

For example, if you have 10 digits number, it will take at most 10k mod operation which is pretty fast.

rubberman commented: Pretty much what I said, just clearer! :-) +13
invisal 381 Search and Destroy

Not entirely suprirsed that you got this result. You skip the loop as soon as found a collision

        if(birthdays.contains(randomBirthday))
        {
            collisionCount++;
            break; // break from the test as soon as you found the collision
        }

and to be honest, your logic is a mess. Even after you fix this bug, you will still get the wrong answer. I think what you truly want to do is something like this

  public static void main(String[] args)
  {
       // Do 100,000 tests on 10 persons.
       System.out.println(birthDayExperiment(10, 100000));
  }

  public static float birthDayExperiment(int person, int test)
  {
      int count = 0;
      int j = test;

      while(--j >= 0) {
          Random random = new Random();
          Set<Integer> birthdays = new HashSet<>(365);

          for(int i = 0; i < person; i++) {
             int tmp = random.nextInt(365);
             if (birthdays.contains(tmp)) { count++; break; }
             birthdays.add(tmp);
          } 
      }

      return (float)count / (float)test;
   }
invisal 381 Search and Destroy

You can use dictionary to simplify your code a bit

dict = {
    "t": 1, "f": 1, "c": 1,
    "b": 2, "h": 2, "y": 2,
    "q": 3, "w": 3, "z": 3
}

value = 0
word1 = input("Please enter a word:")

for letter in word1:
    value += dict.get(letter, 0)

print(value)

and if you want to be even shorter

dict = {
    "t": 1, "f": 1, "c": 1,
    "b": 2, "h": 2, "y": 2,
    "q": 3, "w": 3, "z": 3
}

word1 = input("Please enter a word:")
value = sum([dict.get(x,0) for x in word1])

print(value)
Gribouillis commented: pythonic code +14
invisal 381 Search and Destroy

You can use Cloudflare. It is free and easy to deploy. Just let it manage your DNS and it will act as a wall between your website server and visitors. Visitors will access to Cloudflare nearest server and Cloudflare will fetch the content of your website and cache (static content).

invisal 381 Search and Destroy

How come this discuss turn into a flame war. First of all, there is no different between the sub-forum and tag system based. A single tag equals to a sub-forum. Tag system allows a single question to belong to to multiple sub-forum. Therefore, tag system provides more flexiblity. Many energy has been invested to transform a sub-forum system into tag system, it is plain stupid to reverse back to old system.

However, I still believe that the current design of Daniweb is not yet optimal for newcomer and it is somthing we should discuss.

invisal 381 Search and Destroy

A year ago, I also wrote an article about using only bits to representing the TicTacToe. It might be irrelevant to this question, but I think it is nice to share here for those who interests.

Using Bits for TicTacToe

Using bits to represent a Tic-Tac-Toe board is perfectly fine and is as easy and maintainable as using two dimensional array. Since there are only 8 possibilities for winning condition, you can just check the board against every cases.

1 0 0       0 1 0      0 0 1     1 1 1    0 0 0
1 0 0       0 1 0      0 0 1     0 0 0    1 1 1
1 0 0       0 1 0      0 0 1     0 0 0    0 0 0

0 0 0       1 0 0      0 0 1
0 0 0       0 1 0      0 1 0
1 1 1       0 0 1      1 0 0

To keep the clean-ness of the code, try to abstract the implementation of the board away from the your game logic. It is easier to change the board implementation later if you dislike the bitboard representation.

class Board
{
    private:
        uint32_t board;

    public:
        Board() { board = 0; }

        /* Check if there is any of our piece
           placed in this (x, y) location */
        bool Check(int x, int y) {
            return (board & (1 << y * 3 + x)) > 0;
        }

        /* Make a move in this (x, y) location */
        void Move(int
invisal 381 Search and Destroy

That's a people problem, not a Daniweb problem. I don't think Daniweb should pander to the laziest of the lazy.

I am speechless. You should know that Daniweb is a business. The greatest asset of business like Daniweb is visitor. If visitor has problem, the website will have problem. Believe it or not, we have more dumb and lazy people than smart people in this world.

I don't know anyone who hasn't bookmarked a site or two (dozen) in their browser of choice. If a site is important enough to return to then it is usually bookmarked. Again, if you are too lazy to press CTRL-D (or whatever to bookmark) then I suggest you just stop using the internet altogether. Or do you type all of the addresses you visit in by hand every time you go there?

There are two problems with your suggestion.

  • What you suggest is not to only bookmark the site, but to bookmark the address of each tag that you frequently use.
  • Maybe they will bookmark the site, if the site is important. But, at first, you need to show them that the site has what they want.

In Stackoverflow, they have option for you to specified which one is your favorite tag and it is in the front page. You can basically click on it to quickly go to your section. Why do I have to bookmark every tag that I want? Why do I have to type "javascript" …

invisal 381 Search and Destroy

Allow me to share from my experience of running a few websites which probably has more visitor than Daniweb (based on Alexa). The different between my website and Daniweb is that Daniweb aims for tech-kind of guy. My website provides content to everyone in our local language. We are poor country and majority even have hard time knowing how to type a website address and adding a bookmark is like a rocket science to them. So, whenever we make a design, we always follow this principal:

  • Anything that is used often must be big and one or a few click away. Anything that is rarely use should be small. Anything that almost noone use should be removed. We have introduced a lot of features, but also remove a lot of features if not successful. It is a burden to keep maintain something that does not work.

So, here is my response to @Reverend Jim

So many programs are using the hamburger/waffle icon that its function should be obvious by now.

It is obvious for you because you have been loyal to Daniweb for so long. You are very smart person and most of the contributors here are pretty smart so I bet they know how to get thing done. However, Daniweb heavily rely on beginner to ask question so that you smart people can help. These guy usually are not loyal to Daniweb. If they cannot find what they want in 1 minute when they hit the …

invisal 381 Search and Destroy

It is better to understand how the HTTP Cookie works.

When your browser open a website, you send a HTTP request to the server. The HTTP request looks like this.

GET /index.php HTTP/1.1
Host: www.example.org

The request message tell server that you are requesting www.example.org (in case, a single server hosts multiple domain, telling which domain to access will help server decide which content to serve) and tell which page you want to request.

HTTP/1.1 200 OK
Content-Length: 17
Content-type: text/html
Set-Cookie: some_cookie=some_value

HTML Content HERE

The server will response back HTTP/1.1 200 OK that's mean the page you are trying to request exists. Optionally, the server may send Set-Cookie: .... to tell browser that you need to store the following cookie value into your browser for this domain.

The NEXT TIME, the browser request again to any page of this domain, it will send the whole cookie to the server.

GET /test.php HTTP/1.1
Host: www.example.org
Cookie: some_cookie=some_value

Browser HAVE obilgation to send all the cookie to the server, but browser does not have obilgation to send localStorage information to server. The rule of thumb is that if data that you want to set is not neccessary important for server to have it, store it in localStorage because have too much cookie consume unneccessary bandwidth.

Interestingly, when you use session_start(), the PHP will attempt to read if browser has session id in the cookie, if there is no session id in the cookie, it will generate a …

cereal commented: well explained +13
Aeonix commented: So, IT IS sent by HTTP!! +4
invisal 381 Search and Destroy

Why don't you do something like this?

 for($i = 0; $i < count($response); $i++) {
     $ph[$response[$i]] = array('quantity' => $iteminfo[$i][1]);
 }
James_43 commented: Ah, that's awesome. THanks so much! +2
invisal 381 Search and Destroy

Nice try. The reason that your code does not properly work is because when you delete a item in the list, you are decreasing the index of all the higher index by one then you increase the searching index by one also. So, you will skip some elements.

To solve this, you need to do it the reverse order.

l1 = [4,9,2,6]
l2 = [3,9,4,5]

i = len(l1) - 1
while(i >= 0):
    j = len(l2) - 1
    while(j >= 0):
        if (l1[i] == l2[j]):
            del(l1[i])
            del(l2[j])
        j -= 1
    i -= 1

print(l1)
print(l2)

However, there is still flaw in this code. For example, [9, 9, 1] and [2, 9]. The first list has more number 9 than the second list. The above code will only remove one 9. There is slightly better way to do this using dictionary to decide which number is duplicated in both list and remove later.

l1 = [4,9,9,2,6]
l2 = [3,9,4,5]
d = {}

for x in l1:
    d[x] = d.get(x, 0) | 1

for x in l2:
    d[x] = d.get(x, 0) | 2

l1 = [x for x in l1 if d.get(x,0) != 3]
l2 = [x for x in l2 if d.get(x,0) != 3]

print(l1)
print(l2)
homeboy commented: Thank you for the quick replay. I learn something new from you (using dictionary) +0
invisal 381 Search and Destroy

.... in a constant loop ...

Do you mean you want to put all of those code in an infinite loop? You can use while True:. First, you indent all of your code print('What would you like to do?') and below. Then add the while loop above it. So it should look like this

 while True:
    print('What would you like to do?')
    ## --- all the code below the above code

Indentation is one of the thing that I hate the most in Python. It usually force you to care about this little detail. Usually, it is terrible bad because you need to be consistence with your indentation (use 2 space? 3 space? or tab?). By the way, enjoy your journey to mastering Python ^^

invisal 381 Search and Destroy

(I was meant to post this as comment, but because it is too long so I will make a reply)

To be precise, tail recursion optimization is the process of defining recursive code that can be efficiently turn to iterative code. So in theory, the recursive binary search takes O(log(n)) memory. In practice, some compilers are smart enough to turn the recursive binary search to iterative binary search.

JamesCherrill commented: OK, yes. +15
noobjavacoder commented: I though tail recursion is not allowed in java. Am i correct? +0
invisal 381 Search and Destroy

Change it to

import os
answer = raw_input('Ready for shutdown, continue?')
if answer == 'Yes':
     os.system("shutdown -s -t 0")

First of all, you are trying to ask for two inputs and check whether the two input are the same. What you want to do is getting only one input and check if the input is a string "Yes".

Secondly, Indentation in Python has meaning. Anything inside the condition must be one indentation depth than the condition code.

invisal 381 Search and Destroy

First question, is there any difference between binary search and recursive binary search?

Iterative binary search and recursive binary search are same algorithm with different choice of implementation.

so does it mean for 2nd function it will be low of 4, high of 9 and then mid of 6...?

No, the low would be 5 and high would be 9. Why would you want to include the 4th element in the list while you have already confirm that it is not what you are searching for.

Noted that, iterative binary search usually is faster and more memory efficient. The iterative run in O(log(n)) and use O(1) memory. While, the recursive one run in O(log(n)) and use O(log(n)) memory because you keep push high and low into the stack.

invisal 381 Search and Destroy

Capture2.PNG

It would be nice to allow user to resize the height of the editor. It is terrible experience to write a long post with current editor height.

diafol commented: Good point. It used to sometime in the past. +0
cereal commented: would be nice +0
invisal 381 Search and Destroy

Welcome to Daniweb, let me completely guide you to creating the most basic HangMan game using VB.NET in Console Application. Then, you can apply the basic principle to your Hangman project in WinForm.

First of all, we started with the empty VB.NET console project.

Sub Main()
End Sub
GameLoop

You need to create a game loop, setting up all the possible words, and determine the maximum number of attempt that player can guess. The game loop will simply keep asking if the player want to continue playing our game.

Const MaxNumberOfAttempt As Integer = 10
Dim Words As String() = {"LOVE", "DANIWEB", "PROGRAMMING"}

Sub Main()
    Do
        Game()
        Console.WriteLine("Press 'y' and enter to continue")
    Loop Until Console.ReadLine() <> "y"
End Sub

Sub Game()
End Sub
Game

In this section, we will focus on what inside our Game() function.

Sub Game()
End Sub

First of all, we need to pick one word out of our word list.

Sub Game()
    '' Picking one word from our possible word list
    Dim HiddenWord As String = Words(New Random().Next(0, Words.Length - 1))
End Sub

Then, we have create another variable to hold the correct letters that player has guess in our hidden word. At first, our player hasn't guess any letter. Therefore, all the letter is hidden. For example, if our hidden word is "DANIWEB", the initial correct guess is "-------".

 Sub Game()
    '' Picking one word from our possible word list
    Dim HiddenWord As String = Words(New Random().Next(0, Words.Length -
ddanbe commented: Good one! +15
invisal 381 Search and Destroy

I joined DaniWeb ten years ago when I was just a beginner programmer and it was probably the golden age of DaniWeb. In that time, I felt that DaniWeb was the most modern and most innovative forum among all the forums on the internet. The design was top-notch (the current design is still top-notch), running the best customized vBulletin, and with great people. Before, I went inactive six year ago, my reputation rank was around 120. Six year later, my rank barely dropped and that indicates that during these six year Daniweb is mess up.

What I have noticed during the past six years is that Daniweb stop innovating and stop trying to be unqiue. Daniweb keep playing a catch-up game and trying to compete with everyone. Nowaday, Daniweb is like a little bit of everything: a little bit of question and answer website, a little of social media, a little of forum, and a little of blog. Daniweb does not have its own landscape, but trying hard to steal a bit of other landscape.

The big question should be what direction should Daniweb go and where should be our territory.

invisal 381 Search and Destroy
  1. For developing productive software
  2. For learning (learning C++ language, implementing algorithms and data structures) or solving fun programming problem.
  3. I don't use it

___________________________________________________________________________

NOTE
I haven't been in Daniweb for years and there are so many changes that I don't even know how to create a poll (or maybe this feature has been removed).

Reason

A few days ago, I am starting developing a small open-source portable C++ IDE for fun. My aim is not to compete with any other IDE in term of rich-features. Instead, I focus on simple interface, easy to use, and good for educational purpose. One of our main feature is that it is easy to get C++ code running (no need to creating new project, no need to save the file before able to compile and run, just write code and press F5). So, the reason behind this post is to measure my potential audiences which is people who casually use C++ for doing small thing.

invisal 381 Search and Destroy

It seem like you put free(array); in the loop instead of outside of the loop.

invisal 381 Search and Destroy

I did not mean assign a variable to Nothing does not help anything. There is thing called Garbage Collector which clear unused memory. If particular memory address proved to be unused (probably no variable hold its address anymore), then it will free the memory. However, in your example, it does not help because that string you want to free is a constant and it's always needed.

codeorder commented: Garbage Collector?; forgot about it, hobbyist and all.thanx. :) +12
invisal 381 Search and Destroy

yes C++ really faster than VB.NET

I don't think you get my idea. Not everything written in C++ is faster then VB.NET. If C++ program is using the wrong algorithm for the problem, VB.NET that using the right algorithm will perform better.

your application need to inject .NET code at runtime (which C++ don't need to)

Indeed, C++ program is translated into native code, so do .NET program. The process of .NET gone like this:

  1. Every .NET program is compiled into CIL(Common Intermediate Language)
  2. When .NET program is run, CIL code will get translated into native code (through Just-In-Time Compiler)
  3. Then native code is executed.

The end result is the same which is in NATIVE CODE. To me, the reason that .NET program run slower because of garbage collector and other managed libraries. However, for safer program, there should be a trade-off.

So what is my point? My point is that VB.NET beginner programmer most of time will produce a faster program than C++ beginner programmer, because VB.NET beginner will use right tool provided my .NET libraries which is a wrapper of good implemented native code. Moreover, VB.NET beginner probably tend to make less optimization mistake. For example:

VB.NET version

Private Function IsPrime(ByVal n As Long) As Boolean
        For i As Integer = 2 To Math.Sqrt(n)
            If n Mod i = 0 Then
                Return False
            End If
        Next

        Return True
    End Function

C++ version assuming compiling with no compiler optimization

bool IsPrime(long
invisal 381 Search and Destroy

Not everything programmed in C++ is faster than VB.NET. It is just matter of using the right data structure and the right algorithm for your problem.

M.Waqas Aslam commented: nice +1
invisal 381 Search and Destroy

Introduction[INDENT]
Since this is my first thread in VB.NET forum(most of the time, I was in C/C++ forum), I want to share something that you might find it useful with your school project or with your works.

Button is already a MUST-HAVE element in every program (I couldn't imagine program without a single button would function). Because it is everywhere, its appearance affects your form's appearance greatly. Some people might not care about how their software looks, but to me, it is a very important aspect for my software.

NOTE: I am pretty new to VB.NET myself. If there is any mistake, please correct me.
[/INDENT]

Step 1: Creating UserControl and Essential Properties[INDENT]Creating UserControl into your project. Then imports the following:

Imports System.ComponentModel
Imports System.Windows.Forms
There are four important properties that you need.BackColor ForeColor Text BorderColor Because UserControl already has BackColor and ForeColor properties, you only need to construct Text and BorderColor properties Private _BorderColor As Color '' Button Border Color Public Property BorderColor() As Color Get Return _BorderColor End Get Set(ByVal value As Color) _BorderColor = value '' Force your control to re-draw itself '' in order to update the new border color Me.Invalidate() End Set End Property <EditorBrowsable(EditorBrowsableState.Always)> _ <Browsable(True)> _ Public Overrides Property Text() As String Get Return MyBase.Text End Get Set(ByVal value As String) MyBase.Text = value '' Force your control to re-draw itself '' in order to update the new inputted text Me.Invalidate() End Set End Property

[/INDENT]
Step 2: Drawing the …

kvprajapati commented: Welcome! Informative tutorial. +12
invisal 381 Search and Destroy

with 100% accuracy unlike some algorithms

There is no any square root algorithm that guarantee a 100% accurate result. For example: Let's say what is 100% accurate result of square root of 2?

greatest algorithm invented for calculating square roots?

Fast inverse square root is still one of amazing algorithm I have seen so far.

Anyway, still it is nice to see people try to invent something new.

invisal 381 Search and Destroy

The poster was 13 years old when he starter this thread. By now, he would be 18 years old. I don't know if he could hear your messages.

jonsca commented: Yes +4
invisal 381 Search and Destroy

}while ( restart = true ); will loop infinitely because the condition always is true. Change to }while ( restart == true );

invisal 381 Search and Destroy
invisal 381 Search and Destroy

then what is the purpise of this website?every time i post any question,it is considered as assignment

The purpose of this forum = (everything related to C++) minus (giving free homework's answer)

Salem commented: Nicely put +20
invisal 381 Search and Destroy

Uh? You meant: k = 84 * m / 2;

I think (168 * m) / 2 = 84 * m

AFAIK, k <<= 1; is the most efficient way to do a multiplication by two.

Shift left is slightly slower than addition operator in modern processor.

tux4life commented: Oops, yes, that's a stupid mistake from me :$ +8
invisal 381 Search and Destroy

I have recently started to write my own tiny little electronic-book. This e-book is not about teaching C++ from ground up, but it is a collection of C++ pieces that I have learnt during these past few years that I want to share with everyone. I call this e-book "C++: Random Pieces". It is still incomplete.

I decide to post my first draft, hoping to get constructive feedback and to bring meaningful discussion.

[B]NOTE:[/B] My English is very poor. If you find any grammatically mistake or you have better way of explain the point, please do not hesitate to correct. [B]NOTE:[/B]If you have any trick or useful information related to C++, do not hesitate to share. [B]NOTE:[/B]My programming knowledge is limited, if I have made any mistake, please spare my ignorance.

There will be around 20 to 25 C++ pieces that will be included in this e-book. I have finished the first 4 pieces so far. Firstly, I will post the first two pieces here.

The ICE Man commented: Nice Contributions :) +0
Nick Evan commented: Good thread. This might spark some interesting discussions :) +12
invisal 381 Search and Destroy
"select ORDER_DATE FROM ORDERS WHERE ORDER_NUM =" + num

You cannot simply combine a character string with an integer by simply use operator +. "select ORDER_DATE FROM ORDERS WHERE ORDER_NUM =" returns an address of where character string store and if you add num to that address, it cuts num numbers of beginner characters. For example:

int main()
{
    std::cout << "select ORDER_DATE FROM ORDERS WHERE ORDER_NUM =" + 3;
    // OUTPUT IS: ect ORDER_DATE FROM ORDERS WHERE ORDER_NUM =
    return 0;
}

One of the easiest way to solve your problem is to use string class and then ask user for string input rather than integer input. Then combine the input and the SQL query together.

string sqlQuery;
    
    cout << "Please enter a customer number: " << endl;
    cin >> sqlQuery;
    
    sqlQuery = "select ORDER_DATE FROM ORDERS WHERE ORDER_NUM = " + sqlQuery;
    query_state = mysql_query(&mysql, sqlQuery.c_str());

Don't forget to include #include <string> .

I hope this will help.

invisal 381 Search and Destroy

I suppose one way to do it would be to create an array of 101 characters, each array element represents the numeric grade. The use the grade to index into that array. For example

Or create an array of 11 characters

char grades[11] = {'J' ,'I', 'H' ,'G', 'F' ,'E','D', 'C', 'B', 'A', 'A'};

// now code to get grade
int score = 93;
char gr = grades[score/10];
invisal 381 Search and Destroy

For those who are lazy to search through internet here is the link: gets() vs fgets()

tux4life commented: Good link. +23
invisal 381 Search and Destroy

i want bankers algoritham

I am greatly disappointed.

Salem commented: But not entirely surprised ;) +36
invisal 381 Search and Destroy

this function will calculate a string formula which support cos, sin, log, abs, mod, and example : [10*2+(2+3)]/(5 mod 4) and you will get the answer, and this function it really easy to plugin with you code.

invisal 381 Search and Destroy

All your code do is assigning each element of your matrix to -1 and then display them. It is no surprise at all that you did not achieve the assignment because you haven't figured or aren't willing to figured the pattern. Everything in this world is patterned either simple or complex pattern. In your assignment, the pattern is pretty obvious.

-1  -1  -1  -1 -1  0
-1  -1  -1  -1  0  1
-1  -1  -1   0  1  1
-1  -1   0   1  1  1
-1   0   1   1  1  1
 0   1   1   1  1  1

If you look at the all -1 elements, you will see a triangle-pattern.

i=0       1       2      3     4
         ------------------------------
j=0     -1       -1      -1     -1     -1 
j=1     -1       -1      -1     -1 
j=2     -1       -1      -1
j=3     -1       -1 
j=4     -1

To assign all of -1 elements in your 6x6 matrix without using any loop, I need to do this:

matrix[0][0] = -1
matrix[0][1] = -1
matrix[0][2] = -1
matrix[0][3] = -1
matrix[0][4] = -1

matrix[1][0] = -1
matrix[1][1] = -1
matrix[1][2] = -1
matrix[1][3] = -1

matrix[2][0] = -1
matrix[2][1] = -1
matrix[2][2] = -1

matrix[3][0] = -1
matrix[3][1] = -1

matrix[4][0] = -1

But by assigning these -1 elements in your matrix with bare hand is pain in the ass, so I need to look for some pattern in what I have done with bare-hand

matrix[0][0] = -1
matrix[0][1] = -1
matrix[0][2] = -1
matrix[0][3] = -1
matrix[0][4] = -1
DdoubleD commented: Wow! Ok, I need some lottery numbers.... +1
mrnutty commented: Reps for the long post, probably took 32.15 min out of your life? +3
tux4life commented: Great post :) +21
invisal 381 Search and Destroy

1. Why create this function when you can simply compare two characters with operator ==.

int Check_Characters(char s1,char s2) {
    if(s1==s2)
        return 1;
    return 0;
}

2. You have made same mistake again like your last post. First, you assign num = i so that also mean num is equal to i . Then, you compare num and i which they will always equal to each other.

num=i;
            if(num==i)

3. x is always 0

Temp[x]=str[i];
invisal 381 Search and Destroy

Sorting concept is simple: from the least to the greatest or from the greatest to the least. To do so, you need to do comparison. So, the magic trick is comparison-rule (which is greater and which is lesser). For example: we got 5 points (consisting of x-axis and y-axis).

X, Y
Point-A   (5, 10)
Point-B   (4, 6)
Point-C   (6, 7)
Point-D   (5, 9)
Point-E   (4, 9)

And then I create my comparison-rule:

[B]If [/B] Point1.X is greater than Point2.X [B]then[/B]  Point1.X is greater than Point2
[B]If [/B] Point1.X is equal to Point2.X [B]then[/B] 
   | [B]If[/B] Point1.Y is greater than Point2.Y  [B]then[/B] Point1 is great than Point2
   | [B]If[/B] Point1.Y is lesser than Point2.Y  [B]then[/B] Point1 is lesser than Point2
[B]If [/B] Point1.X is lesser than Point2.X [B]then[/B]  Point1.X is lesser than Point2

Using this comparison with some comparison-process. I have finally sorted my points.

[B]Result after sort[/B]
           X, Y
Point-C   (6, 7)
Point-A   (5, 10)
Point-D   (5, 9)
Point-E   (4, 9)
Point-B   (4, 6)

Now, time to change my comparison-rule so that I would get difference result:

New comparison-rule:

[B]If[/B] Point1.X + Point1.Y > Point2.X + Point2.Y [B]Then[/B]  Point1 is greater than Point2
[B]Else[/B]  Point1 is lesser than Point2.

After do comparison-process with this new rule, I got difference result:

[B]Result after sort[/B]
           X, Y
Point-A   (5, 10)  // 5 + 10 = 15
Point-D   (5, 9)   // 5 + 9 = 14
Point-C   (6, 7)    // 6 + 7 = 13
Point-E   (4,
VernonDozier commented: Good explanations. +22
invisal 381 Search and Destroy

Here is your code and its logical error.

int RemoveChars(char *S,char c) {
    int i=0;
    int spaces=0;
    char temp;
    for(i=0;S[i]!=0;i++) {
        temp=S[i];
        if(S[i]!=c) {
            // temp = S[i] and S[i] = temp, Hence, S[i] = S[i]
            S[i]=temp; 
            putchar(temp);
        }
        else
            spaces++;
    }
    return spaces;
}

So basically, the reason why putchar(temp); works is because you avoid printing character that you want to remove into the screen. However, your string that store in the memory remain the same.

So, I made some correction to your code and it works perfectly, I guess.

int RemoveChars(char *S,char c) 
{
	int count=0; 
	int spaces = 0; 
	char* temp;
	// allocate enough memory to store new string after remove.
	for(int i=0; S[i] != 0; i++) {
		if (S[i]==c)
			spaces++;
		else
			count++;
	}
	temp = (char*)malloc(count+1);

	// write new string without character you want to remove
	for(int j=0, i=0; S[i] != '\0'; i++) {
		if (S[i]!=c) 
			temp[j++] = S[i];
	}
	temp[count] = '\0'; // end string

	strcpy(S, temp); // copy new string to old string
	free(temp); // de-allocate new string memory.

	return spaces;
}
yellowSnow commented: good little answer +2
invisal 381 Search and Destroy

If you truly understand the concept of doubly-linked list, these problems would be very easy. Lets start with basic doubly-linked list concept. Doubly-linked list data structure consist of 3 important components: set of data, pointer to address of previous data (*prev), and pointer to address of next data (*next). When you learn linked-list, you will often heard the term "node". Node is simply just a record.

NULL <---  [*prev|[B]data[/B]|*next] <---> [*prev|[B]data2[/B]|*next] <--> [*prev|[B]data3[/B]|*next] --> NULL

Let say that we have kth nodes and we want to display all of data out into the screen. Assuming plist is the address of our first node.

while (plist != NULL) {
    std::cout << plist->data;
    plist = plist->next;
}

To count total nodes, to count nodes that have even or odd data value, or to print backward also use this technique except with some extra conditions.

To add new node in, no matter at what position it will be inserted in (at beginning, at middle, or at the end), you need to allocate memory location to store new node and assign proper *next and *prev address. For example, you want to insert new node at the end of your list. To do so, you need to know the address of your last node. Then, assign the *prev of the new node to the address of the last node and then *next of the new node point to NULL which to determine that it is the end of the list. Then *next …

Hiroshe commented: Consider posting this as a tutorial! +4
invisal 381 Search and Destroy

ya and who wrote that? It doesn't sound like a professional environmental assessment to me.

I have provided the link to you. If you are curious where is that come from, you can check the references of that article. Anyway, I just share what I have came across so I don't dare to make any comparision to other sources of engery.

cwarn23 commented: I agree and nice person to talk to on IRC +0
invisal 381 Search and Destroy

By the looks of it, you're supposed to manually manage the numbers. Edward's first attempt would probably use strings to store the numbers and then handle the arithmetic just like it's taught in elementary school with digit by digit calculations and saving of the carry or borrow values.

That's the simple and easy to write solution, but it's not optimal in terms of speed or memory footprint.

Do as what Edward has said and you will able to solve your problem easily. You don't actually need integer to store number, you can just use string to represent the number. First of all, you create one string to store the input which is in the format you have mentioned before:

first_number[+ or -]second_number

Then create 2 other strings: the first string stores the first number, and the second string stores the second number. Then calculate it like what you have taught in your elementary school.

For example:

[B]User's Input:  162823+562369[/B]
-> First String = 162823
-> Second String = 562369

Calculate it manaully like you would calculate by hand.

 1     1   1
 1 6 2 8 2 3  
                         +
 5 6 2 3 6 9
---------------
 7 2 5 1 9 2
scream2ice commented: great explanation...cheers +1
invisal 381 Search and Destroy

You might wonder why your problem hasn't been answered. It is obvious that you haven't use the code tag which make it very unfriendly to read your code. I recommend you to tag your code and post your error messages.

Here is the key of having a successful question: (if you follow this guide correctly, I am sure that many people will answer your question)

Describe your problem clearly and fully!

So you have a great title and you're ready to compose a post. Resist the temptation to copy and paste your code and as an afterthought say "It doesn't work". That's not a description of the problem. If you want help, you have to give us enough information to work with. Include at least all of the following in your description of the problem:

1) An overview of what your program does.
2) The result of your current code.
3) What you expected your code to do.
4) The contents of any input files (if appropriate)

This tells us what context your program is in so that we can offer alternative solutions. It tells us exactly what your code does so that we can more easily pinpoint the problem without performing tedious troubleshooting steps. Finally, it tells us what you wanted your code to do so that we can compare what it does with what you wanted it to do. Most of the time, a knowledgeable member can answer your question almost immediately using just …

Salem commented: Absolutely! No code tags == ignored code +19
invisal 381 Search and Destroy

Text-based Role-Playing Game Project (For Beginners)
Firstly, this game will start with an introductatory storyline of the game to attract player interest. Then, it asks a player to enter his or her name and which class the player want to choose. There are going to be 3 classes for player: Warrior, Mage and Archer. Each class has it own unique abilities.

Class System

  • Warrior:

    Having the high hitpoint and equip with heavy weapons and armors.
    Starting State:

    • Hitpoint: 50 (increased by 10+level*7 for each level)
    • Mana: 10 (increased by 1.25*level for each level)
    • Attack: 20 - 25 (increased by 2*level for each level)

    Skill:

    • Evading: (Passive)
      • Level 1: Raise Defense level by 10%. If a shield is not equipped, the effect will decrease by half.
      • Level 2: Raise Defense level by 15%. If a shield is not equipped, the effect will decrease by half
      • Level 3: Raise Defense level by 25%. If a shield is not equipped, the effect will decrease by half
    • Sword Dance: (Active)
      • Level 1: Swinging your sword rapidly cause the target to get hitted 2 times. (cost 5 mana)
      • Level 2: Swinging your sword rapidly cause the target to get hitted 3 times. (cost 8 mana)
      • Level 3: Swinging your sword rapidly cause the target to get hitted 4 times. (cost 12 mana)
    • Shock Stun: (Active)
      • Level 1: Concentrate all your energy force into your weapon and hit hardly to the target cause them unable to move in the next turn …
Alex Edwards commented: Nice post man =) +2
23.12.2012 commented: This will keep me busy for some days :) Thanks a lot, it's a nice quest +1