2017-10-16 1 views
-2

나는 일주일 동안이 대학 운동에 갇혀 있는데, 어떻게 해결할 지 모르겠습니다.배열을 사용자 입력에 따라 2 차원으로 나누는 방법은 무엇입니까?

연습은 단어를 쓰고 배열에 저장하는 사용자로 구성됩니다. 그런 다음 사용자는 숫자를 입력하고 프로그램은 사용자 번호 입력에 따라 단어 배열을 2 차원 배열로 나눕니다.

예 : 사용자가 "Car", "Truck", "Motorbike", "Cat", "Dog", "Bird"을 씁니다. 그리고 "3"을두고, 그래서 프로그램이 있습니다 :

["Car", "Truck", "Motorbike", "Cat", "Dog", "Bird"]

[["Car", "Truck", "Motorbike"] ["Cat", "Dog", "Bird"]] 

하고 사용자 입력 4 경우, 반환은 다음과 같아야합니다

[["Car", "Truck", "Motorbike", "Cat"] ["Dog", "Bird"]] 

편집 : 여기에 코드

이야
using System; 
using System.Collections; 

namespace probando_separar_arrays { 
    class Program { 
     static void Main(string[] args) { 
      int num, i = 0; 
      String pos; 
      ArrayList array = new ArrayList(); 
      do { 
       Console.Write("Please write a word: "); 
       pos = Console.ReadLine(); 
       array.Add(pos); 
      } while (!int.TryParse(pos, out num)); 
      Console.WriteLine("The input words are: "); 
      while (i < array.Count - 1) { 
       Console.WriteLine(array[i]); 
       i++; 
      } 
      /* Here is where I got stuck, cannot find a way to initialize the 
      * Bidimensional array 
      */ 
      Console.ReadKey(); 
     } 
    } 
} 
+7

가 어디 정확히 붙어있는가? 이것은 꽤 str8 앞으로 보인다. 당신이 시도한 (코드) 또는 정확한 질문이 아닌 전체 작업을 게시하십시오. 결국, 과제는 다른 사람의 해결책을 검증하지 않는 연습을위한 것입니다.) – DanteTheSmith

+2

갖고 계신 것을 보여주십시오. 우리가 당신을 위해 숙제를하면 아무에게도 도움이되지 않습니다. 우리는 도울 수 있습니다. – Amy

+0

배열을 여러 조각으로 나누려면 linq 메서드 skip() 및 take()를 사용할 수 있습니다. – jdweng

답변

1

Linq 사용해보기 :

using System.Linq; 

... 

// Let user input all the items in one go, e.g. 
// Car, Truck, Motorbike, Cat, Dog, Bird 
string[] source = Console 
    .ReadLine() 
    .Split(new char[] { ' ', '\t', ';', ',' }, StringSplitOptions.RemoveEmptyEntries); 

// size of the line; 
// simplest approach (Parse); int.TryParse is a better choice 
int n = int.Parse(Console.ReadLine()); 

// Let's create a jagged array with a help of modulo arithmetics: 
// source.Length/n + (source.Length % n == 0 ? 0 : 1) 
// we have "source.Length/n" complete lines and (possible) incomplete tail 
string[][] result = Enumerable 
    .Range(0, source.Length/n + (source.Length % n == 0 ? 0 : 1)) 
    .Select(index => source 
    .Skip(n * index) // skip index lines (each n items long) 
    .Take(n)   // take up to n items 
    .ToArray())  // materialize as array 
    .ToArray(); 

// finally, let's join the jagged array (line by line) into a single string 
string text = "[" + string.Join(" ", result 
    .Select(line => $"[{string.Join(", ", line)}]")) + "]"; 

Console.WriteLine(text); 

수입 :

Car, Truck, Motorbike, Cat, Dog, Bird 
4 

결과 : 여기

[[Car, Truck, Motorbike, Cat] [Dog, Bird]] 
0

당신이 원하는 않는 일반적인 방법 :

public static T[][] SplitArray<T>(T[] array, int size) { 
    // calculate how long the resulting array should be. 
    var finalArraySize = array.Length/size + 
     (array.Length % size == 0 ? 0 : 1); 
    var finalArray = new T[finalArraySize][]; 
    for (int i = 0 ; i < finalArraySize ; i++) { 
     // Skip the elements we already took and take new elements 
     var subArray = array.Skip(i * size).Take(size).ToArray(); // Take actually will return the rest of the array instead of throwing an exception when we try to take more than the array's elements 
     finalArray[i] = subArray; 
    } 
    return finalArray; 
} 
관련 문제