Zahlen in zufälliger Reihenfolge

Hallo,
als kleine Bonusaufgabe könnte man noch sagen, dass man eine eigene Rand-Funktion schreiben muss.
Ist gar nicht soschwer wie es sich anhört, eine Funktion mit 2 Zeilen Code (und insgesamt 3 Rechenoperatoren) sind vollkommen ausreichend.
 
Hab das auch mal versucht^^

Code:
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    
    ofstream Zahlen;
    int Zufall;
    
    Zahlen.open("E:\\Programmieren\\Programmiertes\\C++\\Zufällige Zahlenreihenfolge\\Zahlen.txt");
    
    srand(time(NULL));
    
    for( int y = 0; y <= 10000; y++)    {
         
         Zufall = (rand() % 10000) ;
         
         if( Zufall <= 999 && Zufall >= 100)
               Zahlen <<"0";
         
         
         else if( Zufall <= 99 && Zufall >= 10)
               Zahlen <<"00";
               
         else if( Zufall < 10 )
               Zahlen <<"000";
         
         Zahlen << Zufall << endl;
     }
     
     Zahlen.close();
     
int Ende;
cin >> Ende;

return 0;
}

Ist das eig. ein "guter" Programmierstyle ?
Also die von den anderen C++-Lösungen sehen ja ganz anders aus...
 
Ist doch alles richtig.

Edit: Achso, es darf nur bis 9999 gehen...
Und 0000 ist eig. auch in der Ausgabe, oder ?
 
Du gibst einfach 10001 Zufallszahlen im Bereich 0 bis 9999 aus. Also schon dadran sieht man dass die Zahlen doppelt ausgegen werden.
Und wegen der einfachen Generierung werden auch noch andere Zahlen doppelt ausgegeben.
 
Hab auch mal eine kleine PERL Lösung.

Code:
#!/usr/bin/perl
open F, ">numbers.txt";

$a{rand()} = ($_) for (0..9999);
printf F "%04d\n",$_ for (values %a);

close F;
 
Hallo!

Meine Java Lösung

Code:
public class RandomNums {

	public static void main(String[] args) throws IOException {
		ArrayList<String> nums = new ArrayList<String>();
		
		for(int i=0; i<1000; i++)
			nums.add(String.format("%04d", i));
		Collections.shuffle(nums);

		FileWriter writer = new FileWriter(new File("nums.txt"));
		for(String num : nums) {
			writer.write(num +"\n");
			writer.flush();
		}
	}

}

Gruß
Felix
 
Da das Ding schneller ist als ich erwartet habe, belasse ich bei bei der Version
Code:
import random
def add_num():
    x = random.randrange(0,10000,1)
    if x in zahlen:
        return add_num()
    else:
        return x


zahlen = [-1] * 10000
output = open("ausgabe.txt","w")
for i in zahlen:
    i= add_num()
    output.write(str(i)+"\n")
output.close()
 
Hi

Hier mal was in C++/CLI.

Code:
#include "stdafx.h"

using namespace System;
using namespace System::IO;


int main(array<System::String ^> ^args)
{
	Int32 zahl[10000];
	Boolean gezogen[10000];
	Random ^zufall = gcnew Random();

	for (Int32 zaehler=0;zaehler<=9999;zaehler++)
	{
		gezogen[zaehler]=false;
	}

	for (Int32 zaehler=0;zaehler<=9999;zaehler++)
	{
		zahl[zaehler]=zufall->Next(0,10000);
		while (gezogen[zahl[zaehler]]==true)
		{
			zahl[zaehler]=zufall->Next(1,10000);
		}
			gezogen[zahl[zaehler]]=true;
	}
		
	StreamWriter ^datei = gcnew StreamWriter("0000-9999.txt");
	for (Int32 zaehler=0;zaehler<=9999;zaehler++)
	datei->WriteLine("{0}",zahl[zaehler]);
	datei->Close();

    
	return 0;
}

Ausgabe ist im Anhang.
 
Ruby Einzeiler

Code:
File.open('1.txt','w'){|f|(0..10000).sort_by{rand}.each{|x|f<<sprintf("%04d", x)+"\n"}}
 
