vendredi 30 décembre 2022

How to print random character from string in Java [duplicate]

I'm working on a project that you try to find the full word. There is an option that gives you a clue. The clue is printing individual characters from random index. but sometimes I am accesing same characters. I dont want to print duplicate characters (from same index). For example the word is computer. When I press the clue button, character from 2nd index reveals. But when I press again, random number chooses 2nd index again randomly. I dont want to acces 2nd index anymore. How can I do that? Thanks.

I tried to create an array list to store random indices. And I created a for loop to check all the elements of the array list to avoid same indices. But its not working or I couldnt make it.




How can I let random point to START from the selected location in each iteration in FOR LOOP in Matlab?

The code below deploy random point and make it move in 5 directions. So, after excuting the first loop, the second loop will select the direction that produce max " X " value. My question is, How can Iet this random point to start from the position that selected when produce max " X " value IN THE SECOND ITERATION AND THIRD ITERATION UP TO 10 iterations that determined in the third loop. In other words how can I let the point to START from selected position each iteration ?

Thanks in advance

v=2;%7.2/3.6;
hfig = figure('Color', 'w');
hax = axes('Parent', hfig);
for gg = 1:1:10  % THIRD LOOP
for jj=1:1       % SECOND LOOP
  angleOption = [24 56 72 36 96];
for ii = 1:numel(angleOption)      % FIRST LOOP
chooseAngle = angleOption(ii)
 PosPoint1_x=center(1)+cos(chooseAngle); % Initial positions
PosPoint1_y=center(2)+sin(chooseAngle);
PosPoint1 = [PosPoint1_x ,PosPoint1_y]
h(1) = plot(PosPoint1(1,1),PosPoint1(1,2),'Parent', hax,'Marker', '.','Color', 'k','LineStyle', '-','MarkerSize', 12);
hold(hax, 'on') 
grid(hax, 'on')  
axis(hax, 'equal')
displacement = [cos(chooseAngle).*v, sin(chooseAngle).*v];
newPos = PosPoint1 + displacement
startpos = newPos-displacement
dd(ii,:)=newPos(:,:)
cc=length(dd)
dd1(ii,:)=startpos(:,:)
cc1=length(dd1)
XData = [h.XData PosPoint1(:, 1)];
YData = [h.YData PosPoint1(:, 2)];
set(h, 'XData', XData, 'YData', YData)
drawnow
XData = [h.XData PosPoint1(:, 1)];
YData = [h.YData PosPoint1(:, 2)];
set(h, 'XData', XData, 'YData', YData)
drawnow
%  currentXvalue_1(ii) = DO SOME CALCULATIONS
end
 [maxXvalue_1(countmax), idx_max1] = max(currentXvalue_1);
pickangle_maxX_1 = ActionSpace11(idx_max1)
Displacement_max1 = [cos(pickangle_maxX_1(:)) .* v1 ,sin(pickangle_maxX_1(:)) .* v1];
XYnew11Max = PosPoint1 + Displacement_max1;
    fprintf(' 1 Keep on the same position '); 
XData = [h(1).XData PosPoint1(:,1)];
YData = [h(1).YData PosPoint1(:,2)];
set(h(1), 'XData', XData, 'YData', YData)
drawnow
end
end



how can I get a random text from txt in cypress

sorry I am new to cypress

I got a large txt file, it has 5000 lines of txt

all txt is divided by \n

12331565399
29165910115
58108651482
74656524192
70536463673
11606518282
15616508033
and more...

I stored this txt file in my fixtures

and in my e2e cy, I wrote

cy.readFile('./cypress/fixtures/list.txt')

it gives me all the txt file but I don't know how to pick a random txt from that file

please help me




jeudi 29 décembre 2022

Mutate existing container for `rand` results in Julia?

I have a simulation where the computation will reuse the random sample of a multi-dimensional random variable. I'd like to be able to re-use a pre-allocated container for better performance with less allocations.

Simplified example:

function f()
    container = zeros(2) # my actual use-case is an MvNormal
    map(1:100) do i
        container = rand(2)
        sum(container)
    end
end

I think the above is allocating a new vector as a result of rand(2) each time. I'd like to mutate container by storing the results of the rand call.

I tried the typical pattern of rand!(container,...) but there does not seem to be a built-in rand! function following the usual mutation convention in Julia.

How can I reuse the container or otherwise improve the performance of this approach?




mercredi 28 décembre 2022

Java while loop random number

i'm new to Java and I am trying to code a little "fighting game" (more random than fight actually). I want each punch to have a random number of damages between 0 and 30. The problem is, the first number randomly sorted will be used until the end (if it's 12, both fighters will punch at 12 damages every turn until Player 1 wins). How can I generate a different random number at every iteration of the loop until there's a winner ?

package jeu_propre;

public class main {
    public static void main(String[] args){
        System.out.println("Player 1, choose your name : ");
        String nom_pone= new java.util.Scanner(System.in).nextLine();
        System.out.println("Player 2, choose your name : ");
        String nom_ptwo= new java.util.Scanner(System.in).nextLine();
                        
        int r=new java.util.Random().nextInt(30);
        
        weapons fists = new weapons();
        fists.name="fists";
        fists.damage = r;
        
        
        player number_one = new player();
        number_one.name= nom_pone;
        number_one.hp= 100;
        
        player number_two= new player();
        number_two.name=nom_ptwo;
        number_two.hp= 100;
        
        
        boolean running=true;
        while (running == true) {
            System.out.println("Fight !");
            System.out.println(number_one.name +" hit " + number_two.name);
            String frapper= new java.util.Scanner(System.in).nextLine();
            System.out.println(fists.damage);
            number_two.hp= number_two.hp -= fists.damage;
            
            if (number_two.hp <=0) {
                System.out.println(number_one.name +" wins !");
                running=false;
                break;
            } else {
                System.out.println(number_two.name + " still has "+number_two.hp);
                running = true;
            }
            System.out.println("Fight !");
            System.out.println(number_two.name +" hit " + number_one.name);
            String frapper2= new java.util.Scanner(System.in).nextLine();
            System.out.println(fists.damage);
            number_one.hp= number_one.hp -= fists.damage;
            
            if (number_one.hp<=0) {
                System.out.println(number_two.name +" wins !");
                running=false;
                break;
            }else {
                System.out.println(number_one.name + " still has "+number_one.hp);
                running = true;
            }
        }

I tried to change the values between the brackets and associating the random command directly to "fists.damage"




Generate a random vector elements that sum up to one?

Let us consider that we have a vector V. Where V(1,6): the vector contains six columns (cases). How can I set up a random vector that will sum up to 1. I mean that: sum(V(1,:)) == 1 ). Where all the elements should be between 0 and 1. Upperbounder =1 and lowbounder =1.




Missing capital W in generating a random nonce

enter image description here

Is there a particular reason for why the capital W is missing?

This method works fine for creating random nonce, just curious as to whether it's intentional or a simple typo :)




How to generate random datetime in specific format ? and how to add some duplicated datetime?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Random_Files
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            var randomDateTimes = GenerateRandomDates(10000);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        public IEnumerable<DateTime> GenerateRandomDates(int numberOfDates)
        {
            var rnd = new Random(Guid.NewGuid().GetHashCode());

            for (int i = 0; i < numberOfDates; i++)
            {
                var year = rnd.Next(1, 10000);
                var month = rnd.Next(1, 13);
                var days = rnd.Next(1, DateTime.DaysInMonth(year, month) + 1);

                yield return new DateTime(year, month, days,
                    rnd.Next(0, 24), rnd.Next(0, 60), rnd.Next(0, 60), rnd.Next(0, 1000));
            }
        }
    }
}

this generate 10,000 random datetime list. but i want each datetime to be in this format : ToString("yyyyMMddHHmm")

and i want that some datetime will be duplicated i mean the same for example 10,000 and in this 10,000 some of them will be the same.

for example : 31/10/2099 05:51:36 to be twice or more times in the random list. more to be random once but some of them to be the same. those are the same also to be random.

for example index 31 and index 77 the same or index 0 and index 791 the same. because later when i make out of this files names i want to compare the files names so i need some names to be the same.




mardi 27 décembre 2022

Is this undefined behavior? why does this code return a seemingly random integer?

I'm looking at the following C code:

#include <stdio.h>
#include <stdlib.h>

void main(){
    int a;
    printf("%d", a);

}

I'm wondering why this code prints a seemingly random number. My first guess is that this is undefined behavior but I could be wrong.




array with random Generator using methods

Hi i'm struggling with this assignment. When the program starts 4 methods are being executed where the next thing hapens.

  • One array gets filled with 100 random numbers between 1 and 1000 000 (method1)
  • The first listbox gets filled with aal the numbers from the array (method2)
  • The second listbox gets filled with the 5 smalest numbers from the array (method3)
  • The third listbox gets filled with the 5 biggest numbers from the array (method3)

This has to run when the program starts.

So far my array gets filled and the first listbox gets filled to. But only in one and not through different methods. i tried to split it up but without succes And my deadline is near.

sorry for the rookie mistakes btw.

public partial class RandomArray : Form
    {   
        int[] arrRandomNumbers = new int[100];
Random randomGenerator = new Random();
        int iRandomNumber = 0;




        public RandomArray()
        {
            InitializeComponent();
           FillArray(arrRandomNumbers);
        }

        
        private void FillArray(int[] array)
        {
            for (int i = 0; i < arrRandomNumbers.Length; i++)

            {

                iRandomNumber = randomGenerator.Next(1, 1000000);

                arrRandomNumbers[i] = iRandomNumber;


            }

        }


        
        private void AddToListBox(int[] array, ListBox box)
        {
            

 foreach (var number in arrRandomNumbers)

                {

                    lbxOne.Items.Add(number);

                }


            


        }
            
                private void AddSmallest(int[] arr, ListBox box)
               {
                  
                   
               } 

            
               private void AddLargest(int[] arr, ListBox box)
            {
                
            }

        
    }

}



How can I generate new random numbers each time in my while loop in Python for a number game?

I've created a number game where it asks the user if they want to play again and then the loop continues. My program uses import random but I want to know how I'd generate new random numbers without having to make variables each time. (I'm a beginner and I don't know what solution to use pls help)

My code works for the most part it's just that when the loop restarts the same number from the last playthrough repeats so the player ends up getting the same results. Here's my code:

`

import random
random_number_one = random.randint (0, 100)

username = input("Greetings, what is your name? ")
start_game = input("Welcome to the number game, {0}!  Would you like to play a game? (Type 'Yes/No') ".format(username))

while True:
  if start_game == 'Yes' or start_game == 'yes' :
    print("Let's begin!")
    print(random_number_one)
    user_guess = input("Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: ")
    if user_guess == 'H' or user_guess == 'h' :
        print("You guessed higher. Let's see: ")
        import random
        random_number_two = random.randint (0, 100)
        print(random_number_two)
        if random_number_two > random_number_one :
          print("You are correct! It was higher!")
          play_again_h = input("Would you like to play again? ('Yes'/'No') ")
          if play_again_h == 'Yes' or play_again_h == 'yes' :
            continue
          else:
            break 
        else:
          play_again = input("You were wrong, it was lower. Would you like to play again? ('Yes'/'No')  ")
          if play_again == 'Yes' or play_again == 'yes' :
            continue
          else:
            break
           
    elif user_guess == 'L' or user_guess == 'l':
      print("You guessed lower. Let's see: ")
      print(random_number_two)
      if random_number_two < random_number_one :
        print("You are correct! It was lower!")
        play_again_l = input("Would you like to play again? ('Yes'/'No') ")
        if play_again_l == 'Yes' or play_again_l == 'yes' :
         continue
        else:
         break
      else:
        play_again_2 = input("You were wrong, it was higher. Would you like to play again? ('Yes'/'No')  ")
        if play_again_2 == 'Yes' or play_again_2 == 'yes' :
          continue
        else:
          break
    else:
       print("Invalid response. You Lose.")
       break

  elif start_game == 'No' or start_game == 'no':
    print("Okay, maybe next time.")
    break
  else:
    print("Invalid response. You Lose.")
    break




`




