vendredi 31 juillet 2015

Rectangle intersection in Ruby

So I'm trying to understand this program but I'm having some difficulty. What I don't get in particular is the part with x_min, y_min, x_max, y_max. I get the the program passes through 2 rectangles with the bottom left and top right coordinate points. But where do the array indices come from? [0][0] , [1][1], etc? I'm confused about what's happening here exactly so if someone could break this down for me like I'm 5 that'd be awesome. I saw this particular question was answered before on here but I didn't get the explanation. Thanks.

    # Write a function, `rec_intersection(rect1, rect2)` and returns the
# intersection of the two.
#
# Rectangles are represented as a pair of coordinate-pairs: the
# bottom-left and top-right coordinates (given in `[x, y]` notation).
#
# Hint: You can calculate the left-most x coordinate of the
# intersection by taking the maximum of the left-most x coordinate of
# each rectangle. Likewise, you can calculate the top-most y
# coordinate of the intersection by taking the minimum of the top most
# y coordinate of each rectangle.
#
# Difficulty: 4/5
def rec_intersection(rect1, rect2)

x_min = [rect1[0][0], rect2[0][0]].max
x_max = [rect1[1][0], rect2[1][0]].min

y_min = [rect1[0][1], rect2[0][1]].max
y_max = [rect1[1][1], rect2[1][1]].min

return nil if ((x_max < x_min) || (y_max < y_min))
return [[x_min, y_min], [x_max, y_max]]
end

puts rec_intersection(
      [[0, 0], [2, 1]],
      [[1, 0], [3, 1]]
    ) == [[1, 0], [2, 1]]

puts rec_intersection(
      [[1, 1], [2, 2]],
      [[0, 0], [5, 5]]
    ) == [[1, 1], [2, 2]]


puts rec_intersection(
      [[1, 1], [2, 2]],
      [[4, 4], [5, 5]]
    ) == nil

puts rec_intersection(
      [[1, 1], [5, 4]],
      [[2, 2], [3, 5]]
    ) == [[2, 2], [3, 4]]

Why do I get an error just because I have a large array in swift?

I'm writing something in Swift and I have an array with some pre-calculated values which you can see below:

let pointArray = [[[185,350],8],[[248.142766340927,337.440122864078],5],[[301.67261889578,301.67261889578],5],[[337.440122864078,248.142766340927],5],[[350,185],8],[[327.371274561396,101.60083825503],5],[[301.67261889578,68.3273811042197],5],[[248.142766340927,32.5598771359224],5],[[185,20],8],[[101.60083825503,42.6287254386042],5],[[68.3273811042197,68.3273811042197],5],[[42.6287254386042,101.60083825503],5],[[20,185],8],[[32.5598771359224,248.142766340927],5],[[68.3273811042197,301.67261889578],8],[[101.60083825503,327.371274561396],5]]

My problem is that when compelling, I'm getting the following error:

Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions

I can't quite see why I'm getting this error because this is just an array with data - surely there isn't a maximum size for an array?

So my question is why am I getting the error? Is it just because the array is too large or maybe because there are many decimal points in the array?

Array of classes 'undefined' C++

So, I have a array of monsters and a function to display their names. The problem is the debugger says Mons(the array) is undefined. I'd like to know what I'm doing wrong. Please help! The errors are mostly Mons is undefined.

#include <iostream> 
#include <fstream>
#include <windows.h>
#include <time.h>

/**
RPG v0.1.6
-
**/

//-- WinAPI stuff
void ClearScreen()
  {
  HANDLE                     hStdOut;
  CONSOLE_SCREEN_BUFFER_INFO csbi;
  DWORD                      count;
  DWORD                      cellCount;
  COORD                      homeCoords = { 0, 0 };

  hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
  if (hStdOut == INVALID_HANDLE_VALUE) return;

  /* Get the number of cells in the current buffer */
  if (!GetConsoleScreenBufferInfo( hStdOut, &csbi )) return;
  cellCount = csbi.dwSize.X *csbi.dwSize.Y;

  /* Fill the entire buffer with spaces */
  if (!FillConsoleOutputCharacter(
    hStdOut,
    (TCHAR) ' ',
    cellCount,
    homeCoords,
    &count
    )) return;

  /* Fill the entire buffer with the current colors and attributes */
  if (!FillConsoleOutputAttribute(
    hStdOut,
    csbi.wAttributes,
    cellCount,
    homeCoords,
    &count
    )) return;

  /* Move the cursor home */
  SetConsoleCursorPosition( hStdOut, homeCoords );
  }



