invisal 381 Search and Destroy

There is another way which is even simpler than my last approach. Since random.random() generates number between 0 to 1. If we square it, it will getting smaller. Hence, the lower value will have more chance.

def rand2(n):
    r = random.random()
    r = r * r
    return round(r * n)

The result of rand(5) after 100,000 attempts

0 = 0.31604   (31%) 
1 = 0.2316    (23%)
2 = 0.15841   (15%)
3 = 0.12994   (12%)
4 = 0.11245   (11%)
5 = 0.05156   ( 5%)

If you want to increase the chance of the lower value even further you can do r = r * r * r. The result of rand(5) after 100,000 attempts

0 = 0.46415  (46%) 
1 = 0.20534  (20%)
2 = 0.12483  (12%)
3 = 0.093    ( 9%)
4 = 0.07767  ( 7%)
5 = 0.03501  ( 3%)
invisal 381 Search and Destroy

I believe that computer can quickly calculate square root. Just using Taylor Series or Newton Raphson. These two method is cheap if you don't want too accurate result of the square root. I heard most of GPU has a built-in inverse square root (which can be done in single instruction).

invisal 381 Search and Destroy

Your probability doesn't seem to be correct. Let rework it a bit. We want to random from 0 to n. Let a be the value between 0 to n. The probability of P(a) = 2 * (a + 1) / (n + 1)(n + 2). This way, the sum of P(a) where a from 0 to n will be equal to 1. However, this definition gives higher chance for largeer value (but we can easily reverse the definition to fit your need).

Firstly, we random number between k = 0 to (n+1)(n+2)/2 - 1. Then, we try to find which value should k belong. For example, n = 4 if k is 11 then value is 4.

   k: 0 | 1 2 | 3 4 5 | 6 7 8 9 | 10 11 12 13 14
   v: 0   1     2       3         4

You can easily find the v = ceil( (sqrt(1+8*k)-3)/2 ).

Code in Python:

from random import randint
import math

def rand(n):
    limit = ((n + 2) * (n + 1)) / 2
    r = randint(0, limit-1)
    return math.ceil( ( (1 + 8 * r)**0.5 - 3 ) / 2 )

Here is the probabiliy for rand(5) after 100,000 tried.

0 = 0.04974   ( 4%) 
1 = 0.09431   ( 9%)
2 = 0.14168   (14%)
3 = 0.1887    (18%)
4 = 0.23739   (23%)
5 = 0.28818   (28%)
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

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

Let focus on this line and its error message

  $response[] = array('quantity' => $itemsinfo['qty']);  
  // [] operator cannot be applied to string

First of all, there are two [] in this line. The $response[] and $itemsinfo['qty']. However, I don't think it is $itemsinfo because even if $itemsinfo is a string, the $itemsinfo['qty'] still is a valid syntax. Therefore, the problem is that $response is a string. Therefore, applying the $response[] = something; is not a valid syntax. In my computer, the error message will be "[] is not supported for string" which is very similiar to your error message.

negitron commented: oi invisal, i dont like you +0
cereal commented: +1 +13
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

Maybe you can try to play around with ProjectEuler problems. Each problem is fun to solve and you will learn how to optimize your code by looking at other people approach.

invisal 381 Search and Destroy

The explanation is that in the first syntax the number of rows has to be calculated in every loop, while in the second it doesn't.

The second does not run faster. In VB.NET, For Loop does pre-calculate for us. For example:

Dim ending As Integer = 10
Dim count As Integer = 0

For i As Integer = 0 To ending
   ending = 1
   count += 1
Next

Msgbox(count)

It will run from 0 to 10 even though you change the ending to 1. Unlike C++. That's why I said that C++ beginner programmer will more likely to make more mistake.

invisal 381 Search and Destroy

Naming your variable (long or short) does not affect the performance because once it is compiler, it will be just a piece of memory address.

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

.NET provide a flexible way to organize your data and print by using PrintDocument. The following is the "Hello World" example of using PrintDocument.

Dim WithEvents pd As New System.Drawing.Printing.PrintDocument

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        pd.Print()
    End Sub

    Private Sub pd_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles pd.PrintPage
        e.Graphics.DrawString("Hello World", Me.Font, Brushes.Black, 0, 0)
    End Sub
invisal 381 Search and Destroy

You can use variable to check whether you can find matched string or not in your search process.

Dim isFound As Boolean = False

For Each intCount In myArray
   If intCount = myString2 Then
      isFound = True
      Exit For
   End If
Next

If isFound Then
   Msgbox("Found.")
Else
   Msgbox("Not found.")
End If
invisal 381 Search and Destroy

Maybe this is the simplest thing ever but i'm a beginner trying to learn at least 1 language.
How come the Script below keeps displaying the Else message until it finds the string? I was expecting for it to display 1 single Box whether it was found or not? why does it keep itterating through the Else condition?

Dim myArray,myString,myString2,intCount

myString = "my;string;question;hope;you;can;answer"
myString2 = "question"

myArray = split(myString,";")