Levy Flights Cuckoo Search algorithm Python

I am implementing a cuckoo search algorithm for the TSP. However i am struggling with the part of levy flights in the implementation to create ranges. The levy flight should be between 0 and 1. See picture below for more explanation. Is there anyone who could help me out with the python implementation?

Currently i have the following code:

def levyFlight(u): return u/math.pow(1-u, 1.6)

def randF(): return uniform(0.0001, 0.9999)

levy = levyFlight(randF())

enter image description here




This is a number guessing Python code ,but it stops after entering the first guessing number. Can you tell me where is the fault?

import random
winning_number = random.randint(1,100)
guess = 1
number = int(input("guess a number between 1 and 100: "))
while not game_over:
  if number == winning_number:
    print(f"you win, and you guessed this number in {guess} times ")
    game_over = True
  else:
    if number < winning_number:
      print("too low")
      guess += 1
      number = int(input("guess again: "))
    else:
      print("too high")
      guess += 1
      number = int(input("guess again: "))

I want to continue the guessing number until it reach the right answer.




I cannot randomize my list. it gives me only one character when I print it

#Password Generator Project
import random
letters = ['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', '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']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']

print("Welcome to the PyPassword Generator!")
nr_letters= int(input("How many letters would you like in your password?\n"))
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))

password = []

for l in range (0 , nr_letters+1):
    random_l = random.choice(letters)
    password.append(random_l)

for i in range (0 , nr_symbols+1):
    random_i = random.choice(symbols)
    password.append(random_i)

for n in range (0 , nr_numbers+1):
    random_n = random.choice(numbers)
    password.append(random_n)

print(random.choice(password))

I want to randomize and print the password list at the end of the code but it gives me only one character. When I print it without random function or shuffle it prints properly.




lundi 26 décembre 2022

Replacing the contents or following text of a keyword in Powershell

I want to replace the contents of a certain keyword or text in a .txt file Example:

word.pass=haiwueuofbdkoabqo1738379

I want to replace the contents or text of word.pass=

I only know about replacing a certain keyword but not the following text or the line




dimanche 25 décembre 2022

New to coding and pranking friend who knows nothing, but my script input breaks

I know it sounds dumb, but I am making an annoying baby simulation that repeatedly asks questions unless given an exact input response to prank a friend.

I have a set of random questions as well as random follow-up questions to feed to him while he will toil away until he essentially discovers the "password" input. My follow-up questions, however, will not randomize and instead select only one out of the list and then break the code entirely, making the new input prompt a random character/element over and over again infinitely.

I have tried placing another while loop within the while loop to assert more definite randomness to the follow-up question pulling and hopefully fix the input prompt issue, but I am not even sure if you can do such a thing successfully and it didn't work so I removed it, and I am still REALLY new to coding entirely.

I may just be over my head despite the idea seeming relatively simple so the solution may be something I haven't learned, but here is my silly prank script that I cant fix:


from random import choice

new_questions = ["Where are all the dinosaurs?: ", "How are babies made?: ", "Why don't we have superpowers?: ", "Why is the sky blue?: "]
questions = ["Well why is the sky blue then?!: ", "Why though?: ", "I still don't get it...why?: ", "OHH OKAY...no, no, wait, but...Why?: ", "WHY?!: ", "You suck at explaining things...just tell me why already.: ", "Why?: ", "What does that have to do with the sky being blue...?: ", "Yeah, I get that part, but why?: ", "Ok, why?: "]

new_questions = choice(new_questions)
answer = input(new_questions).strip().lower()

while answer != "just because":
    questions = choice(questions)
    answer = input(questions).strip().lower()

I have yet to finish it, as I am still trying to understand why this first part breaks.

Upon running, you will see that it executes most of it well, but it cannot randomly pick from my variable "questions" multiple times randomly, and it also breaks after the first pull from the questions list and will consequently only ask for an input with a singular character element instead.




Getting random Vector2 positions within a crescent area

I am struggling to find a way to get Random positions within a Crescent area. Calculating the crescent is well documented using the difference of two overlapping circles. But that calculates the surface area, which is not enough if I want to generate random positions in that area.

illustration

In this illustration we know both the center origin points and radii:

CenterPoint of CircleA ca=0,0 Radius of ca caRad = 100
CenterPoint of CircleB cb=9,0 Radius of cb cbRad = 85

knowing these values we could fill in all the variables on the illustration; A, B, D, E and F. Calculating the Crescent Area would be

π*(caRad²) - π*(cbRad²) = 2775π

And this is where I am stuck, I have all the information yet, don't know on how to proceed getting random positions 'Within' that crescent area.

Any help in this matter is very appreciated, Nick.




How to select a number according to a uniform distribution from a set of first n natural numbers in python? [closed]

Suppose I have a set of the first n natural numbers, i.e., [n]:= {1,2,3,...n}. Now, I have to select one number from the set [n]. I want to select the number according to a uniform distribution. In other words, the probability that a number j in the set [n] will be selected is 1/n.

Here is what I have tried;

a = 2**33
b = np.random.randint(1, a)

but this code is giving me the following error:

ValueError: high is out of bounds for int32

Clearly, random.randint isn't working for me. So, how can I select a number according to the uniform distribution in Python?




randomize Nested symbols for coin blocks

I am back for a long due break. I want to know how to randomize the frames for coin blocks.

Code:

if(coinblock1.hitTestObject(blowfishPong) == true){
            if (ballSpeedXCoinGame > 0) {
                ballSpeedXCoinGame *= -1;
                ballSpeedYCoinGame = calculateBallAngleCoinGame((character.y, blowfishPong.y);
                var randomCoin = Math.floor(Math.random() * coinblock.length+1);
                gotoAndStop(randomCoin);
                if(randomCoin.currentFrame == 2){
                    coin += 1;
                    CoinSFX.play();
                }
                else if(randomCoin.currentFrame == 12){
                    coin += 5;
                    CoinSFX.play();
                }
                else if(randomCoin.currentFrame == 22){
                    coin += 10;
                    CoinSFX.play();
                }
                else if(randomCoin.currentFrame == 32){
                    coin += 50;
                    CoinSFX.play();
                }
                else if(randomCoin.currentFrame == 42){
                    coin += 100;
                    CoinSFX.play();
                }
        }
    }

ArgumentError:

Error #2109: Frame label NaN not found in scene Main Game.
    at flash.display::MovieClip/gotoAndStop()
    at BlowfishPong_CoinGameTest__fla::MainTimeline/loopCoinGame()[BlowfishPong_CoinGameTest__fla.MainTimeline::frame1:131]

How to randomize the range for following frames rather than the beginning for the coin block?




samedi 24 décembre 2022

Flutter release version only bug on Android

Description

I've developed a dart class to generate random circles for the splash screen of my app. It generates circles of different sizes that do not intersect each other and also leave some space in the center of the screen for the logo. This code works fine on IOS and in debug mode on Android. However, when run in release mode on Android - there's a white screen instead of the expected SplashScreen. The code for reproduction is at the bottom of this issue.

Expected result (might differ a bit - it's random)

Simulator Screen Shot - iPhone 14 Pro - 2022-12-24 at 10 20 36

Steps to Reproduce

  1. Try running with flutter run --debug on Android device - works just fine, the SplashScreen renders
  2. Try running with flutter run --release on Android device - white screen instead of expected SplashScreen, nothing happens
  3. Comment out the lines inside // REMOVE TO AVOID THE BUG.
  4. Try running with flutter run --debug on Android device - works just fine
  5. Try running with flutter run --release on Android device - works just fine

Works fine on IOS in all modes without commenting out the buggy lines.

Flutter commands outputs

flutter run --verbose --release:

[        ] Installing APK.
[   +1 ms] Installing build/app/outputs/flutter-apk/app.apk...
[        ] executing: /Users/olegbezr/Library/Android/sdk/platform-tools/adb -s f213fa8d install -t -r /Users/olegbezr/Code/splash_bug/build/app/outputs/flutter-apk/app.apk
[+1338 ms] Performing Streamed Install
           Success
[   +3 ms] Installing build/app/outputs/flutter-apk/app.apk... (completed in 1,339ms)
[   +2 ms] executing: /Users/olegbezr/Library/Android/sdk/platform-tools/adb -s f213fa8d shell echo -n 8797e6dd9572aee4f95fbb041f30bfdedcd623cb > /data/local/tmp/sky.com.example.splash_bug.sha1
[  +45 ms] executing: /Users/olegbezr/Library/Android/sdk/platform-tools/adb -s f213fa8d shell am start -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -f 0x20000000 --ez enable-dart-profiling true com.example.splash_bug/com.example.splash_bug.MainActivity
[  +87 ms] Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x20000000 cmp=com.example.splash_bug/.MainActivity (has extras) }
[   +1 ms] Application running.
[   +1 ms] Flutter run key commands.
[        ] h List all available interactive commands.
[        ] c Clear the screen
[        ] q Quit (terminate the application on the device).

flutter analyse:

Analyzing splash_bug...                                         
No issues found! (ran in 2.0s)

flutter doctor -v:

[✓] Flutter (Channel stable, 3.3.8, on macOS 13.0 22A380 darwin-arm, locale en-US)
    • Flutter version 3.3.8 on channel stable at /Applications/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 52b3dc25f6 (6 weeks ago), 2022-11-09 12:09:26 +0800
    • Engine revision 857bd6b74c
    • Dart version 2.18.4
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at /Users/olegbezr/Library/Android/sdk
    • Platform android-33, build-tools 33.0.0
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14C18
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio
    • Android Studio at /Applications/Android Studio Preview.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)

[✓] Android Studio (version 2021.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)

[✓] IntelliJ IDEA Ultimate Edition (version 2021.2.2)
    • IntelliJ at /Applications/IntelliJ IDEA.app
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart

[✓] VS Code (version 1.74.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.56.0

[✓] Connected device (4 available)
    • IN2020 (mobile)        • f213fa8d                             • android-arm64  • Android 11 (API 30)
    • iPhone 14 Pro (mobile) • 84586B2B-4DD8-4682-941D-6E790AF5CCAC • ios            • com.apple.CoreSimulator.SimRuntime.iOS-16-2 (simulator)
    • macOS (desktop)        • macos                                • darwin-arm64   • macOS 13.0 22A380 darwin-arm
    • Chrome (web)           • chrome                               • web-javascript • Google Chrome 108.0.5359.124

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!

The code

import 'dart:math';

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Flutter Demo',
      home: SplashScreen(),
    );
  }
}