In C:
Mann, ist man eingerostet wenn man ne Weile nix macht :(
Code:
#include <stdlib.h>
#include <stdio.h>

main()
{
srand(time(0));
int a[9999],i,c,k;
FILE *file;

for(i=0;i<=9999;i++)a[i]=i;
for(i=0;i<=9999;i++){c=a[i];a[i]=a[k=rand()%10000];a[k]=c;}

file=fopen("random_number_list.txt", "w");
if(file==NULL){printf("File Access Error");exit(EXIT_FAILURE);}
for(i=0;i<=9999;i++)fprintf(file, "%00004d\n",a[i]);
fclose(file);
}
 
Hier meine ruby Lösung:

Code:
a = []; i = 0; k = 0
while a.length != 10000
	b = rand(10000); k = 0
	a.each { |part|
		if part == b
			k = 1
		end
	}
	if k != 1
		a.push(b)
		if b < 10
			puts "000#{b}"; c = "000#{b}"
		elsif b < 100
			puts "00#{b}"; c = "00#{b}"
		elsif b < 1000
			puts "0#{b}"; c = "0#{b}"
		else
			puts "#{b}"; c = "#{b}"
		end
		file = File.new("zahlen.txt", "a"); file.puts c; file.close
	end
end
Alle Zahlen werden in der Datei zahlen.txt abgespeichert.
 
Ebenfalls Ruby:
ab 1.8.7:
Code:
open('a.txt','w'){|o|o.puts [*'0000'..'9999'].shuffle}

für ätere Versionen:
Code:
open('a.txt','w'){|o|o.puts [*'0000'..'9999'].sort_by{rand}}
 
Ruby

Code:
File.open("zahle.txt", "w") { |datei| 	zahlen = (0000..9999).sort_by{rand}.each { |zahl| 	datei.puts zahl } }

meine version gerade anfänger :p bin sehr stolz das ich das geschaft habe auch wenn ich das mit den 0456 - 456 nicht hingekrieg habe :-D
 
VB

Auch wenn der letzte Beitrag schon ein bisschen her ist, hier meine Lösung:

Code:
Module Module1
    Public ausgegeben(9999) As Integer
    Public zahl As Integer
    Public fName As String = "C:\Zahlenspiel.txt"
    Public alt As String
    Public neu As Boolean = False

    Sub Main()

        For y As Integer = 0 To 9999
            ausgegeben(y) = -1
        Next
        Console.WriteLine("Working...")
        For x As Integer = 0 To 9999
            Randomize()
            neu = False
            Do
                zahl = CInt(Int((10000 * Rnd()) + 1))
                zahl -= 1
                If Array.IndexOf(ausgegeben, zahl) = -1 Then

                    Try
                        Dim inStream As IO.StreamReader
                        inStream = New IO.StreamReader(fName)
                        alt = inStream.ReadToEnd
                        inStream.Close()
                        inStream = Nothing
                    Catch
                        alt = ""
                    End Try

                    Dim outStream As IO.StreamWriter
                    outStream = New IO.StreamWriter(fName)
                    outStream.Write(Format(zahl, "0000") & vbCrLf & alt)
                    outStream.Close()
                    outStream = Nothing

                    ausgegeben(x) = zahl
                    neu = True
                End If
            Loop While neu = False
        Next

        Console.WriteLine("Done!")
        Console.ReadLine()
    End Sub

End Module

Saß ne halbe Ewigkeit an der Erzeugung der Zufallszahlen, da VB i-wie nicht so wollte wie ich... :rolleyes:

PS: Hätte die Liste ja als .txt mit hochgeladen, aber die 59KB große .txt war wg. Beschränkung (19,5KB) zu groß.
Wann wurde das eingeführt? Sind ja auch andere .txt Dateien in diesem Thread, die knapp 60KB haben.
 
Objective-C mit dem Foundation Framework:
Code:
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
    NSMutableArray *numbers = [NSMutableArray arrayWithCapacity:10000];
    int i;
    srand(time(NULL));
    for (i = 0; i < 10000; i++) {
        NSString *content = [NSString stringWithFormat:@"%.4d", i];
        NSUInteger numbersCount = [numbers count];
        NSUInteger randomIndex = rand() % (numbersCount+1);
        [numbers insertObject:content atIndex:randomIndex];
    }
    [[numbers componentsJoinedByString:@"\n"] writeToFile:@"output.txt" atomically:YES encoding:NSUTF8StringEncoding error:NULL];
    
    [pool drain];
    return 0;
}
 
Common Lisp:
Code:
(loop for i from 0 upto 1000 collecting i into l 
          finally (with-open-file (file "./a.out" :direction :output)
            (format file "~{~4,'0D~^~%~}" (sort l #'> :key (lambda (x) (random 1.0))))))
 
Code:
[delphi]
procedure BlubGod(Filename: String; Max: DWord);
var
  StrLst  : TStringList;
  Values  : Array of DWord;
  i       : Integer;
begin
  StrLst := TStringList.Create;
  try
    Randomize;
    SetLength( Values, Max );
    for i := 0 to Max - 1 do
      Values[i] := i;
    StrLst.BeginUpdate();
    try
      repeat
        i := Random( Max );
        dec( Max );
        StrLst.Add( IntToStr( Values[i] ) );
        if i = Max then
          Continue;
        // some exchange magic...
        Values[i] := Values[i] - Values[Max];
        Values[Max] := Values[Max] + Values[i];
        Values[i] := Values[Max] - Values[i];
      until Max = 0;
    finally
      StrLst.EndUpdate();
    end;
    StrLst.SaveToFile( Filename );
  finally
    StrLst.Free;
  end;
end;
[/delphi]

Der folgende Aufruf benötigt ~4.0 sek
Code:
  BlubGod('blub.txt', 1000000);
 
Zuletzt bearbeitet:
In Ruby:
Code:
datei=File.open("zahlen.txt","w")
datei.puts Array(1..1000).shuffle.to_s.delete("[").delete("]")
datei.close
 
Code:
#!/usr/bin/env ruby

foo = (0..9999).to_a.shuffle
File.open('foo.txt', 'w') { |f| foo.each { |i| f.printf("%04d\n", i) } }
 
Zuletzt bearbeitet:
Zurück
Oben