You have been given an array of size 2n+1 that have n pair of integers(can be +ve, -ve or 0) and one unpaired element.
How would you find the unpaired element.
Inspired by Raymond Chen's post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world stuff.
[1][2][3][4]
[5][6][7][8]
[9][0][1][2]
[3][4][5][6]
Becomes:
[3][9][5][1]
[4][0][6][2]
[5][1][7][3]
[6][2][8][4]
Update: Nick's answer is the most straightforward, but is there a way to do it better than n^2? What if the matrix was 10000x10000?
I have xml structure
all data comes here inside CDATA
I am using css file in it to format text and classes are mentioned in xml
Below is the code which shows data but does not format with CSS.
Thanks in advance!
var myXML:XML = new XML();
var myURLLoader:URLLoader = new URLLoader();
var myURLRequest:URLRequest = new URLRequest("test.xml");
myURLLoader.load(myURLRequest);
//////////////For CSS///////////////
var myCSS:StyleSheet = new StyleSheet();
var myCSSURLLoader:URLLoader = new URLLoader();
var myCSSURLRequest:URLRequest = new URLRequest("test.css");
myCSSURLLoader.load(myCSSURLRequest);
myCSSURLLoader.addEventListener(Event.COMPLETE,processXML);
var i:int;
var textHeight:int = 0;
var textPadding:int = 10;
var txtName:TextField = new TextField();
var myMov:MovieClip = new MovieClip();
var myMovGroup:MovieClip = new MovieClip();
var myArray:Array = new Array();
function processXML(e:Event):void
{
myXML = new XML(myURLLoader.data);
trace(myXML.person.length());
var total:int = myXML.person.length();
trace("total" + total);
for(i=0; i<total; i++)
{
myArray.push({name: myXML.person[i].name.toString()});
trace(myArray[i].name);
}
processCSS();
}
function processCSS():void
{
myCSS.parseCSS(myCSSURLLoader.data);
for(i=0; i<myXML.person.length(); i++)
{
myMov.addChild(textConvertion(myArray[i].name));
myMov.y = textHeight;
textHeight += myMov.height + textPadding;
trace("Text: "+myXML.person[i].name);
myMovGroup.addChild(myMov);
}
this.addChild(myMovGroup);
}
function textConvertion(textConverted:String)
{
var tc:TextField = new TextField();
tc.htmlText = textConverted;
tc.multiline = true;
tc.wordWrap = true;
tc.autoSize = TextFieldAutoSize.LEFT;
tc.selectable = true;
tc.y = textHeight;
textHeight += tc.height + textPadding;
tc.styleSheet = myCSS;
return tc;
}
According to their documentation, you should use Array hydration rather than record hydration when retrieving data for read-only purposes.
However, this means I have to access the attributes of the retrieved object using arrays and string keys:
$user['Phonenumbers'][0]['number']
instead of the OO style:
$user->PhoneNumbers[0]->number
Now I'm kinda new to PHP, but in other languages I've worked with the 2nd notation would be preferable because typos would be caught at compile time while typos in string literals would not be noticed until runtime. Does this apply to PHP/Doctrine?
In a ruby on rails app, I build an array of Project Names and project id values, but want to truncate the length of the names. Current code is:
names = active_projects.collect {|proj| [proj.name, proj.id]}
I have tried to add a truncate function to the block, but am getting undefined method for class error.
Thanks in advance - I just cannot wrap my head around this yet.
How to find maximum occuring integer(Mode) in an unsorted array of integers? One O(nlogn) approach I could think of is to sort. Is there any other best approach?
Hi,
I'm trying to insert a timestamp (hour:min:sec) into a two-byte array and i'm a little confused on how to accomplish this...any help is greatly appreciated!
int Hour = CTime::GetCurrentTime().GetHour();
int Minute = CTime::GetCurrentTime().GetMinute();
int Second = CTime::GetCurrentTime().GetSecond();
BYTE arry[2];
//Need to insert 'Hour', 'Minute', & 'Second' into 'arry'
Thanks!
I wanna fix a 2D board for a game. I've already fixed other panels for the gui and everything goes well. But the panel for the board cant be printed on the window. I'm a bit confused about it as i think i've followed the same ideas as for the others panels i need.
Here's what i've done:
/**
*Method used to construct the square in the area of the
*gui's grid. In this stage a GUISquare array is being constructed,
* used in the whole game as
*a mean of changing a square graphical state.
*@param squares is the squares array from whom the gui grid will be
*constructed.
*@see getSquare about the correspondance beetween a squareModel and
* a GUISquare.
*/
private void initBoardPanel(SquareModel[][] squares){
BoardPanel.setLayout(new GridLayout(myGame.getHeight(),myGame.getWidth())); //set layout
Squares=new GUISquare[myGame.getHeight()][myGame.getWidth()];
grid=new JPanel[myGame.getHeight()][myGame.getWidth()];
for (int i=0; i< myGame.getHeight(); i++){
for (int j=0; j<myGame.getWidth() ; j++){
grid[i][j] = new JPanel( );
GUISquare kout=new GUISquare(i,j);
kout.setSquare(myGame.getSquares()[i][j]);
kout.draw(myGame.getSquares()[i][j].getGoTo(),myGame.getSquares()[i][j].getNumber()); /*draw method is been called. the first parameter is the number of
the square that the player will be moved to if lands in this one
square,the second parameter is just the number of the square */
kout.setVisible(true);
grid[i][j].add(kout);
grid[i][j].setVisible(true);
BoardPanel.add(grid[i][j]);
BoardPanel.setVisible(true);
BoardPanel.setBackground(Color.WHITE);
GUISquare temp=this.getSquare(squares[i][i]);
Squares[i][j]= temp;
}
}
this.add(BoardPanel,BorderLayout.WEST);
// this.pack(); //sets appropriate size for frame
this.setVisible(true); //makes frame visible
}
/**
* Transformer for Rand/Move
* <br>This method is used to display a square on the screen.
*/
public void draw(int goTo ,int number) {
JPanel panel = new JPanel();
JLabel label1 = new JLabel(""+"Move To"+goTo);
JLabel label2 = new JLabel(""+number);
JSeparator CellSeparator = new JSeparator(orientation);
panel.add(CellSeparator);
panel.setLayout(new BorderLayout());
panel.add(label1, BorderLayout.CENTER);
panel.add(label2, BorderLayout.LINE_START);
}
I've posted only one draw method...but all versions are alike.
Can someone please write to me source code in Java? I have a task: create a program, that contains two dimensional array (with numbers) and the programm needs to sum zeros in each column and then get out the number of column in which the zeros are least.. thanks!
What's the simplest way of printing an array of primitives or of objects in Java? Here are some example inputs and outputs:
int[] intArray = new int[] {1, 2, 3, 4, 5};
//output: [1, 2, 3, 4, 5]
String[] strArray = new String[] {"John", "Mary", "Bob"};
//output: [John, Mary, Bob]
arr = ["red","green","yellow"]
arr2 = arr.clone
arr2[0].replace("blue")
puts arr.inspect
puts arr2.inspect
produces:
["blue", "green", "yellow"]
["blue", "green", "yellow"]
Is there anyway to do a deep copy of an array of strings, other than using Marshal as i understand that is a hack.
I could do:
arr2 = []
arr.each do |e|
arr2 << e.clone
end
but it doesn't seem very elegant, or efficient.
Thanks
I've got two entities, one named exercise and the other named workout. I would like to store several different exercises in each workout object.
What is the correct logic here? Create an array of exercises in each workout?
What is the difference between Object Literals and Array Literals in JavaScript? I know it has something to do with the length method but i don't fully understand it.
I have an table view, and the data source returns elements in the wrong order. So I have to reverse the elements in that array which returns the data for each row. How would I do that the most efficient way?
wondering if it is possible to use an array with Sass as I find my self repeating the following sort of thing:
.donkey
h2
background-color= !donkey
.giraffe
h2
background-color= !giraffe
.iguana
h2
background-color= !iguana
Hi!
I need to count number of repeating and position where they repeat of all number in multidimensional array like this:
1 2 1
1 1 2
2 3 1
And result need to be:
Number 1- two times on position 1, one time on position 2, two times on position 3
Number 2- one time on position 1, two times on position 2, one times on position 3
Number 3- 0 on position 1, one time on position 2, 0 on position 3
How i can do this? Thanks!
Hi guys:
Assume the JSON returned is
{"2010143545":{"info":[1,"soccer"]},
"2010143547":{"info":[0,"Basketball"]}
}
How do I use JQuery to render the array on ASP.NET page? More precisely, what kind of HTML template do I need to set to stuff the JSON with JQuey?
Thanks you.
I'm getting the following error in my ASP.net web page:
Invalid length for a Base-64 char array.
This happens when a user activates an ajax request before the previous request completes. How can I prevent this error fro occurring?
I am having a problem understanding how array.sort{|x,y| block} works exactly,hence how to use it?
ruby-doc example:
a = [ "d", "a", "e", "c", "b" ]
a.sort #=> ["a", "b", "c", "d", "e"]
a.sort {|x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]
thanks
Hi,
is there any possibility to send from formtastic form value of :string field like
- semantic_form_for :project do |form|
- form.inputs do
= form.input :task_ids, :as => :string
as Array? Currently value of this field is sending as String and i'd like to no parse this string in controller.
Also, could you give me idea - if task with submitted id is not found - what is best way to catch this situation - validation in controller or what?
I have an array (for checkboxes) that I need to pass alongside the regular form in an ajax post, but can't seem to get this to work:
new_data = [a,b,c,d,e];
somedata_assoc = JQuery.param({'choices[]': new_data});
$.ajax({
type: "POST",
url: contract_qurl,
data: $(div).find("form").serialize()+"&"+somedata_assoc,
context: $(this),
success: function(data) { $("#results_table").html(data); }
});
how to convert avi file to an jpg's images array using .net , i need to develop a task that will take the avi file and save it as jpg images on another folder
I have the following code:
public void setContent(Importer3D importer) {
if (DEBUG) {
System.out.println("Initialization of Mesh's arrays");
}
coords = importer.getCoords();
texCoords = importer.getTexCoords();
faces = importer.getFaces();
if (DEBUG) {
System.out.println("Applying Mesh's arrays");
}
mesh = new TriangleMesh();
mesh.getPoints().setAll(coords);
mesh.getTexCoords().setAll(texCoords);
mesh.getFaces().setAll(faces);
if (DEBUG) {
System.out.println("Initialization of the material");
}
initMaterial();
if (DEBUG) {
System.out.println("Setting the MeshView");
}
meshView.setMesh(mesh);
meshView.setMaterial(material);
meshView.setDrawMode(DrawMode.FILL);
if (DEBUG) {
System.out.println("Adding to 3D scene");
}
root3d.getChildren().clear();
root3d.getChildren().add(meshView);
if (DEBUG) {
System.out.println("3D model is ready!");
}
}
The Imporeter3D class part:
private void load(File file) {
stlLoader = new STLLoader(file);
}
public float[] getCoords() {
return stlLoader.getCoords();
}
public float[] getTexCoords() {
return stlLoader.getTexCoords();
}
public int[] getFaces() {
return stlLoader.getFaces();
}
The STLLoader:
public class STLLoader{
public STLLoader(File file) {
stlFile = new STLFile(file);
loadManager = stlFile.loadManager;
pointsArray = new PointsArray(stlFile);
texCoordsArray = new TexCoordsArray();
}
public float[] getCoords() {
return pointsArray.getPoints();
}
public float[] getTexCoords() {
return texCoordsArray.getTexCoords();
}
public int[] getFaces() {
return pointsArray.getFaces();
}
private STLFile stlFile;
private PointsArray pointsArray;
private TexCoordsArray texCoordsArray;
private FacesArray facesArray;
public SimpleBooleanProperty finished = new SimpleBooleanProperty(false);
public LoadManager loadManager;}
PointsArray file:
public class PointsArray {
public PointsArray(STLFile stlFile) {
this.stlFile = stlFile;
initPoints();
}
private void initPoints() {
ArrayList<Double> pointsList = stlFile.getPoints();
ArrayList<Double> uPointsList = new ArrayList<>();
faces = new int[pointsList.size()*2];
int n = 0;
for (Double d : pointsList) {
if (uPointsList.indexOf(d) == -1) {
uPointsList.add(d);
}
faces[n] = uPointsList.indexOf(d);
faces[++n] = 0;
n++;
}
int i = 0;
points = new float[uPointsList.size()];
for (Double d : uPointsList) {
points[i] = d.floatValue();
i++;
}
}
public float[] getPoints() {
return points;
}
public int[] getFaces() {
return faces;
}
private float[] points;
private int[] faces;
private STLFile stlFile;
public static boolean DEBUG = true;
}
And STLFile:
ArrayList<Double> coords = new ArrayList<>();
double temp;
private void readV(STLParser parser) {
for (int n = 0; n < 3; n++) {
if(!(parser.ttype==STLParser.TT_WORD && parser.sval.equals("vertex"))) {
System.err.println("Format Error:expecting 'vertex' on line " + parser.lineno());
} else {
if (parser.getNumber()) {
temp = parser.nval;
coords.add(temp);
if(DEBUG) {
System.out.println("Vertex:");
System.out.print("X=" + temp + " ");
}
if (parser.getNumber()) {
temp = parser.nval;
coords.add(temp);
if(DEBUG) {
System.out.print("Y=" + temp + " ");
}
if (parser.getNumber()) {
temp = parser.nval;
coords.add(temp);
if(DEBUG) {
System.out.println("Z=" + temp + " ");
}
readEOL(parser);
} else System.err.println("Format Error: expecting coordinate on line " + parser.lineno());
} else System.err.println("Format Error: expecting coordinate on line " + parser.lineno());
} else System.err.println("Format Error: expecting coordinate on line " + parser.lineno());
}
if (n < 2) {
try {
parser.nextToken();
} catch (IOException e) {
System.err.println("IO Error on line " + parser.lineno() + ": " + e.getMessage());
}
}
}
}
public ArrayList<Double> getPoints() {
return coords;
}
As a result of all of this code, I expected to get 3d model in MeshView. But the present result is very strange: everything works and in DEBUG mode I get 3d model is ready! from setContent(), and then unexpected ArrayIndexOutOfBoundsException:
File readed
Initialization of Mesh's arrays
Applying Mesh's arrays
Initialization of the material
Setting the MeshView
Adding to 3D scene
3D model is ready!
java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 32252
at com.sun.javafx.collections.ObservableFloatArrayImpl.rangeCheck(ObservableFloatArrayImpl.java:276)
at com.sun.javafx.collections.ObservableFloatArrayImpl.get(ObservableFloatArrayImpl.java:184)
at javafx.scene.shape.TriangleMesh.computeBounds(TriangleMesh.java:262)
at javafx.scene.shape.MeshView.impl_computeGeomBounds(MeshView.java:151)
at javafx.scene.Node.updateGeomBounds(Node.java:3497)
at javafx.scene.Node.getGeomBounds(Node.java:3450)
at javafx.scene.Node.getLocalBounds(Node.java:3432)
at javafx.scene.Node.updateTxBounds(Node.java:3510)
at javafx.scene.Node.getTransformedBounds(Node.java:3350)
at javafx.scene.Node.updateBounds(Node.java:516)
at javafx.scene.Parent.updateBounds(Parent.java:1668)
at javafx.scene.SubScene.updateBounds(SubScene.java:556)
at javafx.scene.Parent.updateBounds(Parent.java:1668)
at javafx.scene.Parent.updateBounds(Parent.java:1668)
at javafx.scene.Parent.updateBounds(Parent.java:1668)
at javafx.scene.Parent.updateBounds(Parent.java:1668)
at javafx.scene.Parent.updateBounds(Parent.java:1668)
at javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2309)
at com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:329)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:479)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:459)
at com.sun.javafx.tk.quantum.QuantumToolkit$13.run(QuantumToolkit.java:326)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$300(WinApplication.java:39)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:101)
at java.lang.Thread.run(Thread.java:724)
Exception in thread "JavaFX Application Thread" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 32252
at com.sun.javafx.collections.ObservableFloatArrayImpl.rangeCheck(ObservableFloatArrayImpl.java:276)
at com.sun.javafx.collections.ObservableFloatArrayImpl.get(ObservableFloatArrayImpl.java:184)
The stranger thing is that this stack doesn't stop until I close the program. And moreover it doesn't point to any my array. What is this? And why does it happen?