class SplashScreen extends StatefulWidget {
  const SplashScreen({Key? key}) : super(key: key);

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  List<SplashRandomCircle> _circles = [];

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final width = MediaQuery.of(context).size.width;
    final height = MediaQuery.of(context).size.height;
    final circlesCount = 8 + Random().nextInt(4);

    setState(() {
      _circles = SplashRandomCircle.randomListNoIntersection(
        count: circlesCount,
        width: width,
        height: height,
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          ..._circles
              .map(
                (e) => Positioned(
                  left: e.xCoord - e.radius,
                  top: e.yCoord - e.radius,
                  child: Container(
                    decoration: BoxDecoration(
                      shape: BoxShape.rectangle,
                      borderRadius: BorderRadius.circular(e.radius * 0.9),
                      color: e.color,
                    ),
                    width: e.radius * 2,
                    height: e.radius * 2,
                  ),
                ),
              )
              .toList(),
        ],
      ),
    );
  }
}

class SplashRandomCircle {
  static int opacityPrecision = 10000;
  static Random randomizer = Random();
  static Color mainColor = const Color.fromARGB(255, 156, 74, 67);

  static Color randomBlue(double minOpacity, double maxOpacity) {
    final deltaOpacity = ((maxOpacity - minOpacity) * opacityPrecision).round();
    return mainColor.withOpacity(
      randomizer.nextInt(deltaOpacity) / opacityPrecision + minOpacity,
    );
  }

  static double randomX(double width, double multiplier) {
    final right = randomizer.nextBool();

    var xCoord = randomizer.nextDouble() * width * multiplier;
    if (right) {
      xCoord = width - xCoord;
    }
    return xCoord;
  }

  static double randomY(double height, double multiplier) {
    final bottom = randomizer.nextBool();

    var yCoord = randomizer.nextDouble() * height * multiplier;
    if (bottom) {
      yCoord = height - yCoord;
    }
    return yCoord;
  }

  static double randomRadius(double minRadius, double width, double multiplier) {
    return randomizer.nextDouble() * width * multiplier + minRadius;
  }

  final double xCoord;
  final double yCoord;
  final double radius;
  final Color color;

  SplashRandomCircle({
    required this.xCoord,
    required this.yCoord,
    required this.radius,
    required this.color,
  });

  static SplashRandomCircle random({
    required double width,
    required double height,
    double widthMultiplier = 0.5,
    double heightMultiplier = 0.5,
    double minRadius = 10,
    double radiusMultiplier = 0.5,
    double minOpacity = 0.3,
    double maxOpacity = 0.8,
  }) {
    return SplashRandomCircle(
      xCoord: randomX(width, widthMultiplier),
      yCoord: randomY(height, heightMultiplier),
      radius: randomRadius(minRadius, width, radiusMultiplier),
      color: randomBlue(minOpacity, maxOpacity),
    );
  }

  static List<SplashRandomCircle> randomListNoIntersection({
    required int count,
    required double width,
    required double height,
    double widthMultiplier = 0.6,
    double heightMultiplier = 0.6,
    double minRadius = 6,
    double radiusMultiplier = 0.6,
    double minOpacity = 0.4,
    double maxOpacity = 0.9,
    double logoWidthMultiplier = 0.4,
    double circlesSpacingMultiplier = 0.04,
  }) {
    final circles = <SplashRandomCircle>[];
    while (circles.length < count) {
      final newCircle = SplashRandomCircle.random(
        width: width,
        height: height,
        widthMultiplier: widthMultiplier,
        heightMultiplier: heightMultiplier,
        minRadius: minRadius,
        radiusMultiplier: radiusMultiplier,
        minOpacity: minOpacity,
        maxOpacity: maxOpacity,
      );

      var checkPosition = true;
      // check if the new circle intersects with any of the existing circles
      for (final circle in circles) {
        final xDiff = circle.xCoord - newCircle.xCoord;
        final yDiff = circle.yCoord - newCircle.yCoord;
        final distance = sqrt(xDiff * xDiff + yDiff * yDiff);

        // REMOVE TO AVOID THE BUG
        if (distance < circle.radius + newCircle.radius + width * circlesSpacingMultiplier) {
          checkPosition = false;
          break;
        }
        // REMOVE TO AVOID THE BUG
      }

      // check if the new circle doesn't intersect with the logo
      final centerXDiff = width / 2 - newCircle.xCoord;
      final centerYDiff = height / 2 - newCircle.yCoord;
      final distance = sqrt(centerXDiff * centerXDiff + centerYDiff * centerYDiff);

      // REMOVE TO AVOID THE BUG
      if (distance < newCircle.radius + width * logoWidthMultiplier) {
        checkPosition = false;
      }
      // REMOVE TO AVOID THE BUG

      if (checkPosition) {
        circles.add(newCircle);
      }
    }
    return circles;
  }
}



vendredi 23 décembre 2022

Select a random Guild member using Discord.js

I'm trying to make a command that based off of one of the april fools videos will mention a random member of teh server. unfortuneately ive had no luck with everything ive googled.

I would like to mention I'm still very new to javascript and discord.js

the best ive found so far is:

interaction.guild.members.random();

and that didnt work (it told me its not function)




Approach to generate unique short number for current day

I need to generate a number that is unique for the current day, I'm bound to use short data type and I tought to use hour/minute to achieve that. This is my VB code:

Dim ora As String = dataora.Substring(6, 2) 'es. 07
Dim minuti As String = dataora.Substring(8, 2) 'es 14
Dim parteOra = ora * 1000
Dim parteMinuti = rando.Next(0, 708)
Dim parteFinale = rando.Next(0, 9000)
Dim CUL as short = CShort(parteOra + (minuti + parteMinuti) + parteFinale)

