lundi 24 février 2020

I cant display my downloaded images on my app

in the update status method:

public void updateStatus() {

    Random random = new Random();
    URLSize = celebURLs.size();

    if (URLSize <= 0) {
        URLSize++;
        //chosenImage = random.nextInt(URLSize);
    } else {
        chosenImage = random.nextInt(URLSize);
    }

    ImageDownloader imageDownloader = new ImageDownloader();
    Bitmap celebPics;

    try {
        celebPics = imageDownloader.execute(celebURLs.get(chosenImage)).get();
        imageView.setImageBitmap(celebPics);

        locationOfCorrectAnswer = random.nextInt(4);
        int incorrectAnswer;
        for (int i = 0; i < 4; i++) {
            if (i == locationOfCorrectAnswer) {
                answers[i] = chosenNames.get(chosenImage);
            } else {
                incorrectAnswer = random.nextInt(celebURLs.size());
                while (incorrectAnswer == chosenImage) {
                    incorrectAnswer = random.nextInt(celebURLs.size());
                }
                answers[i] = chosenNames.get(incorrectAnswer);
            }

        }
        button1.setText(String.format("%s", answers[0]));
        button2.setText(String.format("%s", answers[1]));
        button3.setText(String.format("%s", answers[2]));
        button4.setText(String.format("%s", answers[3]));

    } catch (Exception e) {
        e.printStackTrace();
    }

}

I changed the code because it brought up an exception"IllegealArgumentException n must be positive" but even after changing the code to always increment the size of random generated values of the array list, it still wont work




Select a random object in javascript/jquery

Can anyone tell me how to select a random key and corresponding item value from the following object using Javascript/JQuery?

var choose_one = {
  "key 1" : "item 1",
  "key 2" : "item 2",
  "key 3" : "item 3"
};

Many thanks.




Generate random number with a loop

I plan to generate a list of random numbers in a certain way as bellow:

list1 = []
rand = random.randint(1, 10)
for i in range (10):
   list1.append(rand)
list1

but the result is a list of repeating of a same number as bellow:

[8, 8, 8, 8, 8, 8, 8, 8, 8, 8]



dimanche 23 février 2020

Random number generator in c program is not generating correct random numbers

I am working on a project about a game that involves creating randomly generated rooms with either monsters, prizes, or empty. However, every time I run the program it sets the room as a prize, and even generates incorrect numbers for the amount of points the prize gives you.

#include <stdio.h>
#include <stdlib.h>
#include "monsterbattle.h"
#include <time.h>

int main(int argc, char *argv[]) {

Character user;
int numRooms;

srand(time(NULL));

user.hitPoints = 50;
user.experiencePoints = 0;

printf("Welcome to Monster-Battle!\n");
printf("Enter the amount of rooms you would like to endure: ");
scanf("%d", &numRooms);

printf("You have decided to endure %d rooms, good luck!\n", numRooms);
printf("----------------\n");
printCharacter(user);

struct Room *roomArray = malloc(sizeof(struct Room) * numRooms);

fillRooms(roomArray, numRooms);

enterRoom(roomArray, user, numRooms);

free(roomArray);

return 0;

}

Here is my main function, where I call all of my functions.

#include <stdio.h>
#include <stdlib.h>
#include "monsterbattle.h"
#include <time.h>

void printCharacter(Character c) {

printf("Player Stats: (HP: %d XP: %d)\n", c.hitPoints, c.experiencePoints);

}

int getRandomNumber(int min, int max) {

return min + rand() % (max+1 - min);

}

void fillRooms(Room *rooms, int length) {

for (int i = 0; i < length; i++) {

int randomNum = getRandomNumber(0, 9);

if (randomNum == 0) {
rooms[i].type = EMPTY;
}

else if ((randomNum >= 1) && (randomNum <= 4)) {
rooms[i].type = PRIZE;
rooms[i].prize.points = getRandomNumber(5, 10);
}

else if ((randomNum >= 5) && (randomNum <= 9)) {
rooms[i].type = MONSTER;
rooms[i].monster.hitPoints = getRandomNumber(10, 30);

if (rooms[i].monster.hitPoints % 3 == 0) {
rooms[i].monster.experiencePoints = 1;
}
else if (rooms[i].monster.hitPoints % 3 != 0) {
rooms[i].monster.experiencePoints = 0;
}

}

}

}