class Player {
    public:
    int HP;
    int MHP;
    int STR;
    int AGI;
    int RES;
    int XP;
    int LVL;
    Player() { HP = 8; MHP = 8; STR = 4; AGI = 3; RES = 2; XP = 0; LVL = 1; };
private:
};

struct DT {

void save_to_file(std::string filename, const Player& P)
{
    std::ofstream f( filename.c_str() );
    f << P.HP << std::endl;
    f << P.MHP << std::endl;
    f << P.STR << std::endl;
    f << P.AGI << std::endl;
    f << P.RES << std::endl;
    f << P.XP << std::endl;
    f << P.LVL << std::endl;
}

bool load_from_file(std::string filename, Player& P) {
  std::ifstream f( filename.c_str() );
  f >> P.HP;
  f >> P.MHP;
  f >> P.STR;
  f >> P.AGI;
  f >> P.RES;
  f >> P.XP;
  f >> P.LVL;
  if(f.good()){
    std::cout << "Success!" << std::endl;
  }
  else {
    std::cout << "Failure" << std::endl;
  }
  return f.good();
}

};

class Monster {
public:
    int HP;
    int MHP;
    int STR;
    int AGI;
    int RES;
    int XP;
    std::string name;
    ///For Calling
    Monster() { };
    ///Set variables for new battle
    Monster(int A, int B, int C, int D, int E, int F, std::string G){
    this->HP = A;
    this->MHP = B;
    this->STR = C;
    this->AGI = D;
    this->RES = E;
    this->XP = F;
    this->name = G;
    };
    void setStats(int A, int B, int C, int D, int E, int F, std::string G){
    this->HP = A;
    this->MHP = B;
    this->STR = C;
    this->AGI = D;
    this->RES = E;
    this->XP = F;
    this->name = G;
    };
};

int monstersalive = 3;




// -- Call Functions
void BtlDisplay(Player& P, Mons M[]);
void Battle(Player& P, Mons M[]);

int main()
{
    // -- Call Classes
    Player p;
    DT d;

    Monster Mons[3];
    for(int j = 0; j < 3; j++){
        Mons[j].setStats(9,9,9,9 + j,9,9,"Noob");
    }

    BtlDisplay(p,Mons);


    //Battle(p,m);


    d.save_to_file("GameData1.txt", p);
    d.save_to_file("GameData2.txt", p);
    d.save_to_file("GameData3.txt", p);



    return 0;
}

void BtlDisplay(Player& P, Mons M[]) //-- Displays battle stats
{
    ClearScreen();
    std::cout << "---------" << std::endl;
    std::cout << "L " << P.LVL << std::endl;
    std::cout << "HP " << P.HP << "/" << P.MHP << std::endl;
    std::cout << "---------\n\n" << std::endl;
    std::cout << "Monsters\n--------" << std::endl;
    for(int i = 0; i < 3; i++){
        if(M[i].HP > 0){

        }
    }
}

void Battle(Player& P, Mons M[])
{
    while(monstersalive > 0 && P.HP > 0){
        srand(time(NULL));
    }
}

IndexError: Too many indices when indexing array with another array

I realize a lot of people have asked about this error, but I have yet to find anything that will help me. I'm new to Python and working on some pretty high-level simulations, so up until now this website has been my best friend - now I could really use some help figuring out how to fix this error.

This is my code:

def nanalyze(pupil, pw_sim):
    import numpy as np

    temp_s = abs(pw_sim)**2 * pupil

    vals_x, vals_y = np.where(pupil > 0)
    mask = pupil[vals_x[0]:vals_x[len(vals_x)-1], vals_y[0]:vals_y[len(vals_y)-1]]

    s_i = (np.mean(temp_s[tuple(mask)]**2) / (np.mean(temp_s[tuple(mask)])**2)) - 1
    return s_i

The second-to -last line,s_i = (np.mean(temp_s[tuple(mask)]**2) / (np.mean(temp_s[tuple(mask)])**2)) - 1, is what returns the index error: too many indices.

pupil and pw_sim are each arrays of shape (1024,1024). temp_s is therefore also a (1024,1024) array and mask ends up being a (1023,1023) array. I've tried making mask a (1024,1024) to check and see if I'm getting the index error just because of the difference in shapes, but that doesn't seem to change anything. I cannot figure out what the problem is!

Reading A File and Storing It In An Object

I am trying to read from a file and store the contents into an object called ToDoList(from what I assume is under the GetItem method). Then I am supposed to allow the user to add on to the list. But I am lost on how to create the object and print it.

