• STATISTIQUES
  • Il y a eu un total de 2 membres et 8523 visiteurs sur le site dans les dernières 24h pour un total de 8 525 personnes!


    Membres: 2 605
    Discussions: 3 580
    Messages: 32 820
    Tutoriels: 78
    Téléchargements: 38
    Sites dans l'annuaire: 58


  • ANNUAIRE
  • [FR] apprendre-a-manipuler
    Site d'apprentissage de la manipulation d'autrui.
    Hacking
    [FR] Infomirmo
    Challenge présenté sous la forme de 6 niveaux de difficultés diverses et variées avec chacun plusieurs chall...
    Challenges
    [FR] Kalkulators
    Ce projet a plusieurs buts, le premier étant l’étude de toutes formes cryptographiques, le cot&ea...
    Cryptographie
    [EN] HackQuest
    Logic: 12, JavaScript: 14, Applet: 6, CrackIt: 13, Crypto: 11, Internet: 3, Exploit: 7, Stegano: 12, Flash: 1, Programmi...
    Challenges
    [FR] Forum-Webmaster
    Une communauté webmaster pour apporter / recevoir de l'aide en création de site internet. Webmaster...
    Webmaster
    [EN] Bright Shadows
    JavaScript: 13, Exploit: 27, Crypto: 69, CrackIt: 52, Stegano: 67, Flash: 3, Programming: 16, Java-Applet: 10, Logic: 20...
    Challenges
    [FR] PHP Débutant
    Apprendre le PHP par l'exemple, facilement et simplement. Réservé d'abord aux débutants....
    Programmation

  • DONATION
  • Si vous avez trouvé ce site internet utile, nous vous invitons à nous faire un don du montant de votre choix via Paypal. Ce don servira à financer notre hébergement.

    MERCI!




Note de ce sujet :
  • Moyenne : 0 (0 vote(s))
  • 1
  • 2
  • 3
  • 4
  • 5
question du jour 2 - le retour
31-05-2014, 19h06 (Modification du message : 01-06-2014, 10h08 par Booster2ooo.)
Message : #16
Booster2ooo Hors ligne
Contributeur
*****



Messages : 165
Sujets : 14
Points: 63
Inscription : Aug 2011
RE: question du jour 2 - le retour
Node.JS

/!\ remplacez le path C:/Users/Booster/
Code JAVASCRIPT :

var fs = require('fs');
var os = require('os');
fs.readFile('C:/Users/Booster/inputFile.txt', 'ascii', function(err, data) {
        if (err) {
            return console.log(err);
        }
        var EOL = os.EOL
          , groups = data.split(EOL+EOL)
          , result = []
          ;
        for(var i = 0,c=groups.length;i<c;i++) {
            var values = groups[i].split(EOL);
            values = values.sort(function(a,b) {
                return a - b;
            });
            result = result.concat(values);
            result.push(EOL);
        }
        console.log(result.join(EOL));
        return;
    }
);
 


Autre sample C#, sans l'utilisation de la lib LINQ

Code CSHARP :

using System;
using System.Text;
using System.IO;
using System.Collections;

namespace NPNQDJ
{
    class Program
    {
        public class StringAsIntComparer : IComparer
        {
            public int Compare(object l, object r)
            {
                return Int32.Parse((string)l).CompareTo(Int32.Parse((string)r));
            }
        }