Knowing that short data type manage a 0-32767 range (from 0 up, I can't use negative) my question is: with the code above can I be 100% sure that in the same day I will always have an unique number?

My logic is:

  • hour in 24h format is unique 0-23 number
  • minutes is unique 0-59 number in the same hour
  • parteOra can go from 0 to 23000
  • minuti + parteMinuti can go from 0 to 767
  • parteFinale can go from 0 to 9000
  • putting all togheter I should have a range from 0 to 32767



jeudi 22 décembre 2022

Is there a better way to write this random list function?

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    rand = random.randint(0,place)
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/random.py", line 248, in randint
    return self.randrange(a, b+1)
TypeError: can only concatenate str (not "int") to str

^This is my error. I'm not sure why this code isn't working as I'm new to Python. I'm trying to write a code that detects how big a list is, then selects a random item from the list.

import random

greetings = ["hello","hola","bonjour","privet","ciao","guten tag","shalom"]

place = 0
for i in greetings:
  place = i

rand = random.randint(0,place)
print(greetings[rand])

^This is what I have so far. Any help would be appreciated




mercredi 21 décembre 2022

How to instantiate a randomly picked ScriptableObject?

Im new to Unity and c#, I've been making a turn based game following one of Brackeys tutorial and i've added scriptable objects to it. Im looking to instantiate a random enemy everytime a fight starts.

Here's the lines that should be useful : ImageOfMyCode The resources.LoadAll("Enemies") seems to work since I made 3 scriptable objects and the debug log also says 3.

Im really struggling past this to then shuffle allEnemies and instantite the randomly picked one.

Any help and guidance will be appreciated.




SAS Proc Mixed Random VS Repeated (Or both)?

I have data from a study for a "device". Subjects receive an implant and are followed for 5 years, with a checkup every year. A "disability score" is calculated from a survey every visit. The implant comes in different "sizes". Also, every year the "device condition" is evaluated. What I'm trying to do is see if "device condition" is associated with "disability score" while controlling for implant size/time/subject.

The Data:

I have the subject id, implant (A and B for sizes and is a static/baseline variable), the timepoint (12, 24, 36, 48, 60 months), implant condition (ordinal scale where 0 is best condition and can change timepoint to timepoint within each subject) and the disability score (dependent quantitative variable).

Example shown below

data modelling;
    input sid $ implant $ timepoint condition disability_score;
    cards;
    1 A 12 0 8
    1 A 24 0 9
    1 A 36 1 9.5
    1 A 48 1 8
    1 A 60 2 9
    2 B 12 1 7
    2 B 24 2 6
    2 B 36 2 7
    2 B 48 3 8
    2 B 60 4 9
    .....
    15 A 12 0 8
    15 A 24 0 9
    15 A 36 1 9.5
    15 A 48 1 8
    15 A 60 2 9
    ;
run;

I'm using proc mixed, but I'm not sure which syntax would be most appropriate for this question. My initial inkling is this is a repeated measures situation and used this:

proc mixed data=modelling plots=none;
    class sid implant timepoint condition;
    model disability_score = implant condition timepoint condition*timepoint;
    repeated timepoint / subject=sid;
run;

However, one thing I'm concerned with is if timepoint needs/should be a quantitative value, and if this is truly a repeated measures situation. When I run this, the condition and implant seem to be significant, and timepoint is not.

I also tried using the random statement with the subject id instead and using timepoint as quantitative

proc mixed data=modelling plots=none;
    class sid implant condition;
    model disability_score = implant condition timepoint condition*timepoint;
    random sid;
run;

When I do this, I get vastly different results, with timepoint being significant and both implant and condition no longer significant.

Really, I'm not 100% sure which is the correctly specified model, and am looking for some validation and/or guidance to the correctly specified model for this question.




Generate 45 degree (or less) line from 2 randomly generated points

I'm randomly generating 2 points and drawing a line with them. A problem occurs when the line is too steep (> 45 degrees) and the line appears more like spaced out dots than an actual line. Another problem is that if the line is perpendicular (90 degrees, parallel to y axis) the algorithm is dividing my 0 and giving an error out.

So my question is: How can I randomly generate 2 points that make a 45 degree (or less) line?

Point.py:

class Point:
   def __init__(self, x, y):
    self.x = x
    self.y = y

main.py:

from Point import Point
from random import randint

def simple_line(p1, p2):
  # Calculate slope of line
  # y = mx + b
  m = (p2.y - p1.y) / (p2.x - p1.x)

  # Calculate height of line

  b = p1.y - m * p1.x

  return m, b

def draw_lines(img_array, points):
  for p in points:
    m, b = simple_line(p[0], p[1])

    # some code to draw on image.... 


random_points_array = []
 
# Generate lots of lines
for i in range(500):
  random_points_array.append((Point(randint(0, len(img_array[0])), randint(0, len(img_array))), 
                              Point(randint(0, len(img_array[0])), randint(0, len(img_array)))))

draw_lines(random_points_array)



mardi 20 décembre 2022

Generating one random number from given input [C++]

#include <iostream>
using namespace std;

int main()
{

int n;
int *array;
array= new int[n];
cout<<"Masukkan ukuran array"<< endl;
cin >> n;
cout << "Masukkan nilai array" << endl;

for (int i=0; i < n; i++)
{
    cin >> array[i];
}

cout << "hasil array adalah"<< endl;
for (int i=0; i < n; i++)
{
    cout<<array[i]<< " ";
}
cout << endl<< "hasil urut adalah"<< endl;
for(int i = 0; i < n;i++)
{
    for (int j=i+1;j<n;j++)
    {
        if (array[j]<array [i])
        {
            int temp=array[i];
            array[i]=array[j];
            array[j]= temp;
        }
        else;
    }
}

for (int i=0;i<n;i++)
{
    cout << array[i]<< " ";
}




return 0;

}

i'm trying to generate a single random number from the inputted value for example i input 1,3,6,8 to my array and im trying to figure it out how to generate a random number from given input so the output will be 3 or 6 or 8 etc




Select randomly percent of datasets in each percent of epochs

I have a model that should train with 25000 data in 50000 epochs. I want to train with percentage of datasets for percentage of epochs for example it trains for 10 first epoch only 1000 random data then for 10 next epoch, 1000 random data..... My source code in part of dataloder is in follow.

class DataModule(pl.LightningDataModule):

  def __init__(self, train_dataset, val_dataset,  batch_size = 2):

    super(DataModule, self).__init__()
    self.train_dataset = train_dataset
    self.val_dataset = val_dataset
    self.batch_size = batch_size

  def train_dataloader(self):
    return DataLoader(self.train_dataset, batch_size = self.batch_size, 
                      collate_fn = collate_fn, shuffle = True, num_workers = 2, pin_memory = True)
  
  def val_dataloader(self):
    return DataLoader(self.val_dataset, batch_size = self.batch_size,
                    collate_fn = collate_fn, shuffle = False, num_workers = 2, pin_memory = True)

I understand below code could select random of dataset but I want to train the other data for next epochs too.

df_fraction= df_mydataset.sample(frac=0.04) 

And I understand below code could select random of dataset but I dont know how it works.Because I should change data for each 10 epochs

train_sampler = SubsetRandomSampler(train_indices)
train_loader = torch.utils.data.DataLoader(dataset, batch_size=2, sampler=train_sampler)

How can I do that with batch_size=2?




Python pandas conditional random select - selecting random item with multiple criteria

Trying to make a random selection from a list of products:

product_id  type    year_created
1   shirt   2021
2   book    2021
3   chair   2022
4   shirt   2021
5   book    2022
6   shirt   2022
7   shirt   2022
8   desk    2021
9   shirt   2022
10  lamp    2022
11  tv  2021
12  tv  2022

...

Would like to select random product ids, but making sure that the end result has one of each "type" in each "year released". So only one shirt from 2021, one shirt from 2022, one book from 2021, one book from 2022, etc.

Is there a way to do this in Python with a function apart from filtering the data and running a random query on each subset? Thank you!




Hi! I have a problem in my python exam question :( [closed]

Create a random list of one hundred 3 digit numbers with some selected seed. Save that list in variable list_q2. Then print elements, which are divisible by their corresponding index's last digit. Ignore index zero.

Hints: use library random.

Here's what I already did:

import random

x = []
n = 100
for i in range(n):
    x.append(random.randint(100, 999))



lundi 19 décembre 2022

name 'privtopub' is not defined

My code looks like:

from django.shortcuts import render, redirect
from django.contrib.auth.models import User, auth
from django.contrib import messages
from .models import Details
from bitcoin import *
import random
import bs4
import requests

def login(request):

    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']

        user = auth.authenticate(username=username, password=password)

        if user is not None:
            auth.login(request, user)
            return redirect('/')
        else:
            messages.info(request, 'Invalid Credentials')
            return redirect('login')

    else:
        return render(request, 'login.htm')

def register(request):

    detail = Details()
    bits = random.getrandbits(256)
    bits_hex = hex(bits)
    private_key = bits_hex[2:]
    print(private_key)
    # private_key = random_key()
    public_key = privtopub(private_key)
    address = pubtoaddr(public_key)
    detail.private_key = private_key
    detail.public_key = public_key
    detail.address = address

But I get the error: name 'privtopub' is not defined




Pick a number game advice

I have an app in development - it's a pick a number game between 1 & 1,000,000... One number is the jackpot, the other 999,999 numbers are not.

I have 15 different items that will be found on the other numbers (in place of higher or lower), each taking the player through a series of 5 screens.

I want item 1 to be spread randomly across 150,000 numbers, item 2 to be spread randomly across 20,000 numbers and so forth (all items totalling 999,999). I also want the ability to adjust those numbers on the fly through the admin panel.

My developers are saying that to do this they would need to code 1,000,000 entries - which is not practical and would cause everything to crash...

I'm not a coder. Starting to wish I was... But the way I see it is the player either picks the winning number or they don't. If they don't, can't code just randomly choose one of the 15 sequences to take the player through? Showing item one for example no more than 150,000 times? (Or whatever I set it at in the admin panel)

How would you do this? Any advice will be greatly appreciated!

,.....................




How can you generate a unique list of random integers? [duplicate]

My task is to create two functions: function 1: checks if the randomly generated list is all unique integers function 2: generates a random list of integers.

my function 1 works. my question is for function 2: I know how to randomly generate integers... But I really can't figure out how to randomly generate a list?

import random
#check for unique integers in list
def allunique(x):
    unique_or_not= []
    for item in x:
        if item in unique_or_not:
            return False
        unique_or_not.append(item)
    return True


#need 3 inputs of the # of values to generate, starting # in range of list, ending # in range of list
def list_of_nums():
    num_of_values= int(input("Please enter the number of values you wish to generate:"))
    start= int(input("Please enter the starting # of the values you wish to generate:"))
    end= int(input("Please enter the end # of the values you wish to generate:"))



    for i in range(0,num_of_values):
#have to loop to do it a certain amount of times, append value immediately to list:????



I have such a code and I don't want my random function to return the random numbers it previously gave,what can i do to fix this [duplicate]

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {  
    srand(time(NULL));
    int i = 0;
    int dizi[20];

    for (i = 0; i < 20; i++) {
        dizi[i] = rand() % 20;
    }   

    for (i = 0; i < 20; i++) {
        printf("%d\n", dizi[i]);
    }   
    
    return 0;
}

Is the if else structure sufficient to solve this problem or do I need to do something about the rand function?




How to prevent duplicates in random selection?

I wrote small program to populate my game with NPCs named by random selections from first name and last name lists. It worked but sometimes there are duplicate names selected. How can I prevent duplicates?

I could use dict but I prefer list. Is this big disadvantage? The commented block in adding_male_NPC is my attempt to solve this problem.

import random

women_names = ["Jennifer", "Jenna", "Judith", "Becky", "Kelly"]
man_names = ["Adam", "John", "Jack", "Jim", ]
surnames =["Salzinger", "Jefferson", "Blunt", "Jigsaw", "Elem"]
marriage_status = ["Single", "In couple", "Engaged", "Married", "Divorced", "Widow"]
male_NPCs = []
list = []


def clr_list(list):
    del list


def randomizer(list):
    random_choice = random.choice(list)
    clr_list(list)
    return random_choice


def random_male():
    male_surname = randomizer(surnames)
    male_name = randomizer(man_names)
    male_NPC = male_name + " " + male_surname
    return (male_NPC)


def add_one_man():
    male_NPCs.append(random_male())
    return


def addding_male_NPC(count_of_NPC_males):
    while count_of_NPC_males > 1:
        add_one_man()
        # for m in male_NPCs:
        #     unique_count = male_NPCs.count(m)
        #     if unique_count > 1:
        #         male_NPCs.pop(unique)
        #         count_of_NPC_males +=1
        #     else:
        count_of_NPC_males -= 1


count_of_NPC_males = int(input("How many males should create?: "))
addding_male_NPC(count_of_NPC_males)

print(male_NPCs)
print(len(male_NPCs))

So i tried this but its impossible to count strings or somehow don't use well .count what is most possible. Get idea to take indexes before creating sum of stings and use it to check double but i feel that i make circles. I understand that provided list of names and surnames are not guarantee make doubles with high numbers but you got the point of this.

def addding_male_NPC(count_of_NPC_males):
    while count_of_NPC_males > 1:
        add_one_man()
         for m in male_NPCs:
             unique_count = male_NPCs.count(m)
             if unique_count > 1:
                 male_NPCs.pop(unique)
                 count_of_NPC_males +=1
             else:
                  count_of_NPC_males -= 1

Edit This is so sad :(

mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)

But anyway it will cut planned and needed numbers of item. So question is still active. This answer is quite half answer. I wait for better one.




random number with specific condition in python

I'd like to generate an int random number between 0 and 1 n number of times. I know the code to generate this:

num_samp = np.random.randint(0, 2, size= 20)

However, I need to specify a condition that say 1 can only appear a number times and the rest should be zeros. For instance if I want 1 to appear only 5 times from the above code, then I would have something like this [0,1,0,0,0,1,1,0,0,0,1,0,1,0,0,0,0,0,0,0]

Can someone help with the code to generate something like this? Thanks




dimanche 18 décembre 2022

Randomly sampling from list values and corresponding names

What I want to do is randomly sample from the list values (in this case cities) and create a variable from that sample. Also according to the city randomly picked, another variable (country) should contain the country that corresponds to the city of that observation.

list <- list(Spain = c("Barcelona", "Madrid"), Austria = c("Vienna", "Salzburg"), 
             France = c("Paris", "Lyon"), Italy = c("Milano", "Roma"))

cbind(Country = c("Italy", "Spain"), City = c("Roma", "Madrid"))



Having troubles appending inside a range loop

import random

def In_Play():
    return random.randint(0,100)

def pitch():
    return random.randint(0,100)

first_pitch_result = []
second_pitch_result = []
third_pitch_result = []
forth_pitch_result = []
fifth_pitch_result = []
sixth_pitch_result = []
seventh_pitch_result = []

pa_result = []

for i in range(0, 1000):
    if pitch()<=43:
       Fpitch = "Count 1-0"
    elif pitch()>=59:
       Fpitch = "Count 0-1"
    else:
       Fpitch = "0-0 In-Play"
       if 18<= In_Play()<41:
           pa_end = "0-0 Single"
       elif 10<= In_Play()<18:
           pa_end = "0-0 Double"
       elif 0<= In_Play()<1:
           pa_end = "0-0 Triple"
       elif 1<= In_Play()<10:
           pa_end = "0-0 Home Run"
       else:
           pa_end = "0-0 OUT"
           
           pa_result.append(pa_end)
               
    first_pitch_result.append(Fpitch)

I am having troubles being able to create the pa_result bucket? When one of the plate appearances end i want it to be dumped into the pa_result (later there will be at the plate results) but for the first pitch i want to end the pa (or i) and then put it into the pa_result but its just keeping the last one. While i am here, i was wondering if its better to continue on under each count, or figure out what plate apperances are left and continue with a new range and if statements. Subtracting the 0-0 In Play with 1-0 and 0-1 Counts.




How to store several inputs to a list and add a number picker for each in Xamarin Forms

I'm curious as to how you can store up to 3 input fields - each attached to a user-name typed into another input field (on the same page). Then after pressing a button and going to a new page: displaying a list of all the inputs made (except for the name) in a random order and attaching a picker to each - from which you can pick a number between 1-10.

If you don't know how to write the code - is it possible to link me to somewhere where I might learn how to do this? Thanks!




samedi 17 décembre 2022

Issues with perlin noise having discontinuous edges

I created a simple perlin noise generator using p5.js, which is based on this link . For the most part, I got 80% of the algorithm working. The only issue is that there is defined discontinuities aligned with each gradient vector. the code for this project is shown below.

// noprotect
var screen_width = 400;
var screen_height = 400;

var res = 2;
var gvecs = {};


function setup() {
  createCanvas(screen_width, screen_height);
  initialize_gvecs();
  draw_perlin_noise();
}

function draw() {
  console.log(gvecs);
  noLoop();
}

function initialize_gvecs() {
  for (var y = 0; y <= res; y++) {
    for (var x = 0; x <= res; x++) {
      let theta = Math.random() * 2 * Math.PI;
      gvecs[[x, y]] = {
        x: Math.cos(theta),
        y: Math.sin(theta)
      };
    }
  }
}

function draw_perlin_noise() {

  loadPixels();

  for (var y = 0; y < screen_height; y++) {
    for (var x = 0; x < screen_width; x++) {
      var world_coordx = map(x, 0, screen_width, 0, res);
      var world_coordy = map(y, 0, screen_height, 0, res);

      var top_L_x = Math.floor(world_coordx);
      var top_L_y = Math.floor(world_coordy);

      var top_R_x = top_L_x + 1;
      var top_R_y = top_L_y;

      var bottom_L_x = top_L_x;
      var bottom_L_y = top_L_y + 1;

      var bottom_R_x = top_L_x + 1;
      var bottom_R_y = top_L_y + 1;

      var top_L_g = gvecs[[top_L_x, top_L_y]];
      var top_R_g = gvecs[[top_R_x, top_R_y]];
      var bottom_L_g = gvecs[[bottom_L_x, bottom_L_y]];
      var bottom_R_g = gvecs[[bottom_R_x, bottom_R_y]];

      var btw_top_L = {
        x: world_coordx - top_L_x,
        y: world_coordy - top_L_y
      };
      var btw_top_R = {
        x: world_coordx - top_R_x,
        y: world_coordy - top_R_y
      };
      var btw_bottom_L = {
        x: world_coordx - bottom_L_x,
        y: world_coordy - bottom_L_y
      };
      var btw_bottom_R = {
        x: world_coordx - bottom_R_x,
        y: world_coordy - bottom_R_y
      };

      var v = top_L_g.x * btw_top_L.x + top_L_g.y * btw_top_L.y;
      var u = top_R_g.x * btw_top_R.x + top_R_g.y * btw_top_R.y;
      var s = bottom_L_g.x * btw_bottom_L.x + bottom_L_g.y * btw_bottom_L.y;
      var t = bottom_R_g.x * btw_bottom_R.x + bottom_R_g.y * btw_bottom_R.y;

      var Sx = ease_curve(world_coordx - top_L_x);
      var a = s + Sx * (t - s);
      var b = u + Sx * (v - u);

      var Sy = ease_curve(world_coordy - top_L_y);
      var final_val = a + Sy * (b - a);

      pixels[(x + y * screen_width) * 4] = map(final_val, -1, 1, 0, 255);
      pixels[(x + y * screen_width) * 4 + 1] = map(final_val, -1, 1, 0, 255);
      pixels[(x + y * screen_width) * 4 + 2] = map(final_val, -1, 1, 0, 255);
      pixels[(x + y * screen_width) * 4 + 3] = 255;

    }

  }
  updatePixels();

}

function ease_curve(x) {
  return 6 * x ** 5 - 15 * x ** 4 + 10 * x ** 3;

}
<script src="https://cdn.jsdelivr.net/npm/p5@1.5.0/lib/p5.js"></script>

an image of the issue I'm having is shown below.

discontinuous edge example

I suspect that my issue has to do with the value between each gradient vector not properly using the adjacent gradient vectors, but I've tested and debugged this extensively and I cant find the issue. I've also tried several different ease_curve functions, but none of them seem to change anything. Any help would be greatly appreciated.




С++ I'm trying to make the randomizer lower and higher and bot [closed]

I'm trying to make a randomizer below and above and a bot that will pass itself, but I can't guess randomly, but the search is below and above


#include <iostream>
#include <Windows.h>

using namespace std;

int main()
{
    int NewNum = 100;
    int bin;
    int ran;
    int num;
    int guess;
    int tries = 0;

    srand(time(NULL));
    num = (rand() % 100) + 1;
    ran = (rand() % 100) + 1;

    cout << "12 let \n";

    do {
        cout << "1-100 \n";
        guess = 0 + ran;
        tries++;

        if (guess > num) {
            cout << "high \n";
            bin = 1;
            if (bin == 1) {
                ran = rand() % ran + 0;
            }
        }

        else if (guess < num) {
            cout << "low \n";
            bin = 0;
            if (bin == 0) {
                ran = ran + rand() % 100;
            }
        }
        else {
            cout << "correct: " << tries << "\n";
        }


    } while (guess != num);

    return 0;
}


I searched on the forums: Stackoverflow, Syberforum and so on, but my problem is not there, but there are similar ones, but I can't randomize below and above, but it seems to me that my randomizer is worse than just an ordinary randomizer. 🥲




Can't add 7 random digits with a fixed beginning in Javascript [closed]

I'm trying to represent a taxpayer number that starts with 50... and then add 7 random digits after.

What I've tried is: const contribuinteComp = 50 + Math.floor(Math.random() * 1000000000);




How to get an item in a list based on a number in Python? [closed]

I am trying to code something in Python that makes the user type random phrases. If you manage to find out how to do this, I would appreciate it.

import pyautogui
import random

phrases = ["Phrase1", "Phrase2", "Phrase3"]

while True:
    pyautogui.write(list.index(phrases, random.randint(1, len(phrases))))

I was expecting to run the code and be able to type a random phrase (e.g. running the code and either typing "Phrase1", "Phrase2", "Phrase3")




Is there a way to random 5 items from dict then sum up their values?

I'm trying to randomize 5 items from a dict then sum up the value of the 5 items?

import random

mydict = {
    1: {"name":"item1","price": 16}, 
    2: {"name":"item2","price": 14},
    3: {"name":"item3","price": 16}, 
    4: {"name":"item4","price": 14}, 
    5: {"name":"item5","price": 13},
    6: {"name":"item6","price": 16},
    7: {"name":"item7","price": 11}, 
    8: {"name":"item8","price": 12}, 
    9: {"name":"item9","price": 14},
    10: {"name":"item10","price": 14},
}

randomlist = random.sample(mydict.items(),5)
print(sum(randomlist))



jeudi 15 décembre 2022

Golang Strange random problems

A few years ago I wrote a simple "module" (https://github.com/parasit/rpgforge) to simulate dice rolls and "translate" human readable dice throw definiton to throws loops. Like "3d6" as 3 times roll six sides dice, etc.

I used it in my tools to support my hobby (pen & paper RPG). The code is simple, but so useful that I haven't really touched it for the last 4 years. However recently I needed another tool, imported my library and found the results very strange. Randomness seems to occur, but the results are returned as series of the same digits. I have no idea what's going on, and the only thing that has changed since the last time is golang from 1.18 to 1.19.

P.S. 1.19 is on win11, 1.18 is on second machine with ubuntu

Sample code:

package main

import (
    "fmt"
    "math/rand"
    "time"

    forge "github.com/parasit/rpgforge"
)

func main() {
    rand.Seed(time.Now().UTC().UnixNano())
    for x := 0; x < 10; x++ {
        fmt.Println(forge.ThrowDices("10d10"))
    }
}

Expected result (on old 1.18):

❯ go run ./main.go
{[6 6 2 6 7 7 10 3 4 3] 0}
{[1 7 7 8 6 1 3 3 6 3] 0}
{[7 4 5 1 3 9 6 7 1 1] 0}
{[1 1 7 2 10 4 5 6 10 7] 0}
{[2 10 10 1 10 3 9 10 3 6] 0}
{[2 8 1 3 1 3 5 4 6 2] 0}
{[3 9 4 5 9 2 4 7 6 6] 0}
{[3 5 7 1 6 4 8 10 9 2] 0}
{[3 6 4 8 1 7 8 10 4 1] 0}
{[2 9 2 8 9 8 5 6 7 2] 0}

But on 1.19 i got something like this:

{[1 1 1 1 1 1 1 1 1 1] 0}
{[1 1 1 1 1 1 1 1 1 1] 0}
{[1 1 1 1 1 1 1 1 1 1] 0}
{[1 1 1 1 1 1 1 1 1 1] 0}
{[8 8 8 8 8 8 8 8 8 8] 0}
{[8 8 8 8 8 8 8 8 8 8] 0}
{[8 8 8 8 8 8 8 8 8 8] 0}
{[8 8 8 8 8 8 8 8 8 8] 0}
{[8 8 8 8 8 8 8 8 8 3] 0}
{[3 3 3 3 3 3 3 3 3 3] 0}

What happened in 1.19 ???




python | how can modify EM algorithm to select random columns

I want to select a random set of columns from dataframe and then calculate probability, the best algorithm for probability is expectation–maximization (EM) algorithm, but with modification to select randomly. The final output is like that ( for every run, the algorithm selected random columns):

Feature    | likelihood 
 F1, F2, F3 |  56   
 F2, F4, F6 |  78 

the code:

import random

def em(data, columns, num_iterations):
  # Initialize the model parameters
  model_params = initialize_model_params(data, columns)

  for i in range(num_iterations):
    # Select a random subset of columns
    selected_columns = random.sample(columns, k=len(columns) // 2)

    # E step: calculate the expected value of the hidden variables using the selected columns
    expected_hidden_vars = calculate_expected_hidden_vars(data, selected_columns, model_params)

    # M step: update the estimates of the model parameters using the selected columns and the expected hidden variables
    model_params = update_model_params(data, selected_columns, expected_hidden_vars)

  # Return the maximum likelihood estimates of the model parameters
  return model_params

def initialize_model_params(data, columns):
  # Initialize the model parameters using the data in the columns
  # Return the initialized parameters

def calculate_expected_hidden_vars(data, columns, model_params):
  # Calculate the probabilities of the different values that the columns can take on
  # Use the current estimates of the model parameters and the probabilities to calculate the expected value of the hidden variables
  # Return the expected hidden variables

def update_model_params(data, columns, expected_hidden_vars):
  # Use the expected values of the hidden variables to update the estimates of the model parameters
  # Return the updated model parameters

how can definitions of the functions: initialize_model_params , calculate_expected_hidden_vars, update_model_params




How to obtain a random sample in order to their category?

I have a DF called 'listing_df', what I need is to compute the NA data from the variables 'number_of_reviews' and 'review_scores_rating' creating random samples according to the numbers of each group of 'room_type'.

I attach a picture of how the DF looks like:

listing_df.png

I tried first of all grouping by 'room_typeI:

test <- listings_df %>% group_by(room_type)

Then, I select the columns where I want to transform the Na data, and create the samples

test$number_of_reviews[is.na(listings_df$number_of_reviews)] <- 
  sample(listings_df$number_of_reviews, size = sum(is.na(listings_df$number_of_reviews)))

test$review_scores_rating[is.na(listings_df$review_scores_rating)] <- 
  sample(listings_df$review_scores_rating, size = sum(is.na(listings_df$review_scores_rating)))

I am not sure if it's createn the random data according the room_type, also I would like to know if it's possible to manage this creating a loop.

Thanks!




How to sort the websites by their popularity?

Im using the script currently and i cant seem to find out a way to sort the Websites by their popularity, im a beginner.

import random

# création d'un dictionnaire Hypertexte
Hypertext = {}
# création d'un dictionnaire pour le nombre de visite
Walk_Number = {}
# une variable pour le nombre total de visite
Total_Walk = 0
#liste des sites web
Websites = ["A","B","C","D","E","F"]
# les liens hypertextes
#  le dictionnaire possède des clés ( nom des sites)
# Qui contiennent des listes (liens hypertextes)
Hypertext["A"] = ["B","C","E"]
Hypertext["B"] = ["F"]
Hypertext["C"] = ["A","E"]
Hypertext["D"] = ["B","C"]
Hypertext["E"] = ["A","B","C","D","F"]
Hypertext["F"] = ["E"]
print(Hypertext)
# On initialise à 0.0 les visites des sites 
Walk_Number["A"] = 0.0
Walk_Number["B"] = 0.0
Walk_Number["C"] = 0.0
Walk_Number["D"] = 0.0
Walk_Number["E"] = 0.0
Walk_Number["F"] = 0.0

i = 0
while i < 1000:
    x = random.choice(Websites)
    while random.random() < 0.85:
        Walk_Number[x] = Walk_Number[x] + 1
        Total_Walk = Total_Walk + 1     
        x = random.choice(Hypertext[x])
    i = i + 1
print (Walk_Number)
print(Total_Walk)

I tried using the sort() function but i cant seem to find a way to sort it into the script




mercredi 14 décembre 2022

How to make this code more compactful and simpler to run?

I fairly started coding no more than 2 weeks now; not even for long, and I was inspired by a thread to make a random back to forth game between a Hero and a Monster where it randomly choose a certain number to decrease the health of either characters and go back and forth until once below 0, the survivor wins. Since I am still very new, I haven't been able to use functions to my advantage to simplify and shorten my code, is there any advice or altercations you would add to the code?

#Randomly generated battle between monster and hero
import random
import time

print('A monster ambushed you hero! Fight back!')
time.sleep(1.2)

hero = 100
monster = 100

chance1 = 1
chance2 = 2
chance3 = 3

while hero and monster > 0:
    print('The hero strikes the monster!')
    number1 = random.randint(1, 3)
    if number1 == 1:
        damage = random.randint(4, 10)
    if number1 == 2:
        damage = random.randint(11, 16)
    if number1 == 3:
        damage = random.randint(17, 25)
    sum1 = monster - damage
    monster = sum1
    time.sleep(1.5)
    print('Monster HP:' + str(sum1))
    if monster <= 1:
        print('Hero Wins!')
        break
    print('The monster attacks the hero!')
    number2 = random.randint(1, 3)
    if number2 == 1:
        damage = random.randint(4, 10)
    if number2 == 2:
        damage = random.randint(11, 16)
    if number2 == 3:
        damage = random.randint(17, 25)
    sum2 = hero - damage
    hero = sum2
    time.sleep(1.5)
    print('Hero HP:' + str(sum2))
    if hero <= 1:
        print('Monster Wins!')
        break

It may seem scrambled but its my first small project and I'd like any feedback so I can expand my knowledge to fluently make similar commands, thank you.




Is there a way to replicate np.random.rand() python function from C?

I want to get random numbers in C sampled in the same way that np.random.rand() does ... the problem is that with rand()/srand() C functions I am not getting good results (random numbers from rand() C function seem to have some pattern). Which is the best solution? call np.random.rand() from C ?

thanks




'builtin_function_or_method' object has no attribute 'choice'

from random import random ,choices
from turtle import Turtle ,Screen
p=Turtle()
p.color("red")
n=(1,2,3,4)
for f in range(0,50,+1):
    n=["1","2","3","4"]
    c=random.choice(n)
    if c==1:
        p.forward(20)
        if c==2:
            p.backward(20)
            if c==3:
                p.up
                p.forward(20)
                if c==4:
                    p.down
                    p.forward

The random.choice function raises the following error:

'builtin_function_or_method' object has no attribute 'choice'

Why does it raise the error and how can I solve the problem?




How to generate random string without using os and random library [duplicate]

I want to create a random 8 bytes string without using os.urandom or random library.

With os, I can do ''.join(os.urandom(8)).

With random, I can do ''.join(chr(random.randint(0, 255)) for _ in range(8)).

How can I do it without these 2 libraries?




mardi 13 décembre 2022

Changing the seed or a random number generator in c++

I have this program where I use the mersenne twister generator like so:

#include <iostream>
#include <random>
using namespace std;

unsigned seed = 131353;
mt19937 generator(seed);
normal_distribution<real> distribution(0.0, 1.0);

int main() {
    cout << distribution(generator);
}

for me it's convenient to declare this generator outside of main so that it is a global variable, so that I don't have to keep passing it as an argument in the functions I have;

but I want to read the seed from a file, which as far as I am aware can only be done inside the main() function.

Is it possible to declare the generator as a global variable and set the seed inside main()?

Thanks in advance

I tried reading the seed from a file outside main function, without success so far




lundi 12 décembre 2022

I'm trying to make a random name generator, but the output is off every time

The generator is supposed make 10 names and pull the names from the tuples first and last then randomly generate an index and assign it to either first or last then append/write each first + last name to the .txt file as well as put each name on a new line. It's supposed to also removed the names from the copied list to ensure there are no name duplicates.

def generateNames(firstName, lastName, file):
   
   
    for i in range (10):
        firstName = list(firstName)
        lastName = list(lastName)
        name = (random.choice(firstName) + " " + random.choice(lastName))
        print(name)        
    print("\t\tYour Generated Names:")    
    

Whenever the code generates the names it looks like this

Please enter a file name:
d

Hit Enter to Generate.

. x
x t
. t
t .
d .
d t
t t
x x
x x
t x
        Your Generated Names:


File has been created.

Rather than the full names.




Generate random numbers from a distribution given by a list of numbers in python

Let's say I have a list of (float) numbers:

list_numbers = [0.27,0.26,0.64,0.61,0.81,0.83,0.78,0.79,0.05,0.12,0.07,0.06,0.38,0.35,0.04,0.03,0.46,0.01,0.18,0.15,0.36,0.36,0.26,0.26,0.93,0.12,0.31,0.28,1.03,1.03,0.85,0.47,0.77]

In my case, this is obtained from a pandas dataframe column, meaning that they are not bounded between any pair of values a priori.

The idea now is to obtain a new list of randomly-generated numbers, which follow the same distribution, meaning that, for a sufficiently large sample, both lists should have fairly similar histograms.

I tried using np.random.choice, but as I do not want to generate one of the values in the original list but rather new values which are or not in it, but follow the same distribution, it does not work...




dimanche 11 décembre 2022

how can i generate a program that guess a word and apply by a button?

i made a button in an html document, that suppose to chose one word from a 20 words i defiend in a what supposed to be a nice guessing program that include a search bar which the user of the program guess one of the words at the search bar (from the 20 i defiend) and the program picks one word randomly and shows that after the user made his guess.
i did the button and search bar but when the user write a word and press the button to get the word that picked by the program nothing happens .
i guess that the problem is at the script i wrote.

 let teams = ["atalanta", "Bologna", "Cremonese", "Empoli", "Fiorentina", 
"Verona", "Inter", "Juventus", "Lazio", "Lecce", "Milan", "Monza",
 "Napoli", "Roma", "Salernitana", "Sampdoria", "Sassuolo", "Spezia",
  "Torino", "Udinese"];

  let secretTeam = teams[Math.floor(Math.random() * 20)];
  console.log(secretTeam);

document.querySelector('.search').addEventListener('.click' , function() {
const guess = teams(document.querySelector('.guess').value);

    if(guess === secretTeam) {
        document.querySelector('.messege').textContent = (secretTeam),'you right!';
        document.querySelector('body').style.backgroundColor = '#4ceb34';}
     
   else{
        document.querySelector('.messege').textContent = (secretTeam),'wrong answer';
        document.querySelector('body').style.backgroundColor = '#f71505';
   }
    
    
})

this is my script




Generate random number in csv file with python

I am struggling with an issue regarding CSV files and Python. How would I generate a random number in a csv file row, based of a condition in that row.

Essentially, if the value in the first column is 'A' I want a random number between (1 and 5). If the value is B I want a random number between (2 and 6) and if the value is C, and random number between (3 and 7).

CSV File

Letter Color Random Number
A Green
C Red
B Red
B Green
C Blue

Thanks in advance

The only thing I have found was creating a new random number dataframe. But I need to create a random number for an existing df.




How do we know the sample has unequally probability sampling, so we need weighted distribution?

I have the claim frequency data from this paper http://erepository.uonbi.ac.ke/bitstream/handle/11295/102825/Makori%2CVanis%20K_Modelling%20of%20Auto%20Insurance%20Claims%20Using%20Discrete%20Probability%20Distributions.pdf?sequence=1&isAllowed=y The data is attached. claim frequency data

I tried to fit the Poisson-Lindley distribution to this data. But, the chi-square test showed that PL Distribution didn't fit for this data. Even though, PL Distribution should fit for the overdispersion data.

Then, I tried to use Weighted Negative Binomial Poisson-Lindley distribution. I found the WNBPL distribution from this paper https://www.preprints.org/manuscript/201805.0026/v1 As a result, the WNBPL distribution fitted this data. As additional information, the Negative Binomial distribution also fitted the data. But, the WNBPL distribution slightly better fitted this data. I still can't understand why did we need add "negative binomial weight function ((x+r-1)!/(x!*(r-1)!)" for PL distribution for fit this data? I think this data has unequal probability sampling, so we need weighted distribution. But, I don't understand why did this data have unequal probability sampling? Advice and feedback would be greatly appreciated!




samedi 10 décembre 2022

How I can create multiple random shapes (Asteroids) using a JavaScript?

Using html class name, I have created a Asteroids shapes which is only static shape, but How I can create multiple random size of shapes using random in JavaScript?




how to make ::selection text background color random from selected colors

I want to make it so that every time someone highlights text on my sight, the highlight color is different. I have predefined colors already chosen and I will also give you the code I currently have.

currently with my code it just runs through each one in a sequence. I need to figure out how to make it so that it will give you a random color from my array.

<script> 
window.colors = ['#F78DA7','#CF2E2E','#FF6900','#FCB900','#7BDCB5','#00D084','#8ED1FC','#0693E3','#9B51E0']
window.order = 0

document.addEventListener("mousedown", function() {
document.head.insertAdjacentHTML('beforeend', '<style>::selection { background-color:' + window.colors[window.order] + '} ::-moz-selection { background-color:' + window.colors[window.order] + '} ::-o-selection { background-color:' + window.colors[window.order] + '} ::-ms-selection { background-color:' + window.colors[window.order] + '} ::-webkit-selection { background-color:' + window.colors[window.order] + '}</style>');
window.order = window.order + 1
if (window.order > window.colors.length - 1){
window.order = 0
}
});
 </script>



Python generating a deterministic random number based on user input

I've been messing around with chatgpt and wrote a function that generates a seemingly random answer, my important condition was that it needed to be output the same number when the equation was entered again, the ultimate liar:

import hashlib
import random

# Define constants for the minimum and maximum values of the
# random number function
RANDOM_NUMBER_MIN = 0
RANDOM_NUMBER_MAX = 99_999

# Define the random_number function
def random_number(input_string):
  # Create a hash object and update it with the input string
  hash_object = hashlib.sha256()
  hash_object.update(input_string.encode('utf-8'))

  # Get the hexadecimal representation of the hash
  hex_hash = hash_object.hexdigest()

  # Convert the hexadecimal hash to an integer and use it to seed the
  # random number generator
  random.seed(int(hex_hash, 16))

  # Generate and return a random number in the range
  # defined by the RANDOM_NUMBER_MIN and RANDOM_NUMBER_MAX constants
  return random.randint(RANDOM_NUMBER_MIN, RANDOM_NUMBER_MAX)

# Define the main function
def main():
  # Prompt the user to enter an equation
  equation = input("Enter an equation (e.g. 2 + 2): ")

  # Print the result of the random number function
  print(f"The result of the random number function is: {random_number(equation)}")

# Call the main function
if __name__ == "__main__":
  main()

Example:

Enter an equation (e.g. 2 + 2): 1 + 1
The result of the random number function is: 68959

I then generated a function that brute forces 10 correct answers.

...
# Define constants for the minimum and maximum values of the
# random number function and the number of solutions to print
RANDOM_NUMBER_MIN = 0
RANDOM_NUMBER_MAX = 99_999
SOLUTION_COUNT = 10
...
# Define the main function
def main():
  # Generate all combinations of numbers from RANDOM_NUMBER_MIN to RANDOM_NUMBER_MAX
  # where the result is between RANDOM_NUMBER_MIN and RANDOM_NUMBER_MAX
  found_solutions = 0
  for result in range(RANDOM_NUMBER_MIN, RANDOM_NUMBER_MAX + 1):
    # Generate all combinations of numbers from RANDOM_NUMBER_MIN to result
    # where the result is equal to result
    for num1 in range(RANDOM_NUMBER_MIN, result + 1):
      num2 = result - num1
      equation = f"{num1} + {num2}"
      if random_number(equation) == result:
        print(f"{equation} = {result}")
        found_solutions += 1
        if found_solutions == SOLUTION_COUNT:
          return

  if found_solutions < SOLUTION_COUNT:
    print(f"Only found {found_solutions} solutions out of {SOLUTION_COUNT}.")
...

Output:

411 + 32 = 443
63 + 436 = 499
382 + 289 = 671
424 + 247 = 671
491 + 232 = 723
855 + 63 = 918
898 + 99 = 997
119 + 928 = 1047
1031 + 393 = 1424
566 + 887 = 1453

Creating this took forever (I could've probably written this quicker), I constantly had to correct it, but maybe you've suggestions on how to improve this?

You could for example evaluate the expression and then add or subtract a number greater than 0, but that wouldn't be safe.




(this is a game) there should be 4 random digits, only 8 attempts are allowed

Task 1: Set up a Python project by following the instructions and routine practiced in all tutorial exercises. Task 2: Implement a human-computer interaction mode, where the following will be possible:

  1. Visualize the user interface as depicted by figure 2.
  2. The user should be in a position to mark interactively the start and end of the game by selecting start and end options from the menu.
  3. The system should be able to generate a 4-digit random number where each digit is in the range of 1-6.
  4. The user should be able to enter a 4-digit number where each digit is in the range of 1-6.
  5. The system should validate the 4-digit number entered by the user and should NOT accept any number where the number does not fall into criteria specified in point 4. and should give an appropriate error message if the criteria do not match.
  6. The user should be able to guess a maximum of 8 guesses and should be able to terminate the game without going into 8 th guess (if he/she wishes) by entering ‘0000’ as the guess. Task 3: Design and implement your “GameInt” game as specified by the problem specification. Task 4: A brief report (less than 10 A4 size pages) which gives the following. • Table of contents • Introduction about the problem • Flowchart or pseudocodes which explains the program o This can be parts of the programs if you implement modular coding • Actual python codes for the program (final solution) • Any other vital information you wish to present (e.g any assumptions you made.) • Screenshots of the working program (Which includes positive and negative results) • Conclusion Task 5: Demonstrate and defend the implemented solution at viva by a) Visualizing the menu as of figure 1. b) Marking the start and end of the program. c) Demonstrate the points specified in Task 2. d) Justifying the results.

I want to limit the attempts only for 8 times




I'm generating a list of 100 random "names", now I need to follow it up with 100 more names and 100 random numbers. C#

I'm making a program that generates the "names" (random lines of text from the ASCII) that are the names of movies in this instance. I should follow them up with a "name" of a director for each (can also be generated from the ASCII), and after that the random year that is the year the "movie" was made (from 1896 to 2021).

I have two separate functions that randomize the names of the movies and directors, but I'm confused with the supposed placement of the Console.Writeline which the intelligence only allows inside their own loops. Otherwise it doesn't seem to be able to use the values "directorname" and "moviename".

I need it to write the names in a single line, ai. (KHGTJ, KGHTJF).

Also I need a way to generate a random year from 1896 to 2021 that is printed after the names of the movie, and director, ai. (KFJU, MDDOS, 1922).

private static void GenerateRandomNames()
        {
            Random random = new Random();
            char y = (char)65;

            for (int p = 0; p < 100; p++)
            {
                string directorname = "";
                for (int m = 0; m < 5; m++)
                {
                    int b = random.Next(65, 90);
                    y = (char)b;
                    directorname += y;
                }
                Console.WriteLine(directorname);
            }

            Random rnd = new Random();
            char x = (char)65;

            for (int j = 0; j < 100; j++)
            {
                string moviename = "";
                for (int i = 0; i < 5; i++)
                {
                    int a = rnd.Next(65, 90);
                    x = (char)a;
                    moviename += x;

                }
                Console.WriteLine(moviename);
            }
            Console.WriteLine();

I need to fix the plecement of the Console.Writeline() so it can print both names in the same line, and be able to print the year after them.

I've tried placing the Console.Writeline() outside the loops, but of course it can't then use the name. But this way it prints them the wrong way.




vendredi 9 décembre 2022

Function to generate a random weighted graph freezes after a certain threshold edges

So I'm trying to generate a random graph with n nodes and n*4 edges by having the nodes 1, 2, 3, ..., n and the edges being an array of triples which stores endpoint of edge 1, endpoint of edge 2 and the weight of the edge:

struct edge{
    int endpoint1;
    int endpoint2;
    int weight;
};

This is the function to generate the array of edges (of triples):

edge* generateRandomGraph(int nrOfNodes)
{
    int adjMatrix[nrOfNodes+1][nrOfNodes+1] = {0};

    int nrOfEdges = nrOfNodes*4 ;

    edge *edges = new edge[nrOfNodes+1];
    
    int counter = 0;

    while(counter < nrOfEdges)
    {
        int a = 1 + rand() % nrOfNodes;
        int b = 1 + rand() % nrOfNodes;

        if(a != b)
        if(adjMatrix[a][b] == 0)
        {
            adjMatrix[a][b] = 1;
            adjMatrix[b][a] = 1;
            edges[counter].endpoint1 = a;
            edges[counter].endpoint2 = b;
            edges[counter].weight = rand() % 100;
            counter++;
        }
    }
                        
    return edges;
}

It functions properly until one point, at element edges[31] when it freezes. What could be the problem? Debugger does not specify any error, but when I try to print the values it breaks. Maybe some segmentation fault because the filling of the array is based on the rand()?




Random answer Android studio Kotlin

I'm a beginner and I wanted to make a code that will print "yes" or "no" on random when the button is clicked. (Using kotlin) here's my code package com.example.calculator

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import android.view.View

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        fun buttonPressed(view: View){
            val randomword = Random. ("yes" or "no")
            textView.text = randomword
        }
    }
}