void enterRoom(Room *room, Character player, int length) {

for (int i = 0; i < length; i++) {

printf("----------------\n");
printf("ROOM %d OF %d...\n", i+1, length);

if (room[i].type = EMPTY) {
printf("This room is empty.\n");
printCharacter(player);
}
if (room[i].type = EMPTY) {
printf("This room is empty.\n");
printCharacter(player);
}

else if (room[i].type = PRIZE) {
printf("This room has a prize. (PTS: %d)\n", room[i].prize.points);
player.hitPoints = player.hitPoints + room[i].prize.points;
printf("You gained %d hit points!\n", room[i].prize.points);
printCharacter(player);
}

else if (room[i].type = MONSTER) {
printf("This room has a monster. (HP: %d XP: %d)\n", room[i].monster.hitPoints, room[i].monster.experiencePoints);
player.hitPoints = player.hitPoints - room[i].monster.hitPoints;
player.experiencePoints = player.experiencePoints + room[i].monster.experiencePoints;
printf("You lost %d hit points!\n", room[i].monster.hitPoints);

if(room[i].monster.experiencePoints = 1) {
printf("You gained %d experience point!\n", room[i].monster.experiencePoints);
}

if(player.hitPoints <= 0) {
printf("Sorry, you died! Better luck next time...\n");
}

printCharacter(player);
}

}

if(player.hitPoints > 0) {
printf("----------------\n");
printf("Congratulations! You survived the game!\n");
}

}

and here is where I define all of my functions. Any help would be appreciated!




Generate "scattered" items, that do not overlap

This is a question that i had to solve, but have been banging my head against a wall for the past 5 days. There must be something really simple that i am missing, or misunderstanding, as the logic seems 100% correct in my head, but it just won't work.

I need to draw "scattered" houses, that do not over lap, 100 of them. I have to use turtle to draw them, so i have X and Y coordinates. And X and Y list for verification purposes, to see if a house is already in that place.

What i am doing is drawing a "house" (square with a triangle on top) on the randomized coordinates, I loop while the number of houses is less than 100. On each loop i randomize the x and y coordinates, from where i start drawing each house with turtle. I check if the value is already in the X and Y verification lists, and also if my new X and Y are +/- the size of the house (treating it as a square)

import turtle
import time
import random
t = turtle.Turtle()
turtle.screensize(1920,1000)
x_verif = []
y_verif = []
t.speed(0)
collision = None


def square():
    for s in range(0, 4):
        t.forward(90)
        t.left(90)

def triangle():
    for s in range(0, 2):
        t.left(-60)
        t.forward(52)

def house():
    square()
    t.left(90)
    t.forward(90)
    triangle()

def scatter():
    print("a")
    house()
    x1 = random.randint(-850, 850)
    y1 = random.randint(-380, 380)
    count = 0
    while count < 100:
        print("a2")
        i = 0
        u = 0
        collision = False
        for  tries in range (0, 2):
            print("a3")
            x_verif.append(x1)
            y_verif.append(y1)
        while u < 100:
            print("a4")

            print(x_verif, y_verif, x1, y1)
            while i < len(x_verif):
                x1 = random.randint(-850, 850)
                y1 = random.randint(-380, 380)
                print(x1, y1)
                if x1 not in x_verif and (x1 > x_verif[i]+91 or x1 < x_verif[i]-91):
                    if y1 not in y_verif and (y1 > y_verif[i]+142 or y1 < y_verif[i]-142):
                        collision = False
                else:
                    collision = True
            if collision == False:
                            t.penup()
                            t.hideturtle()
                            t.setx(x1)
                            t.sety(y1)
                            t.pendown()
                            house()
                            x_verif.append(x1)
                            y_verif.append(y1)
                            count += 1
            i += 1
        u += 1


scatter()

Sorry for the ugly code, and the simplicity behind it. I would love to use list comprehensions for this, but i do not know where my logic fails at the moment. This is like my 100th try, as of this version it only draws the initial house and i think it loops infinitely somewhere....

My problem lies in looping through the whole lists for every new value. Do i need to loop through them every time, or is there some IF condition that I can use? Edit: It keeps on looping through random values, but none of them are accepted by the two IF statements that i'm using.

On a side note: With my current code they also change direction of drawing every time... No idea why is that happening....




How can I generate random points faster in a large arrays?

I am trying to generate random points inside a 3d pepper like shape however when the arr_size is large it takes too long to generate these points.

arr_size is (30,30,30) it takes very little time to generate 1000 random point inside the 3d shape however when arr_size = (265,490,286) it takes a realy long time.

from matplotlib import pyplot as plt
import numpy as np