public class ToDoList {

private ToDoItem[] items;

ToDoItem td = new ToDoItem();
String inputline;
Scanner keyboard = new Scanner(System.in);

int i = 0;

String[] stringArray = new String[100];



private void setItems(ToDoItem[] items) throws FileNotFoundException {
    File file = new File("ToDoItems.txt");
    Scanner ReadFile = new Scanner(file);

    while (ReadFile.hasNext()) {
        String ListString = ReadFile.nextLine();
        stringArray[100] = (ListString);
    }
}

private ToDoItem[] getItems() {

    return items;
}

public void addItem(int id, String description) {
    stringArray[100] = (td.getId() + td.getDescription());

}

public String[] getAddItem() throws FileNotFoundException {

    try (PrintWriter fout = new PrintWriter(new File("ToDoItems.txt"))) {
        do {
            System.out.println("add to the list? [y/n]");
            inputline = keyboard.nextLine();

            if ("y".equals(inputline)) {
                i++;
                stringArray[i] = (td.getId() + ". " + td.getDescription() + "\n");
                fout.print(stringArray[i]);
            } else {

                System.out.println("Here is the list so far:");

            }
        } while ("y".equals(inputline));
        return stringArray;
    }
}

@Override
public String toString() {
    return "ToDoList{" + "items=" + getItems()
            + '}';
}

I am supposed to use the "getAddItem" method to allow the user to add to the list. But I can't figure out how to add an array to an object. let alone make the object.

PHP from string to multiple arrays at the hand of placeholders

Good day,

I have an I think rather odd question and I also do not really know how to ask this question.

I want to create a string variable that looks like this:

[car]Ford[/car]
[car]Dodge[/car]
[car]Chevrolet[/car]
[car]Corvette[/car]
[motorcycle]Yamaha[/motorcycle]
[motorcycle]Ducati[/motorcycle]
[motorcycle]Gilera[/motorcycle]
[motorcycle]Kawasaki[/motorcycle]

This should be processed and look like:

$variable = array(
                   'car'            =>           array(
                                                        'Ford',
                                                        'Dodge',
                                                        'Chevrolet',
                                                        'Corvette'
                                                      ),
                   'motorcycle'     =>           array(
                                                        'Yamaha',
                                                        'Ducati',
                                                        'Gilera',
                                                        'Kawasaki'
                                                      )
                  );

Does anyone know how to do this? And what is it called what I am trying to do?

How to check arrays for equality between multiple values?

So I'm trying to build a tic-tac-toe game that involves the user playing against a the computer. I would like these arrays to check for a winning sequence of blocks that will indicate someone has won the game. I'm wondering if this method of checking different parts of an array and comparing them for equality is valid?

function winner() {
    var blocks = document.getElementsByClassName('block');
    for (var i = 0; i < blocks.length; i++) {
        if (blocks[0, 1, 2].value == 'X' || blocks[0, 3, 6].value == 'X' || blocks[2, 5, 8].value == 'X' || blocks[6, 7, 8].value == 'X' || blocks[2, 4, 6].value == 'X' || blocks[0, 4, 8].value == 'X') {
            alert('Player X Wins!!');
            blocks.classList.toggle('block');
            player === 1;
        }
    };

    var blocks = document.getElementsByClassName('block');
    for (var i = 0; i < blocks.length; i++) {
        if (blocks[0, 1, 2].value == 'O' || blocks[0, 3, 6].value == 'O' || blocks[2, 5, 8].value == 'O' || blocks[6, 7, 8].value == 'O' || blocks[2, 4, 6].value == 'O' || blocks[0, 4, 8].value == 'O') {
            alert('Player O Wins!!');
            blocks.classList.toggle('block');
            player === 1;
        }

    }
}

Also, is this a viable way to dictate whose turn it is? I had a little success with this class switching mechanism to determine which blocks have been chosen in the beginning but can't seem to make it work now.

This is the code for changing turns and class switching so far but I'm sure there's a better way:

var player === 1

var blocks = document.getElementsByClassName('block');

function turn() {
    if (player === 1) {
        player -= 1;
        winner();
        var buttons = document.getElementsByTagName("button");
        console.log(buttons.length);
        for (var i = 0; i < buttons.length; i++) {
            buttons[i].addEventListener("click", function(e) {
                var number = (this.getAttribute('name'));
                var chosenblock = document.getElementsByName(number)[0];
                chosenblock.classList.toggle('chosen');
                chosenblock.value = 'X';
                // console.log('click!');
            });
        }
    } else {
        player += 1;
        winner();
        var computer;
        computer = function() {
                var computerchoice = Math.floor(Math.random() * (9) + 1);

                function compselected(number) {
                    //How to make number equal to the id of the selected block?
                    var chosenblock = document.getElementsByName(number)[0];
                    chosenblock.classlist.toggle('picked');
                }

Any advice is appreciated thanks guys! Here's the fiddle if that helps.