I need to sort a printed array of numbers by size. C# [duplicate]

So in my homework assignment we are supposed to: Make an array with ten integers, sort them to an order of size, and print them.

A former answer told me how to print the array, now I just have to sort it.

I've managed to make and array that generates the numbers, prints them in the console, but I'm having trouble on having them sorted into an order of size.

Here is what I've got done, and now I'm stuck here:

internal class Program
    {
        private static void RandomNumbers()
        {
            int Min = 0;
            int Max = 100;

            int[] ints = new int[10];
            Random randomNum = new Random();

            for (int i = 0; i < ints.Length; i++)
            {
                ints[i] = randomNum.Next(Min, Max);
            }

            for (int i = 0; i < ints.Length; i++)
            {
                Console.WriteLine($"{i}: {ints[i]}");
            }
        }

        static void Main(string[] args)
        {
            RandomNumbers();
        }
    }

I haven't found a way to sort the randomized numbers by size. It's the last part of the assignment.




jeudi 8 décembre 2022

Dynamic grid using prettytable/tabulate

I want to create a dynamic grid with 2 digits random numbers. The grid will have some empty slots with no numbers, which again randomly generated. If the columns consists of one or more empty spaces from top to bottom "NO" should be display under that columns. If the entire column consists of numbers from top to bottom "OK" should be displayed under that column. The grid size is dynamically passed as a command line argument to the program. If no dimensions are passed, the default dimension for the grid is 5x5. The lowest dimensions must be 3x3 while the highest dimension must be 9x9. Some possible commands would be, • C:>perc 3x4

  1. The above creates a 3x4 grid • C:>perc
  2. The above creates a 5x5 default grid