For Each intCount In myArray
If intCount = myString2 Then
msgBox("String Found!!")
Else
msgBox("Sorry, String Not Found")
End If
Next

I am totally expecting it to behave like that. The process will go like this.

  1. Compare intCount, which is "my" to "question". It is not equal, then show "Sorry, String Not Found".
  2. Compare intCount, which is "string" to "question". It is not equal, then show "Sorry, String Not Found".
  3. Compare intCount, which is "question" to "question". It is equal, then show "String Found!!".

The process will go on until you loop through all the element in myArray.

invisal 381 Search and Destroy

I have made picture viewer in VB which also shows all the pics present in a folder as thumbnails using image list and listbox. The problem is whenever the user clicks refresh it takes long time for the image to load. I want to some how make a cache like thing where i can store the image for faster access in the future.

Simple Approach

Here is how I would approach the problem. Firstly, I will build a custom control to display the thumbnails of a given directory path. Then, I create a DirectoryPath property which I can tell my control to list all pictures in that directory in thumbnails.

Dim memDirectoryPath As String = ""
Dim memFile As New List(Of IO.FileInfo)
Dim memThumbnail As New List(Of Image)

Public Property DirectoryPath() As String
        Get
            Return memDirectoryPath
        End Get
        Set(ByVal value As String)
            memDirectoryPath = value
        End Set
End Property

Then I want to construct list of files and list of thumbnails in given directory whenever the directory is assigned.

Public Property DirectoryPath() As String
        Get
            Return memDirectoryPath
        End Get
        Set(ByVal value As String)
            memDirectoryPath = value

            '' Clear the old list of file and thumbnail
            memFile.Clear()
            memThumbnail.Clear()

            '' Construct list of file and its thumbnail
            For Each file As IO.FileInfo In (New IO.DirectoryInfo(value)).GetFiles()
                memFile.Add(file)
                memThumbnail.Add(Nothing)
            Next
        End Set
End Property

Notice that I add Nothing as a thumbnail which actually is not the thumbnail of the file. Assuming that the directory contains a thousand of images. Constructing …

invisal 381 Search and Destroy

@WaltP: It is better, because that's what is the standard:

From Bjarne's FAQ: http://www2.research.att.com/~bs/bs_faq2.html#void-main

I don't see anywhere stated that int main(int argc, char* argv[]) is better than int main() .

I wonder whether char main() is acceptable?

invisal 381 Search and Destroy

I just woke up, so I didn't see that there is some logical mistake in there. The while condition is always false because c is unassigned and it does not equal to 'Y' or 'y'. Try do while instead.

invisal 381 Search and Destroy

Try while (c == 'y' || c == 'Y') and if (c == 'n' || c == 'N')

invisal 381 Search and Destroy

Well, even it is possible, what is the use of it? will it be anything useful?

invisal 381 Search and Destroy

To me, learning English language is far more difficult than learning a programming language.

invisal 381 Search and Destroy

Learning programming is about solving problem not about asking for the exact answer.
firstPerson gave you a very big hint, now it is time for you to make effort to solve
this problem.

Good luck.

invisal 381 Search and Destroy

I have never been a fan of Big Oh estimation and I am pretty poor with it. Correct me if I am wrong.

1)
The execution time for the first exercise would be:
L(n) + L(n/2) + L(n/4) + L(n/8) + .... + L(n/n) approximately equal to 2n

invisal 381 Search and Destroy

NathanOliver, don't you think that condition is unnecessary?

invisal 381 Search and Destroy
invisal 381 Search and Destroy

Instead of closing old thread to prevent newbie and spammer to resurrecting dead ancient thread, we can give warning message to anyone who attempt to post in the old thread.

For example:
I come across an old thread in daniweb (which I forget to check the thread date). I feel so excited and I want to make a comment in that thread. So I click on "Reply" button.

Then, a warning message pop up and ask

This thread is ..... years old thread. 
Are you sure that you want you post in this thread?
[B]Yes[/B] - [B]No[/B]

Then, I have two options, if I click Yes, I will resume to post comment on that thread. If I click No, then I will discontinue to post comment.

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

Since, Narue has pointed how to delete the first occurrence of the selected value. I will show how to delete every occurrence of the selected value.

int i=0, j=0;

    while(i<length) {
        if (i > j) {
            arr[j] = arr[i];
        }

        if (arr[i] == key) {
            i++;
        } else {
            i++;
            j++;
        }
    }
invisal 381 Search and Destroy

Your isPrime function will return 0 for even-number and return 1 for odd-number because your loop always end at the first loop (because you always return a value at the first loop.)

Try this one instead:

int i;
for(i=2; i<(int)sqrt(n); i++) {
  if(n%i==0) return 0;
}
return 1;

You can also further optimize your code by:

int i;
int k = (int)sqrt(n);

for(i=2; i<k; i++) {
  if(n%i==0) return 0;
}
return 1;
invisal 381 Search and Destroy
int xMin = -10;
int xMax = 10;

double xData[xMax - xMin];

