1. Лучший говнокод

    В номинации:
    За время:
  2. Си / Говнокод #12379

    +135

    1. 001
    2. 002
    3. 003
    4. 004
    5. 005
    6. 006
    7. 007
    8. 008
    9. 009
    10. 010
    11. 011
    12. 012
    13. 013
    14. 014
    15. 015
    16. 016
    17. 017
    18. 018
    19. 019
    20. 020
    21. 021
    22. 022
    23. 023
    24. 024
    25. 025
    26. 026
    27. 027
    28. 028
    29. 029
    30. 030
    31. 031
    32. 032
    33. 033
    34. 034
    35. 035
    36. 036
    37. 037
    38. 038
    39. 039
    40. 040
    41. 041
    42. 042
    43. 043
    44. 044
    45. 045
    46. 046
    47. 047
    48. 048
    49. 049
    50. 050
    51. 051
    52. 052
    53. 053
    54. 054
    55. 055
    56. 056
    57. 057
    58. 058
    59. 059
    60. 060
    61. 061
    62. 062
    63. 063
    64. 064
    65. 065
    66. 066
    67. 067
    68. 068
    69. 069
    70. 070
    71. 071
    72. 072
    73. 073
    74. 074
    75. 075
    76. 076
    77. 077
    78. 078
    79. 079
    80. 080
    81. 081
    82. 082
    83. 083
    84. 084
    85. 085
    86. 086
    87. 087
    88. 088
    89. 089
    90. 090
    91. 091
    92. 092
    93. 093
    94. 094
    95. 095
    96. 096
    97. 097
    98. 098
    99. 099
    100. 100
    #include <stdio.h>
    #include <malloc.h>
    #include <sys/time.h>
    #include <pthread.h>
    
    #define MAXPRIME 10000001
    char sieve[MAXPRIME];
    
    typedef struct {
        int id, min, max, step;
        unsigned long long result;
    } Task;
    
    void primes() {
        printf("Searching prime numbers ...\n");
        sieve[0] = sieve[1] = 1;
        for (int i=2; i<MAXPRIME; i++)
            sieve[i] = 0;
        int i = 2;
        while (1) {
            while (i<MAXPRIME && sieve[i])
                i++;
            if (i >= MAXPRIME)
                break;
            for (int j=i*2; j<MAXPRIME; j+=i)
                sieve[j] = 1;
            i++;
        }
    }
    
    double utime() {
        struct timeval tv;
        gettimeofday(&tv, NULL);
        return tv.tv_sec + tv.tv_usec / 1000000.0;
    }
    
    unsigned long long calc(int thread, int min, int max, int step) {
        unsigned long long sum = 0;
        double start = utime();
        int nextshow = max+1;
        for (int n=max; n>=min; n-=step) {
            if (!sieve[n]) {
                sum += 1;
                continue;
            }
            if (n <= nextshow && n > min) {
                double elapsed = utime() - start, eta = elapsed/(max-n)*(n-min);
                printf("Thread %d: current=%d elapsed=%lfs eta=%lfh\n", thread, n, elapsed, eta/3600);
                nextshow = n < 10000 ? 0 : n - 10000;
            }
            int b;
            asm("movl %1, %%ecx\n"
                "1: dec %%ecx\n"
                "movl %%ecx, %%eax\n"
                "imull %%eax\n"
                "idivl %1\n"
                "cmpl %%ecx, %%edx\n"
                "jnz 1b\n"
                "movl %%ecx, %0"
                : "=g"(b)
                : "r"(n)
                : "%eax", "%ecx", "%edx");
            sum += b;
        }
        return sum;
    }
    
    void * thread(void *arg) {
        Task *task = arg;
        printf("Thread %d: working from %d to %d step %d\n", task->id, task->min, task->max, task->step);
        task->result = calc(task->id, task->min, task->max, task->step);
        printf("Thread %d: partial result is %llu\n", task->id, task->result);
        return NULL;
    }
    
    int main() {
        primes();
    
        int threads = 4;
        int max = 10000000;
        pthread_t tid[10];
        Task tasks[10];
    
        for (int i=0; i<threads; i++) {
            tasks[i].id = i;
            tasks[i].min = 1;
            tasks[i].max = max-i;
            tasks[i].step = threads;
            pthread_create(&tid[i], NULL, thread, &tasks[i]);
        }
    
        unsigned long long sum = 0;
        for (int i=0; i<threads; i++) {
            pthread_join(tid[i], NULL);
            sum += tasks[i].result;
        }
    
        printf("Result: %llu\n", sum);
        return 0;
    }

    Мое ужасное решение вот этой задачки: http://projecteuler.net/problem=407

    В день, когда математика упорно не желает вспоминаться...
    на помощь приходят брутальные и бессердечные ассемблер и мультитрединг.

    model name: Pentium(R) Dual-Core CPU E5400 @ 2.70GHz
    real 286m45.890s
    user 545m44.926s

    bormand, 01 Января 2013

    Комментарии (47)
  3. Си / Говнокод #12351

    +135

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    83. 83
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #define MAXSIZE 512
    
    typedef struct word
    {
    	char wordBody[MAXSIZE];
    	int count;
    	struct word* next;
    } Word;
    
    Word* alloc(char* incomeWord)
    {
    	Word* ret;
    	ret = (Word*)malloc(sizeof(Word));
    	ret->count=1;
    	ret->next=NULL;
    	strcpy(ret->wordBody, incomeWord);
    }
    
    void insert(Word **n, char* incomeWord)
    {
    	Word** p_p_n;
    	int h=0;
    
    	if(*n==NULL)
    	{
    		*n = alloc(incomeWord);
    		return;
    	}
    
    	for(p_p_n = n; *p_p_n!=NULL; p_p_n = &(*p_p_n)->next)
    	{
    		if((strcmp(incomeWord,&(*p_p_n)->wordBody))==0)
    		{
    			(*p_p_n)->count++;
    			return;
    		}
    	}
    
    	for(p_p_n = n; *p_p_n!=NULL; p_p_n = &(*p_p_n)->next)
    	{
    		Word* ins = alloc(incomeWord);
    		Word* temp = *p_p_n;
    		Word** tt;
    		int is=0;
    		tt=p_p_n;
    		ins->next=temp;
    		*p_p_n = ins;
    		break;
    	}
    }
    
    void print(Word* n)
    {
    	while(n!=NULL) {
    		if(n->count > 1)
    		{
    			printf("%s %d\n", n->wordBody, n->count);
    		}
    		n=n->next;
    	}
    }
    
    int main(void)
    {
    	char buf[MAXSIZE]={'\0'};
    	FILE *fr;
    	Word* sez=NULL;
    	fr=fopen("Text1.txt", "r");
    
    	while(!feof(fr))
    	{
    		fscanf(fr,"%s",buf);
    		insert(&sez,buf);
    	}
    
    	print(sez);
    	printf("\n%d\n", sizeof(sez));
    	fclose(fr);
    	return 0;
    }

    Считаем сколЬко раз каждое слово встречается в текстовом файле. Программа выполняется 6.5 минут с файлом размером 850 килобайт.

    taburetka, 25 Декабря 2012

    Комментарии (36)
  4. C# / Говнокод #12320

    +135

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    public static string GetCommandLineParameter(string ParameterName)
        {
          ParameterName = ParameterName.ToLower();
          string ParameterIdentifikator = ParameterName.ToLower() + "=";
          
          string RetVal = null;
          foreach(string Arg in Environment.GetCommandLineArgs())
          {
            string ArgLower = Arg.ToLower();
            if(ArgLower.IndexOf(ParameterIdentifikator) == 0)
            {
              RetVal = Arg.Substring(ParameterIdentifikator.Length, Arg.Length - ParameterIdentifikator.Length);
              return RetVal;
            }
          }
          return RetVal;
        }

    читаем параметры из командной строки

    taburetka, 19 Декабря 2012

    Комментарии (13)
  5. C# / Говнокод #12241

    +135

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    if (parameter == null)//если ведомость доков...
                    {
                        cmd.Connection = dbc;
                        cmd.CommandText =
                            "SELECT RTRIM(n.Element) + ' '+ RTRIM(e.Naim) " +
                            "FROM tb_Element e, tb_ElementName n " +
                            "WHERE n.id = e.id " +
                            "AND e.GostTU ='" + head.Text.Substring(0, head.Text.IndexOf(" ")) + "'";
                        dbc.Open();
                        naim = cmd.ExecuteScalar().ToString();
                        dbc.Close();
                        cmd.CommandText =
                        "SELECT " +
                        " LTRIM(RTRIM(s.NameProject)) " +
                        ",LTRIM(RTRIM(n.Element)) + ' '+ LTRIM(RTRIM(e.Naim)) " +
                        ",LTRIM(RTRIM(d.Obozn)) " +
                        "FROM " +
                        " tb_document d " +
                        ",tb_specificationproject s " +
                        ",tb_element e " +
                        ",tb_elementname n " +
                        "WHERE " +
                        "d.pinsp = s.pinsp " +
                        "AND e.pin = s.pinsp " +
                        "AND n.id = e.id " +
                        "AND s.NameProject IN  " +
                        "( " +
                        namelist +
                        ") " +
                        "ORDER BY d.Pinsp ";
                        dbc.Open();
                        dbr = cmd.ExecuteReader();
                        counter = 0;
                        template = File.ReadAllLines(System.Windows.Forms.Application.StartupPath + "\\doclist.xml");
                        while (template[counter].Trim() != "</Table>")
                        {
                            if (template[counter].Trim() != "<Cell ss:MergeAcross=\"4\" ss:StyleID=\"s67\"><Data ss:Type=\"String\">%name%</Data></Cell>")
                            {
                                filedata.Add(template[counter]);
                            }
                            else
                            {
                                filedata.Add("<Cell ss:MergeAcross=\"4\" ss:StyleID=\"s67\"><Data ss:Type=\"String\">" + naim + "</Data></Cell>");
                            }
                            counter++;
    
                        }
                        tail_start = counter;
                        counter = 8;
                        tmp = "";
                        while (dbr.Read())
                        {
                            if (tmp != dbr[0].ToString())
                            {
                                tmp = dbr[0].ToString();
                                //Определяю высоту строки
                                CalcHeight = " ss:Height = " + '"' + Convert.ToString(rowHeight * (1 + dbr[1].ToString().Length / 10)) + '"';
                                filedata.Add("<Row" + CalcHeight.Replace(',', '.') + ">");
                                filedata.Add("<Cell ss:StyleID=\"s100\"><Data ss:Type=\"Number\">" + (counter - 7).ToString() + "</Data></Cell>");
                                filedata.Add("<Cell ss:StyleID=\"s100\"><Data ss:Type=\"String\">" + dbr[1].ToString().TrimEnd() + "</Data></Cell>");
                            }
                            else
                            {
                                filedata.Add("<Row ss:Height = \"" + Convert.ToString(rowHeight).Replace(',', '.') + "\">");
                                filedata.Add("<Cell ss:StyleID=\"s100\"><Data ss:Type=\"Number\">" + (counter - 7).ToString() + "</Data></Cell>");
                                filedata.Add("<Cell ss:StyleID=\"s100\"><Data ss:Type=\"String\"> </Data></Cell>");
                            }
                            filedata.Add("<Cell ss:StyleID=\"s100\"><Data ss:Type=\"String\">" + dbr[2].ToString().TrimEnd() + "</Data></Cell>");
                            filedata.Add("<Cell ss:StyleID=\"s100\"><Data ss:Type=\"String\"> </Data></Cell>");
                            filedata.Add("<Cell ss:StyleID=\"s100\"><Data ss:Type=\"String\"> </Data></Cell>");
                            filedata.Add("<Cell ss:StyleID=\"s100\"><Data ss:Type=\"String\"> </Data></Cell>");
                            filedata.Add("<Cell ss:StyleID=\"s100\"><Data ss:Type=\"String\"> </Data></Cell>");
                            filedata.Add("</Row>");
                            counter++;
                        }
                        counter = tail_start;
                        while (counter < template.GetLength(0))
                        {
                            filedata.Add(template[counter]);
                            counter++;
                        }
                    }

    Суровый промышленный код. Выгружаем в эксель данные из БД.

    Grover, 03 Декабря 2012

    Комментарии (13)
  6. C# / Говнокод #12081

    +135

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    int index = 0;
            this.item[index].SetDefaults("Mining Helmet");
            index++;
            this.item[index].SetDefaults("Piggy Bank");
            index++;
            this.item[index].SetDefaults("Iron Anvil");
            index++;
            this.item[index].SetDefaults("Copper Pickaxe");
            index++;
            this.item[index].SetDefaults("Copper Axe");
            index++;
            this.item[index].SetDefaults("Torch");
            index++;
            this.item[index].SetDefaults("Lesser Healing Potion");
            index++;
            ...

    Crazy_penguin, 08 Ноября 2012

    Комментарии (9)
  7. C# / Говнокод #11715

    +135

    1. 1
    2. 2
    3. 3
    4. 4
    if (TrebContext.WebSession.IsExpiredProperty == "true")
    {
         ...
    }

    Индусы такие индусы.
    bool? Не, не слышал.

    badstarosta, 06 Сентября 2012

    Комментарии (22)
  8. C# / Говнокод #11621

    +135

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    public int getFileRowsCount(string pathToFile)
    {
           System.IO.TextReader streamReader = new System.IO.StreamReader(pathToFile);
           int rowsCounter = 0;
           while ((streamReader.ReadLine()) != null)
           {
               rowsCounter++;
           }
           streamReader.Close();
           return rowsCounter;
    }

    Из http://habrahabr.ru/post/149877/
    И коммент афтора - "Здесь всё просто: пока не дойдём до пустой строки, прибавляем к счётчику строк единичку. Функция возвращает количество строк."

    phoenixx, 20 Августа 2012

    Комментарии (62)
  9. Си / Говнокод #11324

    +135

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    float Q_rsqrt( float number )
    {
            long i;
            float x2, y;
            const float threehalfs = 1.5F;
     
            x2 = number * 0.5F;
            y  = number;
            i  = * ( long * ) &y;                       // evil floating point bit level hacking
            i  = 0x5f3759df - ( i >> 1 );               // what the fuck?
            y  = * ( float * ) &i;
            y  = y * ( threehalfs - ( x2 * y * y ) );   // 1st iteration
    //      y  = y * ( threehalfs - ( x2 * y * y ) );   // 2nd iteration, this can be removed
    
            return y;
    }

    The following code is the fast inverse square root implementation from Quake III Arena, stripped of C preprocessor directives, but including the exact original comment text.

    Вот что такое настоящие магические числа.

    bormand, 30 Июня 2012

    Комментарии (36)
  10. Си / Говнокод #11268

    +135

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    #include <stdio.h>
    #include <unistd.h> 
    #include <stdlib.h> 
    #define MAX_STEP 6
    static int num;
    int seq_gen(int step){
      if(step<MAX_STEP){
    for(int idx=1;idx<=MAX_STEP;idx++){
    for(int i=0;i<=step;i++)printf(" ");
       printf("<id%d step=\"%d\">\n",idx,step);
       seq_gen(++step);
       --step;
       printf("</id%d>\n",idx);
      };
    };
    if(step==MAX_STEP){
     for(int i=1;i<=MAX_STEP;i++){
     for(int si=0;si<=step;si++)printf(" ");
      printf("<id%d>%d</id%d>\n",i,num++,i); 
     }
    }
    };
    int main(){
    printf("<root>\n");
    seq_gen(1); 
    printf("</root>");
    return 0;
    };

    Создает xml файл с 6 элементов с 6 вложенными элементами пока уровень вложенности достигнет 6.

    AliceGoth, 21 Июня 2012

    Комментарии (17)
  11. C# / Говнокод #11233

    +135

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    public TOscillPanel getOscillPanel(String nameTable, XmlNodeList parameters, String idCHPU)
            {
                var actions=new Dictionary<string, object>
                                {
                                    {"addParamOscill", new Action<string, string>(addParamOscill)},
                                    {"removeParamOscill", new Action<string, string>(removeParamOscill)},
                                    {"includeRealTimeMode",new Action<string>(includeRealTimeMode)}
                                };
                return (new TOscillPanel(nameTable, parameters, actions));
            }
    
    //...
                              ((Action<String, String>)_actions["addParamOscill"])(_tableChpu, ((TOptionNode)_oscillTreeView.Nodes[0]).getId());
                              ((Action<String, String>)_actions["addParamOscill"])(_tableChpu, idParameters);
    }
    else
    {
                            ((Action<String, String>)_actions["removeParamOscill"])(_tableChpu, ((TOptionNode)_oscillTreeView.Nodes[0]).getId());
                            ((Action<String, String>)_actions["removeParamOscill"])(_tableChpu, idParameters);
    }

    Это практически единственные и основные упоминания в коде контейнера _actions.
    Говорила же мне мама: "возьми динамически типизированный язык", а я её не слушал. Не мне конечно же. Код из очень крупного частного проекта.
    Динамически типизированный язык тут конечно же не нужен. Просто создаем трудности, а потом стоически их решаем.

    Говногость, 19 Июня 2012

    Комментарии (7)