        static void Main()
        {
            string fileName = "inputFile.txt";
            string fullPath = AppDomain.CurrentDomain.BaseDirectory + fileName;
            if (File.Exists(fullPath))
            {
                string fileContent = File.ReadAllText(fullPath, Encoding.UTF8);
                string[] groups = fileContent.Split(new string[] { System.Environment.NewLine + System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string group in groups)
                {
                    string[] values = group.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                    Array.Sort(values, new StringAsIntComparer());
                    foreach (var val in values)
                    {
                        Console.WriteLine(val);
                    }
                    Console.WriteLine();
                }
            }
        }
    }
}
 
+1 (1) -1 (0) Répondre
01-06-2014, 01h15 (Modification du message : 01-06-2014, 01h41 par gruik.)
Message : #17
balis Hors ligne
Hack Compagnie by Eballys
*



Messages : 156
Sujets : 3
Points: 16
Inscription : Dec 2012
RE: question du jour 2 - le retour
Désolé pour le retard , je n'ai pas eu le temps et une petite flemmingite Big Grin
Les paragraphes sont séparés par une étoile et non des sauts de lignes et ce termine par étoile. tu peux modifier ça facilement dans le if.
Code :
12
4
*
12
45
*
Code C :
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

static int compare ( void const *a , void const *b){
    /* on cast */
    int const *aa=a;
    int const *bb=b;
    return *aa-*bb;
}

void ecrit(int *tab, int taille_n){
    FILE *ecriture;
    int cpt;
    ecriture=fopen("output.tralala","a");
    /* ou utilises un scanf */
    for( cpt=0; cpt < taille_n ; ++cpt)
        fprintf(ecriture,"%d\n",tab[cpt]);
   
    fprintf(ecriture,"\n");
    fclose(ecriture);
}

void range_paragraphe(char *nom_fichier){
    FILE *lecture;
    int *tab=(int*)malloc(sizeof(int));
    int *tmp=NULL;
    char recup[100];
    int rec=0, i=0 , cpt=0;

    tab[0]=0;

    lecture=fopen(nom_fichier,"r");

    if( lecture == NULL){
        printf("Fichier inexistant \n");
        exit(EXIT_FAILURE);
    }

   while( fscanf(lecture,"%s\n",recup) > 0){        
      sscanf(recup,"%d",&rec);
        if( strcmp(recup,"*") == 0 ){
            qsort(tab, i, sizeof(int), compare);
            ecrit(tab,i);
          free(tab);
          tab=NULL;
          tab=(int *)malloc(sizeof(int));
          i=0;
      }
      else{
      /* on met dans le tableau */
      if( i != 0){
          tab= realloc(tab, (i+1) * sizeof(int));
      }
      tab[i]=rec;
      ++i;
      }
   }
    free(tab);
    fclose(lecture);
}

int main(void){
    /* remplace le ici ou utilise le scanf */
    char file[100]="liste.tralalala";

    printf("Nom du fichier ==> ");
    /*scanf("%s",file);*/
    range_paragraphe(file);
    printf("Done \n");

    return 0;
}
Sur le net , les poules ont des dents. Bali .
Soit original soit celui qui sort de l'ordinaire soit toi . Bali .
C: ok bash : ok asm : en cours.
HTML/CSS : ok , PHP/MySQL : en cours.
+1 (2) -1 (0) Répondre
01-06-2014, 09h12
Message : #18
Dobry Hors ligne
Tueur de lamouz
*



Messages : 206
Sujets : 25
Points: 73
Inscription : Aug 2011
RE: question du jour 2 - le retour
Bon on s'est rendu compte avec gruik que le solution ruby n'allait définitivement pas, en fait IO.readlines charge tout le fichier en mémoire, et voici donc une solution alternative (écrite par gruik, un peu modifiée par mes soins), qui permet au moins de charger le gros fichier, cependant le temps d'execution reste assez élevé (13-14s si je me souviens bien).
Code RUBY :

#!/usr/bin/env ruby
arr = []
File.open(ARGV[0]).each_line do |line|
        if line.length != 1
                arr << line.to_i
        else
                if arr.length != 0
                        puts arr.sort
                        puts
                        arr.clear
                end
        end
end
 
Aestuārium Erudītiōnis

There are only two hard things in Computer Science: cache invalidation, naming things, and off-by-one errors.
+1 (0) -1 (0) Répondre
01-06-2014, 10h04 (Modification du message : 01-06-2014, 10h06 par Booster2ooo.)
Message : #19
Booster2ooo Hors ligne
Contributeur
*****



Messages : 165
Sujets : 14
Points: 63
Inscription : Aug 2011
RE: question du jour 2 - le retour
Encore un, PHP:

Note: le file_get_contents est peu être un peu violent, ça peut être remplacé par du fopen

Code PHP :

<?php
        $EOL = PHP_EOL;
        $fileContent = file_get_contents('inputFile.txt');
        $groups = explode($EOL.$EOL,$fileContent);
        unset($fileContent);
        for($i = 0, $c = count($groups); $i<$c; ++$i)
        {
                $values = explode($EOL, $groups[$i]);
                sort($values,SORT_NUMERIC);
                for($j =0,$k = count($values);$j<$k;++$j)
                {
                        echo $values[$j].PHP_EOL;
                }
                echo PHP_EOL;
        }
?>
 
+1 (1) -1 (0) Répondre
04-06-2014, 12h48 (Modification du message : 04-06-2014, 12h48 par notfound.)
Message : #20
notfound Hors ligne
#!/usr/bin/env bash
*



Messages : 687
Sujets : 47
Points: 271
Inscription : Sep 2012
RE: question du jour 2 - le retour
En parlant de ruby sur un autre channel, j'en suis venu à montrer ce thread.

TsT a proposé son code en LUA, que je poste à son nom :

Code LUA :

local f = arg[1]
local fd = assert(io.open(f, 'r'))
local res = {}
local b = {}
while true do
        local line = fd:read('*l')
        if not line or line == "" then
                if #b > 0 then
                        table.sort(b)
                        res[#res+1] = b
                        b = {}
                end
                if not line then break end
        else
                b[#b+1] = tonumber(line)
        end
end
fd:close()
 
for i,v in ipairs(res) do
        res[i] = table.concat(v, "\n")
end
print(table.concat(res, "\n\n"))

 
-- En minimisé oneliner

fd=io.open(arg[1],"r");res,b={},{};while true do local line=fd:read("*l");if not line or line=="" then if #b>0 then table.sort(b);res[#res+1]=b;b={} end if not line then break end else b[#b+1]=tonumber(line) end end;fd:close();for i,v in ipairs(res) do res[i]=table.concat(v,"\n") end;print(table.concat(res,"\n\n"))


-- Et avec un module

local strong = require("strong") -- https://github.com/BlackBulletIV/strong
local powertable = require("powertable") -- TsT small module
 
local function tprint(t) for aa,bb in ipairs(t) do print("      ", aa,bb) end end
 
local f = arg[1]
local fd = assert(io.open(f, "r"))
local res = {}
for elem in fd:read("*a"):lines("\n\n") do
        res[#res+1] = powertable( elem:chomp()plit("\n", true) ):tsort( function(x,y) return tonumber(x) < tonumber(y) end ):concat("\n")
end
print(table.concat(res, "\n\n"))


-- Optimisé performance

local function process_data(fd, para_handler)
        local buf = {} -- buffer for each lines of the current paragraph
        while true do
                local line = fd:read("*l") -- read one line
                if not line then break end -- stop if the end of file is reached
                if line == "" then -- a empty line = end of paragraph
                        para_handler(buf)
                        buf = {} -- reset buffer
                else
                        table.insert(buf, tonumber(line))
                end
        end      
        para_handler(buf)
end
 
local function para_handler(buf, eof)
        -- new paragraph ready
        table.sort(buf)
        print(table.concat(buf, "\n").."\n")
end
           
local f = arg[1]
local fd = assert(io.open(f, "r"))
process_data(fd, para_handler)
fd:close()
 


Voilà.
Temps et conso dernier code (d'après gruik):
Time : 8,80s
Conso : < 5k
+1 (1) -1 (0) Répondre
04-06-2014, 19h08
Message : #21
wapiflapi Hors ligne
Newbie
*



Messages : 4
Sujets : 0
Points: 8
Inscription : Nov 2012
RE: question du jour 2 - le retour
Yop.

Voilà mon code en C: http://pastebin.com/9y6nNV3M

Features principales:
- utilisations mmap & stdio pour minimiser les temps d'accès en lecture/écriture.
- trie par insertion au lieu de quick sort, ce qui est plus efficace sur de petites listes.
- pas de copie des data dans des buffers temporaires.

Code C :

/*
** sort.c in /home/wapiflapi/Projects/misc/gruik/
**
** Made by Wannes Rombouts
** Login   <rombou_w@epitech.eu>
**
** Started on  Wed Jun  4 15:12:23 2014 Wannes Rombouts
** Last update Wed Jun  4 17:55:28 2014 Wannes Rombouts
*/

 
#include        <unistd.h>
#include        <stdlib.h>
#include        <stdio.h>
#include        <string.h>
#include        <fcntl.h>
#include        <err.h>
#include        <sys/mman.h>
#include        <sys/stat.h>
 
struct entry {
  char const    *text;
  size_t        size;
  unsigned int  val;
};
 
static void process_file(char const *data, size_t size)
{
  struct entry  *array;
  size_t        asize;
  size_t        afill;
 
  afill = 0;
  asize = 32;
  if (!(array = calloc(asize, sizeof *array)))
    err(EXIT_FAILURE, "malloc");
 
  data = data;
  size = size;
 
  while (size > 0)
    {
      char const *nextn;
      unsigned int nb;
 
      if (!(nextn = memchr(data, '\n', size)))
        nextn = data + size;
      size -= nextn - data;
 
      /*
      ** Carefull, nextn might not be mapped if no terminating \n.
      */

 
      if (nextn > data)
        {
          if (afill == asize)
            {
              /*
              ** Should check overflows here but I'm lazy.
              */

              asize *= 2;
              if (!(array = realloc(array, asize * sizeof *array)))
                err(EXIT_FAILURE, "realloc");
            }
 
          array[afill].text = data;
          array[afill].size = nextn - data;
 
          /*
          ** Assume positive numbers.
          */

 
          for (nb = 0; '0' <= *data && *data <= '9'; ++data)
            nb = nb * 10 + *data - '0';
          array[afill].val = nb;
 
          afill += 1;
        }
      else
        {
          /*
          ** Group change: sort & print.
          ** Not using quick sort because it is not faster
          ** than insertion sort for sorting small sets.
          ** libc's implementation is slow anyway, probably
          ** due to all the function calls that can't be inlined.
          */

 
          int i, j;
          struct entry x;
 
          for (i = 1; i < afill; ++i)
            {
              x = array[i];
              for (j = i; j > 0 && array[j-1].val > x.val; --j)
                array[j] = array[j-1];
              array[j] = x;
            }
 
          for (i = 0; i < afill; ++i)
            fwrite(array[i].text, 1, array[i].size + 1, stdout);
          fputc('\n', stdout);
 
          afill = 0;
        }
 
      data = nextn + 1;
      size -= 1;
    }
 
  free(array);
}
 
int             main(int argc, char **argv)
{
  int           fd;
  void          *data;
  struct stat   sbuf;
 
  if (argc < 2)
    errx(EXIT_FAILURE, "Usage: %s data_file", argv[0]);
 
  if ((fd = open(argv[1], O_RDONLY)) < 0)
    err(EXIT_FAILURE, "open");
 
  if (fstat(fd, &sbuf) < 0)
    err(EXIT_FAILURE, "fstat");
 
  if (sbuf.st_size)
    {
      if ((data = mmap(NULL, sbuf.st_size, PROT_READ, MAP_PRIVATE,
                       fd, 0)) == MAP_FAILED)
        err(EXIT_FAILURE, "mmap");
 
      process_file(data, sbuf.st_size);
 
      munmap(data, sbuf.st_size);
    }
 
  close(fd);
 
  return 0;
}
 
+1 (5) -1 (0) Répondre


Sujets apparemment similaires…
Sujet Auteur Réponses Affichages Dernier message
  question du jour gruik 9 289 12-11-2013, 16h10
Dernier message: gruik
  Question pour la création de mon site... Wabouz 10 359 05-03-2013, 21h14
Dernier message: Wabouz

Atteindre :


Utilisateur(s) parcourant ce sujet : 1 visiteur(s)
N-PN
Accueil | Challenges | Tutoriels | Téléchargements | Forum | Retourner en haut