xData contains 20 elements starting from 0 to 19.

int counter = xMin;
for (counter; counter <=xMax; counter++) {

While counter runs from -10 to 10

invisal 381 Search and Destroy

If I am not wrong, it is logically correct.

invisal 381 Search and Destroy

You don't understand the code or the code does not work properly? It seem to work properly for me.

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

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

Thanks, but what about Disadvantage?

I have not seen any significant disadvantages of using control array except it slightly increase difficulty in managing your controls. Moreover, control array is not applicable in every program.

invisal 381 Search and Destroy

Control array simply is a group of control that share the same name, same type, and same event procedures that increase flexibility of Visual Basic 6:

  1. Being share the same name and same event procedures allows VB6 programmer to reduce the amount of code.
  2. Able to create new element to control array at run-time.
  3. Consuming less resource than creating multiple regular controls.
invisal 381 Search and Destroy

The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string

My bad :(

You are totally right.

invisal 381 Search and Destroy

You can't simply compare 2 strings with operator ==. There is a function in library <string> called strcmp().

Syntax:
   int strcmp(string1, string2)

Return:
   Return 1 if string1 > string2
   Return 0 if string1 == string2
   Return -1 if string1 < string2.
invisal 381 Search and Destroy

thanks i was using putchar as to debug output but if i did temp as char array would it work 2 ?

You can also use temp as char array, but you don't know how much element you need for your new string...

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

I am at my workplace right now, so I don't have any compiler to test. However, I see several things that could cause some errors.

Firstly, End=S+1; , it should be End = &S[i] + 1 Secondly, int i,temp; , you should initialize the variable temp. int i,temp=0;

invisal 381 Search and Destroy

Now that I don't really understand what you want for your *num. Here is what I understand before:

If I have string "Hello World", and my c is 'W'. so the *num would be 7 because letter 'W' is the 7th letter in the string. Is it what you want or do I understand incorrectly?

invisal 381 Search and Destroy

yah I just noticed it too that it start at 2nd character also but it wont solve the problem since every time the loop runs it will set again *num to 0 coz its not = to the character maybe i should replace the else with an if but it will be same problem too.

As I have mentioned before, your code keep reset the *num to 0. To solve this problem, you need to remove the code where you reset *num:

char *Strchr(char *String, char c, int *num) 
{
   *num = 0;
   while (*String != '\0') {
      (*num)++;
      if (*String == c)
          break;
      String++; 
  }
  return String;
}
invisal 381 Search and Destroy

no *string++ it increment the address of the string *++string increment each character inside

Sorry, I was mistaken about the increment (I was at workplace where there was no compiler to test). I'm surprised that:

*b++ and *++b get the value of the next address and also increase the address. While, (*b)++ and ++*b increase the value by one. It is small matter that I have not noticed before.

Even though you are correct on this one, but you still get small mistake from that line of code. while (*String++) / Instead of starting to compare each letter with variable c from the first letter of your string, you start with the second letter of your string since you increase the first letter address before you start to compare.

invisal 381 Search and Destroy

but while(*string++) is same as (*string!=0) since it will alawys return true till it finds 0 in the end which will encounter when string end

It is difference. Let start that you string "Name". The first character of the string is 'N'. so *string++ is 'O' and next time *string++ will become 'P', 'Q', 'R', 'S'..... 'Z'....

What you want is getting next letter of the string, not the increment of your first letter.

invisal 381 Search and Destroy

i thought if it doesnt find string it intilise it to 1 or ? does it keep incrementing while loop is running and each character it doesnt find it it keep reseting to 1 thats y it turned to 1 coz it got incremented 1 time ?if so how can i fix this ??

while(*String++) , you increase your first character value by one that mean that if your first character 'A' then it will loop from 'A' to 'Z', to character 255 and then to character 0 and to 'A' repeatedly till it match c. So, how can we loop from the beginning of the string to the end of the string. Simple, every string end with '\0' character. So you can simply fix it by:

while (*String != '\0') {
   .....
   String++; // increase address by one step, not value
}

To count the position of the character you want to find in the String, you should do this way:

while (*String != '\0') {
   num++;
   if (*String == c) {
       ...... // whatever you want to do
       break;
   }
   String++;
}
invisal 381 Search and Destroy

it just returns 1 not more than that for int *num for first function

How could *num go beyond 1 when your code does not allow it to go beyond that.

char *Strchr(char *String,char c,int *num) {
    char *ptr;//whish will be ptr to first stuff we found after that char
    while(*String++) {
        #ifdef DEBUG//if this is added i get weird results;
        *num++;
        printf("num is now %d",*num);//this is weird too when i try print the number it prints as address not number
        #endif
        if(*String==c) {
            ptr=String;
            break;
        }
        else {
            ptr='\0';
            [B]*num=0;[/B] // <--- you always reset your *num to 0
        }
    }
    return ptr;
}
invisal 381 Search and Destroy

kbhit() function is in conio.h library and conio.h is not a standard library which is not what Hiroshe want