This is what I tried,

nums = [] for i in range(3): nums.append([]) for j in range(1, 4): nums[i].append(j) print("3X3 grid with numbers:") print(nums)

How can I do this question?



In MySql, How to Associate Three Random Rows from One Table to Each Row of a Another Table

I have a table of Friends (Ann, Bob, Carl) and a table of Fruits (Apple, Banana, Cherry, Date, Fig, Grapefruit)

I need to create an intersection table (Friends X Fruit) that associates each Friend with 3 randomly selected fruits.

For example: Ann might be associated with Cherry, Date, Fig Bob might be associated with Apple, Fig, Banana Carl might be associated with Banana, Cherry, Date

I have developed a script that works well for only ONE friend (pasted below), but I am struggling to expand the script to handle all of the friends at once.

(If I remove the WHERE clause, then every friend gets assigned the same set of fruits, which doesn't meet my requirement).

Setup statements and current script pasted below.

Thank you for any guidance!

CREATE TABLE TempFriends ( FirstName VARCHAR(24) );
CREATE TABLE TempFruits ( FruitName VARCHAR(24) );
CREATE TABLE FriendsAndFruits( FirstName VARCHAR(24), FruitName VARCHAR(24) );
INSERT INTO TempFriends VALUES ('Ann'), ('Bob'), ('Carl');
INSERT INTO TempFruits VALUES ('Apple'), ('Banana'), ('Cherry'), ('Date'), ('Fig'), ('Grapefruit');

INSERT INTO FriendsAndFruits( FirstName, FruitName )
SELECT FirstName, FruitName
FROM TempFriends
INNER JOIN  ( SELECT FruitName FROM TempFruits ORDER BY RAND() LIMIT 3 ) RandomFruit
WHERE FirstName = 'Bob';



How can I generate a random position for an element so that it does not overlap with the position of a different element in javascript?

I am trying to generate random player locations that do not overlap. My initial assumption is that maybe I should (1) generate random positions, (2) check if random positions are overlapping, (3) regenerate positions that are overlapping.

I do not want the flowers or the players to overlap when they are initially generated. Another idea that I had: is there a way I can make a grid system, where players and flowers are initially generated at a spot on the grid and the random function shuffles through grid points?

// game.js

let mapWidth = 200;
let mapHeight = 200;

// let playerWidth = 10;
// let playerHeight = 10;

let flowerWidth = 10;
let flowerHeight = 10;

let player; 

let gameMap = document.createElement('div');
gameMap.setAttribute('id', 'gameMap');
document.body.append(gameMap);
gameMap.style.width = mapWidth  + 'px';
gameMap.style.height = mapHeight + 'px';

const leftKey = "ArrowLeft";
const rightKey = "ArrowRight";
const upKey = "ArrowUp";
const downKey = "ArrowDown";

window.onkeydown = function(event) {
  const keyCode = event.key;
  event.preventDefault();

    if(keyCode == leftKey) {  
      player.stepLeft();
    } else if(keyCode == rightKey) {
      player.stepRight();
    } else if(keyCode == upKey) {
      player.stepUp();
    } else if(keyCode == downKey) {
      player.stepDown();
    } 
}
  

// Game Objects & Players
class Player {
  constructor(posX, posY, playerId, isMe) {
      // this.posX = 0; // for debugging
      // this.posY = 0; // for debugging
      this.posX = posX;
      this.posY = posY;
      this.width = 10;
      this.height = 10;
      this.playerId = playerId;
      this.speed = 2;
      this.isMe = isMe;
      this.elm;
      this.myFlowers = [];
  }
  
  stepRight(){
    // check if step would collide
    if( this.isColliding(this.posX + this.speed, this.posY) == true ){

    }else{
      this.posX = this.posX + this.speed;
      socket.emit('playerMovement', ({x: this.posX, y: this.posY})); 
      this.updatePosition();
    }
    // if not
    // apply step to this.posX 
    // update the DOM (gameMap)
    // tell server that player moved
  }
  stepLeft() {
    if( this.isColliding(this.posX - this.speed, this.posY) == true ){

    }else{
      this.posX = this.posX - this.speed;
      socket.emit('playerMovement', ({x: this.posX, y: this.posY})); 
      this.updatePosition();
    }

  }
  stepUp() {
    if( this.isColliding(this.posX, this.posY - this.speed) == true ){

    }else{
      this.posY = this.posY - this.speed;
      socket.emit('playerMovement', ({x: this.posX, y: this.posY})); 
      this.updatePosition();
    }

  }
  stepDown() {
    if( this.isColliding(this.posX, this.posY + this.speed) == true ){

    }else{
      this.posY = this.posY + this.speed;
      socket.emit('playerMovement', ({x: this.posX, y: this.posY})); 
      this.updatePosition();
    }

  }
  isColliding(nextStepX, nextStepY) {
    //    - bounds of map
    if(nextStepX >= 0 && nextStepX < mapWidth - this.width && nextStepY >= 0 && nextStepY < mapHeight - this.height) {
    //    - other players
      for(let i = 0; i < activePlayers.length; i++) {
        
        if(activePlayers[i].playerId != this.playerId) {
         // other
         let other = activePlayers[i];
         if((other.posX > nextStepX - other.width) && 
            (other.posX <= nextStepX + this.width) && 
            (other.posY > nextStepY - other.height) && 
            (other.posY <= nextStepY + this.height) ) {
              return true
            }
        }
        // console.log(activePlayers[i]);      
      }
      return false
    } else {
      return true
    }
  }
  updatePosition() {
    // if me:
    if(this.isMe === true) {
      gameMap.style.left = - this.posX  + 'px';
      gameMap.style.top = - this.posY  + 'px';
    } else {
      this.elm.style.left = this.posX + 'px';
      this.elm.style.top = this.posY  + 'px';
    }
    // else:
    // move actal this.elm to location
  }
  createElement(){
    this.elm = document.createElement('div');
    // if me....
    if(this.isMe === true) {
      this.elm.setAttribute('class', 'mainPlayer');
    // if not me...
    } else {
      this.elm.setAttribute('class', 'otherPlayer');
    }
    // else
    //  ///
    this.elm.style.width = this.width + 'px';
    this.elm.style.height = this.height + 'px';
  
    // append the mainPlayer to the map
    gameMap.append(this.elm)
  
    // assign element id as the socket id
    this.elm.id =  this.playerId;
  
    // push id to activePlayers array 
    // activePlayers.push(playerInfo.playerId);
  
    // name tag for debug tracking
    let nameTag = document.createElement("p");
    nameTag.innerHTML = this.playerId;
    this.elm.append(nameTag)

     // set map coordinates from random player location
    this.updatePosition();
  }
};

class worldObject {
    constructor(name, posX, posY, width, height) {
        this.name = name;
        this.posX = posX;
        this.posY = posY;
        this.width = width;
        this.height = height;
    }
  };
  
  class Flower extends worldObject { 
    constructor (name, posX, posY, isPicked) {
        super(name, posX, posY); 
        // this.scientific = scientific;
        // this.rarity = rarity;
        this.posX = posX;
        this.posY = posY;
        this.width = 10;
        this.height = 10;
        this.flowerElm;
        this.isPicked = isPicked;
    }
    createElement(){
      this.flowerElm = document.createElement('div');

      this.flowerElm.setAttribute('class', 'flower');

      this.flowerElm.style.width = this.width + 'px';
      this.flowerElm.style.height = this.height + 'px';

      gameMap.append(this.flowerElm)

      this.updatePosition();
    }
    updatePosition() {
      this.flowerElm.style.left = this.posX + 'px';
      this.flowerElm.style.top = this.posY  + 'px';
    }
  };


  // let flowers = [
  //   ghostOrchid = new Flower ("Ghost Orchid", "Dendrophylax Lindenii", 10, randomPosition() - 5, randomPosition() - 5, 10, 10),
  // ];


let activePlayers = [];
let activeObjects = [];
let activeFlowers = [];

let socket = io();
 
socket.on('currentPlayers', function (players) {
  Object.keys(players).forEach(function (id) {
    // me:
    if (players[id].playerId === socket.id) {
      // create an asset for the main player
      if(activePlayers.indexOf(socket.id) === -1) {
        console.log("adding main player");
        // addPlayer(players[id]);
        player = new Player (players[id].x, players[id].y, players[id].playerId, true);
        // push player (mainPlayer) instance to activePlayers array
        activePlayers.push(player);
        // create mainPlayer element 
        player.createElement();
      }
      // or them:
    } else {
      // otherwise, create an other player
      if(activePlayers.indexOf(socket.id) === -1) {
        console.log("adding other player");
        // addOtherPlayers(players[id]);
        let guestPlayer = new Player (players[id].x, players[id].y, players[id].playerId, false);
        // push player (mainPlayer) instance to activePlayers array
        activePlayers.push(guestPlayer);
        // create mainPlayer element 
        guestPlayer.createElement();
      }
    }
  });
});
socket.on('newPlayer', function (playerInfo) {
  console.log("A new player has joined");
  // addOtherPlayers(playerInfo);
  let guestPlayer = new Player (playerInfo.x, playerInfo.y, playerInfo.playerId, false);
  // push player (mainPlayer) instance to activePlayers array
  activePlayers.push(guestPlayer);
  // create mainPlayer element 
  guestPlayer.createElement();
});
socket.on('playerMoved', function (playerInfo) {
  // console.log("a player moved");

  // console.log('delete this: ', players[i].playerId.indexOf(socket.id));
  let movedPlayer = activePlayers.find(player => player.playerId === playerInfo.playerId);
  // console.log(movedPlayer);

  movedPlayer.posX = playerInfo.x;
  movedPlayer.posY = playerInfo.y;

  movedPlayer.updatePosition();

  // let playerOnMove = document.getElementById(playerInfo.playerId)
  // // let movePlayer = document.getElementById(playerInfo.playerId);
  // playerOnMove.style.left = playerInfo.x + 'px';
  // playerOnMove.style.top = playerInfo.y + 'px';

  // console.log(playerInfo.playerId + " moved to: " + playerInfo.x, playerInfo.y);
});
socket.on('flowerData', function (flowerData) {

  
  for(let i=0; i < 5; i++) {
    console.log(flowerData[i].x, flowerData[i].y);
    let flower = new Flower (flowerData[i].id, flowerData[i].x, flowerData[i].y, flowerData[i].isPicked);

    activeFlowers.push(flower);
    // create mainPlayer element 
    flower.createElement();
  }
  
  // gameMap.append(flower);
  // if collide with flower: emit and push to player's inventory
  // this.socket.emit('flowerCollected');
  
});


socket.on('disconnectUser', function (playerId) {
    // remove the div element of the disconnected player
    let el = document.getElementById(playerId);
    console.log(el);
    el.remove(gameMap);

    console.log(activePlayers);
    for(let i = 0; i < activePlayers.length; i++) {
      // console.log('delete this: ', players[i].playerId.indexOf(socket.id));
      let disconnectedPlayer = activePlayers[i].playerId.indexOf(socket.id);
      activePlayers.splice(disconnectedPlayer, 1);
    }

    console.log("A player has left the game");
});

// server.js

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

const port = process.env.PORT;

app.use(express.static('public'));

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

function randomPosition() {
  let random = parseInt( (50 + Math.random()*100));
  return random
}
 
let flower = [
  {
    id: "flowerOne",
    x: randomPosition() - 5,
    y: randomPosition() -5,
    isPicked: false
  },
  {
    id: "flowerTwo",
    x: randomPosition() - 5,
    y: randomPosition() -5,
    isPicked: false
  },
  {
    id: "flowerThree",
    x: randomPosition() - 5,
    y: randomPosition() -5,
    isPicked: false
  },
  {
    id: "flowerFour",
    x: randomPosition() - 5,
    y: randomPosition() -5,
    isPicked: false
  },
  {
    id: "flowerFive",
    x: randomPosition() - 5,
    y: randomPosition() -5,
    isPicked: false
  }
]
players = {};


// while debugging. positions will; mot be random,
// let y = 100; // for debugging
// let x = 10; // for debugging

io.on('connection', function (socket) {
  console.log('a user connected: ', socket.id);

    // create a new player and add it to our players object
  players[socket.id] = {
    // x and y positioning of the map:
    // subtract half of the playerWidth and playerHeight 
    x: randomPosition() - 5,
    y: randomPosition() - 5,
    // x: x, // for debugging
    // y: y, // for debugging
    playerId: socket.id,
  };
  // x += 50; // for debugging
  // if(x>200) x=10; // for debugging

  console.log(players);

  // send the players object to the new player
  socket.emit('currentPlayers', players);
  // update all other players of the new player
  socket.broadcast.emit('newPlayer', players[socket.id]);
  // send flowers to the new player
  socket.emit('flowerData', flower);
  console.log(flower);

  // when a player moves, update the player data
  socket.on('playerMovement', function (movementData) {
    // console.log(movementData);
    players[socket.id].x = movementData.x;
    players[socket.id].y = movementData.y;
    // console.log(movementData.x, movementData.y)
    // emit a message to all players about the player that moved
    socket.broadcast.emit('playerMoved', players[socket.id]);
  });

  // when a player disconnects, remove them from our players object
  socket.on('disconnect', function () {
    console.log('user disconnected: ', socket.id);
    delete players[socket.id];
    // emit a message to all players to remove this player
    io.emit('disconnectUser', socket.id);
  });
});


server.listen(3000, () => {
  console.log('listening on *:3000');
});