def create_bin_pepper(arr_size, center):
    coords = np.ogrid[:arr_size[0], :arr_size[1], :arr_size[2]]
    c = 10
    a1 = np.random.randint(low=5,high=10)
    b1 = np.random.randint(low=7,high=10)
    a2 = np.random.randint(low=5,high=10)
    b2 = np.random.randint(low=7,high=10)
    a3 = np.random.randint(low=5,high=10)
    b3 = np.random.randint(low=7,high=10)
    ellipse1 = ((np.square(coords[0] - center[0]))/np.square(a1) + (np.square(coords[1]-center[1]))/np.square(b1)  + (np.square(coords[2]-center[2]))/np.square(c)  <= 1)
    ellipse2 = ((np.square(coords[0] - center[0]-3))/np.square(a2) + (np.square(coords[1]-center[1]-5))/np.square(b2)  + (np.square(coords[2]-center[2]))/np.square(c)  <= 1)
    ellipse3 = ((np.square(coords[0] - center[0]+3))/np.square(a3) + (np.square(coords[1]-center[1]-5))/np.square(b3)  + (np.square(coords[2]-center[2]))/np.square(c)  <= 1)
    pepper = ellipse1|ellipse2|ellipse3
    pepper2 = np.where(pepper==1,230,pepper)

    for im in range(0,1000):
        #r2=1
        centre_x1 = np.random.randint(low=center[0]-a1+4,high=center[0]+a1-4)#low=11,high=20
        centre_y1 = np.random.randint(low=center[1]-b1+4,high=center[1]+b1-4)#low=15,high=23
        centre_z1 = np.random.randint(low=center[2]-c+4,high=center[2]+c-4)#low=10,high=20

        centre_x2 = np.random.randint(low=center[0]-a2+4,high=center[0]+a2-4)#low=11,high=20
        centre_y2 = np.random.randint(low=center[1]-b2+4,high=center[1]+b2-4)#low=15,high=23
        centre_z2 = np.random.randint(low=center[2]-c+4,high=center[2]+c-4)#low=10,high=20

        centre_x3 = np.random.randint(low=center[0]-a3+4,high=center[0]+a3-4)#low=11,high=20
        centre_y3 = np.random.randint(low=center[1]-b3+4,high=center[1]+b3-4)#low=15,high=23
        centre_z3 = np.random.randint(low=center[2]-c+4,high=center[2]+c-4)#low=10,high=20

        inside_ellipse1 = ((np.square(coords[0] - centre_x1))/np.square(a1) + (np.square(coords[1]-centre_y1))/np.square(b1)  + (np.square(coords[2]-centre_z1))/np.square(c)  <= (1/((np.square(a1))*(np.square(b1))*(np.square(c)))))
        inside_ellipse2 = ((np.square(coords[0] - centre_x2-3))/np.square(a2) + (np.square(coords[1]-centre_y2-5))/np.square(b2)  + (np.square(coords[2]-centre_z2))/np.square(c)  <= (1/((np.square(a2))*(np.square(b2))*(np.square(c)))))
        inside_ellipse3 = ((np.square(coords[0] - centre_x3+3))/np.square(a3) + (np.square(coords[1]-centre_y3-5))/np.square(b3)  + (np.square(coords[2]-centre_z3))/np.square(c)  <= (1/((np.square(a3))*(np.square(b3))*(np.square(c)))))

    pepper2 = inside_ellipse1 | inside_ellipse2 | inside_ellipse3 | pepper2
    pepper3 = np.where((pepper2!=230)&(pepper2!=0),160,pepper2)
    return pepper3

arr_size = (265,490,286)
sphere_center1 = (133,216,40)

pepper = create_bin_pepper(arr_size,sphere_center1)
axis = pepper[:,:,40]
plt.imshow(axis,cmap='gray')#,interpolation='bicubic'
plt.show()




java: method (in enum) to not to return same names [duplicate]

So basicly I need the getRandomNameCourseAsString() return name of subject, but I call it in for(..), so it can return same subject. I don't want to see same subject twice, so i tried this method but it gives me

java.lang.ArrayIndexOutOfBoundsException: 43

Commented lines is working if replace return

public enum CourseName {
    PHYSICS,
    CHEMISTRY,
    HISTORY,
    UKRAINIAN,
    ENGLSH,
    PROGRAMMING,
    PSYCHOLOGY,
    PHYLOSOPHY,
    OOP,
    COMPUTER_SCIENCE;
    private static final CourseName[] COURSE_NAMES = values();
    private static final int SIZE = COURSE_NAMES.length;
    private static final Random RANDOM = new Random();
    private static ArrayList<Integer> list = new ArrayList<>(SIZE);


    //can return same subject if: return COURSE_NAMES[RANDOM.nextInt(SIZE)];
    public static CourseName getRandomCourseName()  {
        return COURSE_NAMES[Rand(list)];
    }

    //want it to not return same subject by this method
    private static int Rand(ArrayList<Integer> list){
        for(int i = 1; i <= SIZE; i++) {
            list.add(i);
        }
        int index = RANDOM.nextInt(list.size());
        list.remove(index);
        return index;

    }
    public static String getRandomNameCourseAsString(){
        return String.valueOf(CourseName.getRandomCourseName());
    }
}