473,508 Members | 2,489 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Project Euler 22 - What am I doing wrong?

26 New Member
So, a few days ago I decided to try Project Euler question #22. The question is:

Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.

What is the total of all the name scores in the file?


Now, I saved the file, and using the internets I found out that names.txt has 5163 names. Also, names.txt is formatted in the following manner: "John","George","Abe" etc. All in one line.
According to that, I built the following program:

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. void swap (int& x, int& y)
  8. {
  9.     int holder = x;
  10.  
  11.     x = y;
  12.     y = holder;
  13. }
  14.  
  15. int main()
  16. {
  17.     string namelist;
  18.     string temp;
  19.     int sum;
  20.     int counter = 0;
  21.     unsigned long long total = 0;
  22.     char alpha[26] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
  23.     int values[5163];
  24.  
  25.     ifstream names ("names.txt");
  26.  
  27.     if (names.is_open())
  28.         getline (names, namelist);
  29.  
  30.     names.close();
  31.  
  32.     for (long i = 0; i < namelist.length(); i += 3) //i += 3 to skip the commas and quotes
  33.     {
  34.         temp.clear();
  35.         sum = 0;
  36.  
  37.         while (namelist[i+1] != '"')    //Loop character by character
  38.         {
  39.             temp += namelist[i+1];   //Build the string from individual characters
  40.  
  41.             for (int k = 0; k < 26; k++)  //Loop through alphabet, compare, save the sum
  42.             {
  43.                 if (namelist[i+1] == alpha[k])
  44.                         sum += k + 1;
  45.             }
  46.  
  47.             i++;
  48.         }
  49.  
  50.         values[counter] = sum;   //Save the sum in the values array
  51.         counter++;
  52.     }
  53.  
  54.     for (int i = 0; i < 5163; i++)
  55.     {    
  56.         for (int j = i; j < 5163; j++)
  57.         {
  58.             if (values[j] < values[i])   //Sort numerically, not alphabetically, as we are looking for numerical values
  59.                 swap(values[j], values[i]);
  60.         }
  61.     }
  62.  
  63.     for (int i = 0; i < 5163; i++)
  64.         total += values[i] * (i + 1);  //Calculate the total
  65.  
  66.     cout << total << endl;
  67.  
  68.     return 0;
  69. }
The code runs very fast, no compile errors. Only one problem - I'm getting the wrong result. What I'm getting:
996321502

I'm running Ubuntu. Compile: g++ -Wall 22.cpp

After a day of headaches, I decided to give up on it. Just now I thought why not ask here, because I really don't want my mistake to repeat itself.

So what's wrong? And how could I avoid this mistake in the future?

Thanks!
Dec 2 '10 #1
4 4383
Banfa
9,065 Recognized Expert Moderator Expert
How do you know 996321502 is the wrong answer? Do you know the right answer?

Clearly you do not think int holds enough bits to hold the total, are you sure that on your platform long long has more bits than int?

Also from line 64 will the result of values[i] * (i + 1) fit in an int if values[i] and i are both large?

Sorting by numeric value of the name will not put the name into alphabetic order. For example Zoe (26 + 15 + 5 = 46) is alphabetically after Colin (53) but numerically before it.

Finally you are using C++ so why are you using arrays instead of vectors?
Dec 3 '10 #2
liams
26 New Member
Yeah, I have the right answer, and it's not what I got. The right answer is about 11 digits if I remember correctly, and long long can hold much more. In line 64, it must fit because the answer, as I said, is about 10/11 digits.

And about the sorting.. I think you're right. I really didn't think about such a case. Thanks for that, I'll rewrite my code.

I'm using arrays because I know how large each one is going to be, and handling arrays directly is faster than using vectors. I only use vectors when I'm uncertain about certain things like capacity, number of elements, and dynamic handling.

Thanks for your answer... I'll see if I can get the right answer now. Will edit when I finish.
Dec 3 '10 #3
Banfa
9,065 Recognized Expert Moderator Expert
It is a common myth that arrays are faster than vectors. Under optimisation they are more or less the same speed wise and obviously vectors have benefits from a memory management viewpoint.

That said if I know the required size I tend to use arrays but in this example I would do the following
  • Make the array alpha constant, it is never altered in the code and making it constant adds a little protection as well as highlighting this for future maintenance.
  • Make values a vector and then write a more general solution that didn't require knowing the number of names in the file in advance. In real life you rarely know this sort of quantity so writing the program like that makes it good practice.
Dec 3 '10 #4
liams
26 New Member
Thanks for the tips. But I'm really interested in how vectors can be more or less the same speed. I mean, arrays are approached directly and vectors are handled differently from what I understand. They're like manageable code, which should be making them slower since they are constantly checked for validity, and their size always changes. Doesn't all this make them slower?
Dec 5 '10 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

6
3622
by: What-a-Tool | last post by:
I'm going out out of my mind trying to get this to work with no luck. The error message I get is at the bottom. Can someone please tell me what I'm doing wrong here. I've tried this a million...
2
2697
by: Aaron Ackerman | last post by:
I cannot a row to this bound DataGrid to SAVE MY LIFE! I have tried everything and I am at a loss. The using goes into add mode with the add button adds his data then updates with the update...
3
1127
by: M O J O | last post by:
Hi, I have a little test project. I spin up a thread, lets it sleep for a second and then the thread makes a button visible ... or at least should make it visible, which it doesn't do. ...
0
1070
by: John Dann | last post by:
I have a program that needs to access a prewritten external data file that is supplied with the program. I want to place this data file in...
5
1529
by: Jeff | last post by:
ASP.NET 2.0 This code crashes. It generate this error: Value cannot be null. Parameter name: type I've created some custom web.config settings and this crash is related to accessing theme...
8
2056
by: watkinsdev | last post by:
Hi, I have created a mesh class in visual studio 6.0 c++. I can create a device, render objects and can edit the objects by for instancnce selecting a cluster of vertices and processing the...
0
1316
by: shapper | last post by:
Hello, I am creating a class with a control. I compiled the class and used it on an Asp.Net 2.0 web site page. I can see the begin and end tags of my control (<oland </ol>) but somehow the...
25
3757
by: jwrweatherley | last post by:
I'm pretty new to python, but am very happy with it. As well as using it at work I've been using it to solve various puzzles on the Project Euler site - http://projecteuler.net. So far it has not...
10
1773
by: DavidSeck.com | last post by:
Hi, I am working with the Facebook API right now, an I have kind of a problem, but I don't know what I am doing wrong. So I have a few arrays, f.ex.: User albums: array(2) {
8
3847
by: Mathismylove | last post by:
Hi. Im new to Java and attempted to increase my knowledge by working on Project Euler..I figured that If Im able to solve as many problems from the project as possible with Java I will get more...
0
7231
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7405
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7504
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5643
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5059
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4724
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3198
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1568
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
773
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.