There is an array of integers with 24 values, called poles. It is necessary to fill it with numbers from 1 to 12, so that each number is repeated 2 times. In this case, the numbers should be "randomly." How to implement?

    3 answers 3

    Here is one of the possible solutions to your problem.

    pole : array [1..24] of integer; procedure peretasovka; var sl:TstringList; i:integer; begin sl:=tstringlist.Create; for i := 0 to 23 do sl.Add(IntTostr(i div 2+1)); // Заполнили список парами чисел последовательно for i := 0 to 23 do sl.Exchange(i,random(sl.Count)); // Перетасовали список for i := 0 to 23 do pole[i+1]:=StrToInt( sl.Strings[i]);// Перенесли со списка в массив sl.Free; end; 
    • four
      cool, at first the numbers were converted to strings, and then back to numbers :) Just like in the joke about how to boil a kettle with water, if it is already with water. - KoVadim
    • This is all probably in order to beautifully sl.Exchange, instead of moving a numerical value along a random index) - ArcherGodson
    • 3
      I agree that I do not labor, but this is also an option, and secondly it will be easier for the student to understand. The more non-educated dolphists will go out, the higher I will be appreciated :) - vdk company
    • one
      To me good programmers do not harm. - KoVadim

    This problem is solved as follows. First, the array is filled with the necessary numbers (in any convenient order, for example, 1, 1, 2, 2, .. 12, 12), and then an algorithm with the name shuffle is applied to it. On Delfi there are options for implementation. Here are two implementations for arrays and collections. You will find the rest in Google for "delphi shuffle" or in Knut's books.

       type TIntArray24 = array [0..23] of Integer; function GetPole: TIntArray24; procedrue Exchange(var I1, I2: Integer); var tmp: Integer; begin tmp := I1; I1 := I2; I2 := tmp; end; var I: Integer; begin for I := Low(Result) to High(Result) do Result[I] := (I + 2) div 2; // +2 если масив от нуля, а цифры нужны от 1 for I := Low(Result) to High(Result) do Exchangle(Result[I], Result[Random(High(Result) - Low(Result)) + Low(Result)]); // махинации с Low High нужны чтобы не менять код когда меняется длина массива end;